input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Is there a free/open-source JavaScript-to-JavaScript compacting compiler (like Google's)? <p>If you look at the source of Google pages with JavaScript, you'll find that the JavaScript is clearly not readable -- or maintainable. For example, all variables and functions are one-letter named (at least, the first 26 are...); there are no extraneous white-spaces or linebreaks; there are no comments; and so on.</p>
<p>The benefits of this compiler are clear: pages load faster, JavaScript execution is faster, and as a bonus, competitors will have a hard time understanding your obfuscated code.</p>
<p>Clearly, Google is using some sort of a JavaScript-to-JavaScript compacting compiler. I am wondering if what they're using is an in-house tool? If not, what <i>are</i> they using? Are there any publicly available (ideally, free/open-source) tools of that sort?</p>
| <p><a href="http://developer.yahoo.com/yui/compressor/" rel="nofollow">YUI Compressor</a> is a Java app that will compact and obfuscate your Javascript code. It is a Java app that you run from the command line (and would probably be part of a build process).</p>
<p>Another one is <a href="http://code.google.com/p/minify/" rel="nofollow">PHP Minify</a>, which does a similar thing.</p>
|
Error with Windows Installer ... "Unable to get installer types" <p>Good morning everyone,</p>
<p>I'm experiencing an error when using the windows installer to install an event source in a product I am deploying.</p>
<p>The error message I receive states the following ...</p>
<blockquote>
<p>Unable to get installer types in the
c:\temp\program.exe assembly. -->
Unable to load one or more of the
requested types. Retrieve the
LoaderExceptions property for more
information.</p>
</blockquote>
<p>Here is the block of code that creates the event source installer ...</p>
<pre><code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Diagnostics;
namespace myapplication
{
[RunInstaller(true)]
public partial class EventSourceInstaller : Installer
{
public EventSourceInstaller()
{
InitializeComponent();
string eventSourceName = "MyAppSourceName";
if (!EventLog.SourceExists(eventSourceName))
{
EventSourceCreationData data = new EventSourceCreationData(eventSourceName, "Application");
EventLog.CreateEventSource(data);
EventLog.WriteEntry(eventSourceName, "Source Added.");
}
}
}
}
</code></pre>
<p>In the installer project I've added a custom action on Install named "Primary output from MyApplication (Active)" to run the event source installer.</p>
<p>I have the following questions</p>
<p>1) Has anyone else run across this and what was the issue?</p>
<p>2) How do I go about retrieving the LoaderExceptions property of the installer?</p>
<p>Thank you in advance for any advice/assistance offered,</p>
<p>Scott Vercuski</p>
| <p>I have never seen that error, but the path c:\temp\program.exe is very strange. Are you trying to run the installer from the c:\temp\ directory?</p>
<p>Are you certain the output of all projects and all third-party DLLs you use are included in the Deployment project? Click on all included files in the Deployment project and check their SourcePath property; are they to the original source files and not the target output folder? Not the temp folder?</p>
|
Adobe air window with no chrome badly calculates dimensions when maximized <p>When i maximize an air window that has no chrome (no system chrome, no flex chrome but i think it's the same even if only flex chrome is used) a few pixels on all sides go offscreen. </p>
<p>Anyone has a solution for this or knows why it happens? </p>
| <p>It's actually easiest to set the air window to the size of the monitor, then set your custom UI to the size of the monitor minus a few pixels. That's the only workaround that I've come up with.</p>
<p>The only downside to this approach may be a small rendering performance loss, since the AIR window has to take alpha transparent pictures of everything behind the window, but this likely so minimal that it won't make a difference (I invite someone to benchmark this). </p>
|
What tools do I need to do Silverlight development? <p>I already own Visual Studio 2008 Team Version, and have an MSDN subscription...and I am an experienced ASP.Net developer.</p>
<p>What do I need to install to do Silverlight development, and can all of those tools be installed alongside my current "production" development machine (want to make sure there will not be any side effects).</p>
<p>I know I want to learn silverlight, but its not clear to me which tools are required and/or recommended in order to get started...</p>
<p>Thanks.</p>
| <p>Download the Silverlight 2.0 SDK and Visual Studio 2008 Tools</p>
<p>Microsoft® Silverlight⢠2 Software Development Kit</p>
<p>Microsoft® Silverlight⢠Tools for Visual Studio 2008 SP1</p>
<p>Check here for the links</p>
<p><a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=4E03409A-77F3-413F-B108-1243C243C4FE&displaylang=en" rel="nofollow">http://www.microsoft.com/downloads/details.aspx?FamilyId=4E03409A-77F3-413F-B108-1243C243C4FE&displaylang=en</a></p>
<p>Another great resource is the original:</p>
<p><a href="http://www.asp.net/downloads/" rel="nofollow">http://www.asp.net/downloads/</a>
AND
<a href="http://silverlight.net/GetStarted/" rel="nofollow">http://silverlight.net/GetStarted/</a></p>
<p>Hope this helps:
Andrew :-)</p>
|
Any new hope? Making a window an MDI child <p>Got some C# forms/controls that can be called up either from a C# control on a Winform in a Winforms MDI app OR the same C# control used by a PowerBuilder MDI app via COM.</p>
<p>I've been using the WinAPI call SetParent to attach forms to the MDI.</p>
<ol>
<li>It works (or seemed to) in both environments.</li>
<li>It lets the child window have its own WindowState (Normal, Maximised) instead of taking on that of the child windows already open (which was a real pain).</li>
</ol>
<p>Say the control is called T. Code on control T calls up form D.</p>
<p>Control T is on form X.<br />
Control T is also on form Y. </p>
<p>In .Net all is well, and form D stays within the MDI.</p>
<p>in PB:<br />
Control T is on PB control PX.
Control T is also on PB control PY. </p>
<p>For PX all is well.<br />
For PY, however, there is a problem - form D does not seem to become an MDI child - it can go outside the app and has a taskbar icon. I stress that this is using <em>same</em> objects as the ones that do work. The SetParent is literally the same line of code.</p>
<p>Further research has revealed that SetParent doesn't <em>really</em> work for proper MDI childing - but that's OK(ish) cos we don't need to merge menus etc.</p>
<p>Interestingly, have found that though SetParent seems to 'work', you don't get the handle back if you try GetParent...</p>
<pre><code>Form form = new MyForm();
WindowsMessageHelper.SetParent(form.Handle, MDIParentHandle); //passed down
int parentHandle = WindowsMessageHelper.GetParent(form.Handle);
</code></pre>
<p>parentHandle will always be 0....</p>
<p>Is there any way of making form D behave under all circumstances? My own researches have not been promising. I don't really want to go back and rewrite my forms as controls and have PowerBuilder manage them - mainly becasue there can be multiple instances of each form and PowerBuilder would have to handle that (instead of the controller class/base class I've got doing it in the .net app).</p>
<p>Can I stress that there is NO problem within .Net, the problem only shows up in the PowerBuilder app</p>
| <p>In the end, we found that the difference was that PB was doing the equivalent of setting .MDIParent for the control PX (the one where calling up form D worked) but not for PY. </p>
<p>Once that was sorted then we were then getting the correct MDIParent handle and all is now well.</p>
|
What language/tool should I use for HTML parsing? <p>I have a couple of websites that I want to extract data from and based on previous experiences, this isn't as easy as it sound. Why? Simply because the HTML pages I have to parse aren't properly formatted (missing closing tag, etc.).</p>
<p>Considering that I have no constraints regarding the technology, language or tool that I can use, <strong>what are your suggestions to easily parse and extract data from HTML pages</strong>? I have tried HTML Agility Pack, BeautifulSoup, and even these tools aren't perfect (HTML Agility Pack is buggy, and BeautifulSoup parsing engine doesn't work with the pages I am passing to it). </p>
<p>Thanks!</p>
| <p>You can use pretty much any language you like <strong>just don't try and parse HTML with regular expressions.</strong></p>
<p>So let me rephrase that and say: you can use any language you like that has a HTML parser, which is pretty much everything invented in the last 15-20 years.</p>
<p>If you're having issues with particular pages I suggest you look into repairing them with <a href="http://tidy.sourceforge.net/" rel="nofollow">HTML Tidy</a>.</p>
|
Javascript calling C# function under Silverlight <p>I have a Silverlight application using C#, with 2 main functions that I want to make accessible from JavaScript functions. I have done the RegisterScriptableObject() in the class and set-up the [ScriptableMember] for the functions I want access to.</p>
<p>This the Silverlight object:</p>
<pre><code><div id="silverlightControlHost">
<object id="silverlightControl" data="data:application/x-silverlight," type="application/x-silverlight-2" width="1024px" height="300px">
<param name="source" value="DrawingWaveForm.xap"/>
<param name="onerror" value="onSilverlightError" />
<param name="background" value="white" />
<param name="minRuntimeVersion" value="2.0.31005.0" />
<param name="autoUpgrade" value="true" />
<a href="http://go.microsoft.com/fwlink/?LinkID=124807" style="text-decoration: none;">
<img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none"/>
</a>
</object>
<iframe style='visibility:hidden;height:0;width:0;border:0px'></iframe>
</div>
</code></pre>
<p>and these are my JavaScript functions:</p>
<pre><code> function Start()
{
var control = document.getElementById("silverlightControl");
control.Content.Page.Start();
}
function Stop()
{
var control = document.getElementById("silverlightControl");
control.Content.Page.Stop();
}
</code></pre>
<p>Can anyone tell me where I'm going wrong as it does not seem to work</p>
| <p>As timheuer said, [Scriptable] on your Silverlight methods.</p>
<p>Call this in your class:</p>
<pre><code>HtmlPage.RegisterScriptableObject("Page", this);
</code></pre>
<p>Call the Silverlight methods marked as Scriptable from your javascript like this:</p>
<pre><code>function CenterMap(latitude, longitude)
{
var silvercontrol = document.getElementById("ctl00_cphMain_slControl");
if (silvercontrol)
silvercontrol.Content.Page.CenterOnCoordinates(latitude, longitude);
}
</code></pre>
<p><a href="http://blogs.vertigo.com/personal/ralph/Blog/archive/2008/05/15/call-silverlight-from-javascript-call-javascript-from-silverlight.aspx" rel="nofollow">This page</a> shows you this and how to do the reverse, calling javascript methods from Silverlight. It's a really nice model.</p>
|
Can I change a nested master page's master dynamically? <p>Okay, so we all know about changing a master page dynamically in a page's OnPreInit event.</p>
<p>But what about a nested master page? Can I change a master's master?</p>
<p>There is no OnPreInit event exposed in the MasterPage class.</p>
<p>Any ideas?</p>
| <p>Just tested this and it works from the PreInit of the Page that is using the nested MasterPage.</p>
<pre><code>protected void Page_PreInit(object sender, EventArgs e)
{
this.Master.MasterPageFile = "/Site2.Master";
}
</code></pre>
<p>Obviously you will need to ensure that the ContentPlaceholderIds are consistent across the pages you are swapping between.</p>
|
OnValidating Event in a custom control <p>When does the <code>OnValidate</code> event fire in the life-cycle of a control?</p>
<p>I'm creating a <code>DateBox</code> that will allow the user to enter a date in MM/DD/YYYY format (text) and need to verify that the date is in that format. It'll never be converted to a date (stored as string) but I would like to know the best time to validate that data (and provide feedback).</p>
<p>Note: It may seem a bit like re-inventing the wheel, but the app that I'm writing gets deployed to a tablet-pc and the winforms <code>DateTimePicker</code> is hell to edit with a stylus and my users just want to be able to write in the date.</p>
| <p><a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.aspx" rel="nofollow">MaskedTextBox Control</a> might help you.</p>
|
How to get users to pay attention to problems? <p>We occasionally need to notify users about warnings or problems. But often times, especially if it's a common problem, users will just dismiss the warning and continue. Often times users won't even remember seeing the warning, but we check their logs and see that several were displayed. So, how do you get users to pay attention when you're trying to tell them something important? </p>
<p>This isn't as simple as forcing users to resolve all problems before allowing them to save. They often need to save data that isn't strictly okay by our business rules for various reasons (usually for problems that can't be solved right away, or at all).</p>
<p>We've got a better warning/error handling system in mind that I think will help a lot, but I want to see what others have done.</p>
| <p>If you want users to pay attention to warnings, use them in moderation!</p>
<p>The big problem with the UAC in Vista is that people are getting so many notifications, that they stop reading <em>who</em> is exactly requesting access to <em>what</em>, they just give permission without thinking.</p>
<p>Another example is the delete confirmation in explorer when sending files to the recycle bin. I got so used to just hitting 'Ok' immediately after pressing 'delete', that I missed the fact that the dialog was telling me that the file would not be moved to the bin, but deleted immediately, for whatever reason. </p>
<p>My personal fix: I disabled the delete confirmation for the recycle bin. If something can not be moved to the bin, I still get a message, and this time I know that it might be important, so I pay attention.</p>
<p><strong>Conclusion:</strong> Don't spam the user with messages, or the important warnings will get lost in the noise.</p>
|
Setting non-canonical mode on stdin with Ruby <p>I'm playing around with making a simple terminal-based game with Ruby, and I'm currently trying to come up with a way of reading input from the terminal.</p>
<p>So far I've been using <code>gets</code>, but I'd like to have the game react instantly without requiring a newline (so you don't need to press a key, THEN enter).</p>
<p>I've figured out I need to put the terminal in non-canonical mode, and I'm assuming I can do that by calling <code>$stdin.ioctl</code>. The problem is, I'm not sure what arguments or flags I should be passing to this, and the documentation and searches just lead to information about the underlying C function.</p>
<p>Can anyone tell me what I should be calling <code>$stdin.ioctl</code> with? I'm using Terminal.app/tcsh on OSX Leopard.</p>
<p>Edit: This is what I ended up using, thanks to MarkusQ:</p>
<pre><code>%x{stty -icanon -echo}
key = STDIN.read(1)
</code></pre>
| <p>Your problem is outside of ruby. </p>
<p>Easiest answer: wrap your IO in %x{stty -raw echo} and %x{stty -raw echo} to change the mode with stty.</p>
<p>You'll probably want to do and ensure an exit handler to make certain the mode is set back when you exit.</p>
<p>-- MarkusQ</p>
|
Where should I implement functionality in Page object - constructor or OnPreInit? <p>A question I have been thinking about for a while - would Stackoverflow users commonly implement significant functionality in a constructor (specifically in classes derived from the System.Web.UI.Page class) , or should we keep the logic here as simple as possible and instead implement functionality in OnPreInit (using the constructor to simply instantiate objects/values that are required for the functionality in the rest of the page to function)? Is there a "best-practice" approach to this scenario?</p>
<p>The background to this question:</p>
<p>The system that I am working on has a fairly deep page hierarchy - there are about 10 chained page objects that the actual page derives from:</p>
<pre>
-- System.Web.UI.Page
----- CustomPage1 : System.Web.UI.Page
-------- CustomPage2 : CustomPage1
---------- etc
</pre>
<p>Each page adds a specific piece of functionality, and often there is either a dependancy on code run within the custom page constructor, or the functionality itself is directly run during construction.</p>
<p>The example that best illustrates my question is the page that loads custom objects from our database to the page so they are available during the page lifecycle - during page construction connections are made to the database and then public properties are populated with the correct values. </p>
<p>To my mind this is better done from the OnPreInit event, mainly because we have greater flexibility to perform some page level checks (e.g. should we want to prevent this functionality being called) before the parent logic is run (given that in a constructor the order of execution will construct the parent classes before the child class). From an OO perspective as well OnPreInit seems to be a more appropriate area to implement this functionality - page construction should deal with construction of the page, setting any default values, etc and then OnPreInit would be used to perform any functionality that was required during the lifecycle of the page.</p>
| <p>I think your reasoning is very sound - I agree that <code>OnPreInit</code> is the proper place for such logic.</p>
|
Oracle Trigger: raise_application_error <p>I want to use the raise_application_error-procedure to stop the login process.
I wrote a trigger, that checks the TERMINAL String, if it is right (I know that isn't realy secure, but at first, it is enough)
So the Trigger works fine and does what i want, but the raise_application_error causes an rollback and sends not the exception that I want. Whenn I log into the DB with my Application, the raise_application_error doesnt stop the app.
First question: Is this the right way, to stop logon the db with the wrong application?
Second question: If yes, what is wrong?</p>
<pre><code>create or replace
TRIGGER after_logon_on_database
AFTER LOGON ON DATABASE
BEGIN
IF sys_context('USERENV', 'TERMINAL')='IAS' THEN
INSERT INTO event_log
(event_date, event_time, username, event_case, event_comment)
VALUES
(SYSDATE, to_char(sysdate, 'hh24:mi:ss'), USER, 'LOGON-SUCCESS', sys_context('USERENV', 'TERMINAL'));
ELSE
INSERT INTO event_log
(event_date, event_time, username, event_case, event_comment)
VALUES
(SYSDATE, to_char(sysdate, 'hh24:mi:ss'), USER, 'LOGON-FAILURE', sys_context('USERENV', 'TERMINAL'));
RAISE_APPLICATION_ERROR(-20001, 'Access denied!');
END IF;
END after_logon_on_database;
</code></pre>
| <p>Read this ask tom-thread: <a href="http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:3236035522926" rel="nofollow">http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:3236035522926</a> </p>
|
svn externals not adding all files <p>We have an external app_code folder shared among multiple projects. I have noticed that when I do an svn update using tortoise svn that not all the files within the folder get added to my app_code working folder. If I delete the whole folder and do an update all files are added. This happens on all folders that are external. Any help on how to work around this problem would be great. We have quite a few files in this folder and it is a pain to have to delete it everytime we want to get newer files. </p>
<p>External definition:<br/>
app_code <a href="http://yversion/repos/app_code/Trunk" rel="nofollow">http://yversion/repos/app_code/Trunk</a><br/>
app_controls <a href="http://yversion/repos/app_controls/Trunk" rel="nofollow">http://yversion/repos/app_controls/Trunk</a> <br/>
app_themes <a href="http://yversion/repos/app_themes/Trunk" rel="nofollow">http://yversion/repos/app_themes/Trunk</a> <br/>
bin <a href="http://yversion/repos/bin/Trunk" rel="nofollow">http://yversion/repos/bin/Trunk</a> <br/>
pagesMaster <a href="http://yversion/repos/Masterpages/Trunk" rel="nofollow">http://yversion/repos/Masterpages/Trunk</a> <br/>
App_WebReferences <a href="http://yversion/repos/App_WebReferences/Trunk" rel="nofollow">http://yversion/repos/App_WebReferences/Trunk</a> <br/></p>
<p>Thanks<br/>
Royal</p>
| <p>Make sure that all your repositories have different uuids.</p>
|
"Program has exited with status 101" <p>Can someone give me a bit more information on this error please?</p>
<p>Console only logs
Program exited with status value:101.</p>
<p>If you imagine I have a nsmutablearray:</p>
<p><img src="http://farm4.static.flickr.com/3547/3301056092%5F8d3ab78225.jpg?v=0" alt="alt text" /></p>
<p>It holds TimeEntry objects:</p>
<pre><code> #import <Foundation/Foundation.h>
#import "Constants.h"
/*
#define KTimeEntryInformationKey @"TEInformation"
#define KTimeEntryFromKey @"TEFrom"
#define KTimeEntryToKey @"TETo"
*/
@interface TimeEntry : NSObject <NSCopying, NSCoding> {
NSDate *from;
NSDate *to;
NSString *information;
}
@property (nonatomic, retain) NSDate *from;
@property (nonatomic, retain) NSDate *to;
@property (nonatomic, copy) NSString *information;
@end
</code></pre>
<p>The app gives me the error only when I add 15-20+ TimeEntry objects to the array and gives me the error when the above viewController (pictured) is popped.</p>
| <p>I believe that's the result code when your program is automatically closed for using too much memory.</p>
<p>It's not a true crash, so it won't stop execution or invoke gdb.</p>
|
Castle Windsor: suppress exceptions thrown by Resolve() <p>When resolving a component which the Windsor container cannot find, an exception is thrown.</p>
<p>StructureMap has a TryGetInstance method, which returns null of it can't find the requested component.</p>
<p>Does Castle Windsor has something like this? Or am I forced to catch these exceptions (I don't like that, because of the performance overhead of throwing and catching exceptions).</p>
<p>Thanks in advance,</p>
<p>Remco</p>
| <p>You can check if the MicroKernel has an instance of the component registered before calling the Resolve method of the Windsor container.</p>
<p>Something like the following should work.</p>
<pre><code>if ( windsor.Kernel.HasComponent( componentType ) )
{
return windsor.Resolve( componentType );
}
return null;
</code></pre>
|
ASP.NET MVC jQuery migration from 1.2.6 to 1.3.2 <p>I have a problem with jQuery migration from 1.2.6 to 1.3.2 in my project. The intellisense for jQuery in VS doesn't work.</p>
<p>To test this issue I created new project, added jQuery to master page, built solution and checked intellisense - works OK.</p>
<p>After this I deleted in solution this files:</p>
<ul>
<li>jquery-1.2.6.js</li>
<li>jquery-1.2.6.min.js</li>
<li>jquery-1.2.6.min-vsdoc.js</li>
<li>jquery-1.2.6-vsdoc.js</li>
</ul>
<p>And added this:</p>
<ul>
<li>jquery-1.3.2.js</li>
<li>jquery-1.3.2.min.js</li>
<li>jquery-1.3.2.min-vsdoc.js</li>
<li>jquery-1.3.2-vsdoc.js</li>
</ul>
<p>I've corrected jQuery link in master page and build solution - intellisense for jQuery doesn't work.</p>
<p>What I have missed?</p>
<p>I use VS2008 SP1, MVC RC1.</p>
<p><strong>UPDATE:</strong>
Now all work OK. I don't sure about solution but I think intellisense was repared when I opened all js files in VS.</p>
<p><strong>SOLUTION</strong>
The reason was the conflict between jquery and jquery.ui
I've created empty vsdoc file for jquery.ui and the problem is eliminated.
I found this solution here:
<a href="http://arahuman.blogspot.com/2009/02/error-updating-jscript-intellisense.html" rel="nofollow">http://arahuman.blogspot.com/2009/02/error-updating-jscript-intellisense.html</a></p>
| <p>Actually, you have to install a new intellisense file. Check <a href="http://blogs.ipona.com/james/archive/2009/01/14/jquery-1.3-and-visual-studio-2008-intellisense.aspx" rel="nofollow">this</a> out. </p>
|
C# Begin/EndReceive - how do I read large data? <p>When reading data in chunks of say, 1024, how do I continue to read from a socket that receives a message bigger than 1024 bytes until there is no data left? Should I just use BeginReceive to read a packet's length prefix only, and then once that is retrieved, use Receive() (in the async thread) to read the rest of the packet? Or is there another way?</p>
<h2>edit:</h2>
<p>I thought Jon Skeet's link had the solution, but there is a bit of a speedbump with that code. The code I used is:</p>
<pre><code>public class StateObject
{
public Socket workSocket = null;
public const int BUFFER_SIZE = 1024;
public byte[] buffer = new byte[BUFFER_SIZE];
public StringBuilder sb = new StringBuilder();
}
public static void Read_Callback(IAsyncResult ar)
{
StateObject so = (StateObject) ar.AsyncState;
Socket s = so.workSocket;
int read = s.EndReceive(ar);
if (read > 0)
{
so.sb.Append(Encoding.ASCII.GetString(so.buffer, 0, read));
if (read == StateObject.BUFFER_SIZE)
{
s.BeginReceive(so.buffer, 0, StateObject.BUFFER_SIZE, 0,
new AyncCallback(Async_Send_Receive.Read_Callback), so);
return;
}
}
if (so.sb.Length > 0)
{
//All of the data has been read, so displays it to the console
string strContent;
strContent = so.sb.ToString();
Console.WriteLine(String.Format("Read {0} byte from socket" +
"data = {1} ", strContent.Length, strContent));
}
s.Close();
}
</code></pre>
<p>Now this corrected works fine most of the time, but it fails when <em>the packet's size is a multiple of the buffer</em>. The reason for this is if the buffer gets filled on a read it is assumed there is more data; but the same problem happens as before. A 2 byte buffer, for exmaple, gets filled twice on a 4 byte packet, and assumes there is more data. It then blocks because there is nothing left to read. <strong>The problem is that the receive function doesn't know when the end of the packet is.</strong></p>
<p><hr /></p>
<p>This got me thinking to two possible solutions: I could either have an end-of-packet delimiter or I could read the packet header to find the length and then receive exactly that amount (as I originally suggested).</p>
<p>There's problems with each of these, though. I don't like the idea of using a delimiter, as a user could somehow work that into a packet in an input string from the app and screw it up. It also just seems kinda sloppy to me.</p>
<p>The length header sounds ok, but I'm planning on using protocol buffers - I don't know the format of the data. Is there a length header? How many bytes is it? Would this be something I implement myself? Etc..</p>
<p>What should I do?</p>
| <p>No - call <code>BeginReceive</code> again from the callback handler, until <code>EndReceive</code> returns 0. Basically, you should keep on receiving asynchronously, assuming you want the fullest benefit of asynchronous IO.</p>
<p>If you look at the MSDN page for <a href="http://msdn.microsoft.com/en-us/library/dxkwh6zw.aspx"><code>Socket.BeginReceive</code></a> you'll see an example of this. (Admittedly it's not as easy to follow as it might be.)</p>
|
C# setting multiple properties through a single assignment <p>I have a property that is assigned as:</p>
<pre><code>public string propertyA{get;set;}
</code></pre>
<p>I want to call a method automatically when this property is set to assign another property in the class. Best way to trigger the call?</p>
| <p>You don't have to use that syntax that is just shorthand. If you expand it you can do whatever you like in the setter.</p>
<pre><code> public string PropertyA
{
get { return a; }
set
{
a = value;
doStuff();
}
}
</code></pre>
|
What is the best way to generate an ID for a SQL Insert? <p>What is the best, DBMS-independent way of generating an ID number that will be used immediately in an INSERT statement, keeping the IDs roughly in sequence?</p>
| <p>DBMS independent? That's a problem. The two most common methods are auto incrementing columns, and sequences, and most DBMSes do one or the other but not both. So the database independent way is to have another table with one column with one value that you lock, select, update, and unlock.</p>
<p>Usually I say "to hell with DBMS independence" and do it with sequences in PostgreSQL, or autoincrement columns in MySQL. For my purposes, supporting both is better than trying to find out one way that works everywhere.</p>
|
How can I return multiple rows as a single row in T-SQL? <p>A few months ago our vendor added a capability to our ticketing system which lets us add any number of custom fields to a ticket. I'd like to query these fields out along with the other call information for reporting purposes, but each extensible field is stored as a row in the database. So basically you have something like this:</p>
<pre><code>ext_doc_no call_record value
1 1001 Test
2 1001 test2
3 1001 moretest
</code></pre>
<p>What I'd like is to query back:</p>
<pre><code>1001 Test test2 moretest
</code></pre>
<p>I've tried to use PIVOT, but that's rather demanding about things like using an aggregate function. Any other ideas on how to do this? </p>
<p>EDIT: I also tried querying each row separately into the main query, and using a function... but both methods are way too slow. I need something to get all the rows at once, PIVOT them and then join into the main query.</p>
| <p>Try to look at <a href="http://stackoverflow.com/questions/488020/what-is-your-most-useful-sql-trick-to-avoid-writing-more-code/488897#488897">this answer</A>.</p>
<p>It does exactly what you want to do.</p>
|
What is the memory footprint for .NET Framework Compact Edition? <p>What is the memory footprint for .NET Framework Compact Edition? </p>
<p>Thanks.</p>
| <p>According to <a href="http://en.wikipedia.org/wiki/.NET%5FMicro%5FFramework" rel="nofollow">this wikipedia page</a>, it's about 12MB</p>
<p>But then again, <a href="http://msdn.microsoft.com/en-us/library/s6x0c3a4.aspx" rel="nofollow">this page</a> says it'll run in 128KB to 1MB.</p>
<p>My guess is that it's going to vary based on how much memory you have available and it'll swap pieces in and out of memory depending on circumstances. Quoting from the second link:</p>
<p><em>Random access memory (RAM) is used to store dynamic data structures and JIT-compiled code. The .NET Compact Framework uses available RAM, up to a limit specified by the device, to cache generated code and data structures and then frees the memory when appropriate.</em></p>
<p><em>The common language runtime uses a code-pitching technique to free blocks of JIT-compiled code at run time when memory is low. This enables larger programs to run on RAM-constrained systems with minimal performance penalty.</em></p>
|
How do I deregister an anonymous handler? <p>C# 2.0 has a neat feature called anonymous functions. This is intended to be used mostly with events: </p>
<pre><code>Button.Click += delegate(System.Object o, System.EventArgs e)
{ System.Windows.Forms.MessageBox.Show("Click!"); };
</code></pre>
<p>Now, suppose that Button is a static member, then adding delegates to it would count as unmanaged resources. Normally, I would have to deregister the handler before regestring it again. This is a pretty common use case for GUI programming. </p>
<p>What are the guidelines with anonymous functions? Does the framework deregrister it automatically? If so, when? </p>
| <p>No, anonymous functions will not get deregistered automatically. You should make sure to do it yourself, if the event should not be hooked up for the whole lifetime of your application.</p>
<p>To do this, of course, you would have to store the delegate reference, to be able to de-register it.
Something like:</p>
<pre><code>EventHandler handler = delegate(System.Object o, System.EventArgs e)
{ System.Windows.Forms.MessageBox.Show("Click!"); };
Button.Click += handler;
// ... program code
Button.Click -= handler;
</code></pre>
<p>Also, see <a href="http://stackoverflow.com/questions/183367/unsubscribe-anonymous-method-in-c">this question</a>.</p>
|
Performance implications of sql 'OR' conditions when one alternative is trivial? <p>I'm creating a stored procedure for searching some data in my database according to some criteria input by the user.</p>
<p>My sql code looks like this:</p>
<pre><code>Create Procedure mySearchProc
(
@IDCriteria bigint=null,
...
@MaxDateCriteria datetime=null
)
as
select Col1,...,Coln from MyTable
where (@IDCriteria is null or ID=@IDCriteria)
...
and (@MaxDateCriteria is null or Date<@MaxDateCriteria)
</code></pre>
<p><strong>Edit</strong> : I've around 20 possible parameters, and each combination of n non-null parameters can happen.</p>
<p>Is it ok performance-wise to write this kind of code? (I'm using MS SQL Server 2008)</p>
<p>Would generating SQL code containing only the needed where clauses be notably faster?</p>
| <p>OR clauses are notorious for causing performance issues mainly because they require table scans. If you can write the query without ORs you'll be better off.</p>
|
Calling .net assembly from vb6 results in runtime error 424 <p>I'm running into some trouble calling a .net assembly from vb6 and was hoping SO could help.</p>
<p>In VB.net I built a ComClass and kept the default constructor and GUIDs.
When deploying, I REGASM.exe the dll, which is located in the same folder as the VB6 exe. The .net dll references two other .net dll's, both of which are in the same folder. </p>
<p>I am trying to load the .net assembly using the VB6 function CreateObject(). When running the VB6 exe, I get the following error</p>
<pre><code> Run-time rror '424':
Object required
</code></pre>
<p>This is occuring on a Windows 2000 server. I am able to create the object on an XP box, however i'm not sure exactly how different the states of the two boxes are.</p>
<p>If anyone has any thoughts, it would be much appreciated. Thanks</p>
| <p>Try REGASM /CODEBASE. This allows you to load the dll where it is instead of the GAC.</p>
|
How to stop Flex / AIR XOR-ing a fill? <p>If you try the following code:</p>
<pre><code>g.beginFill(0xFF0000);
g.drawRect(0, 0, 50, 50);
g.drawRect(25, 25, 50, 50);
g.endFill();
</code></pre>
<p>You would think that it would draw 2 overlapping red squares. However, it doesn't - it draws two red squares except for the overlapping area which is now completely transparent.</p>
<p>Any idea how to get around this?</p>
<p><strong>Post-Accepted-Answer:</strong></p>
<p>Thanks <a href="http://stackoverflow.com/questions/583160/how-to-stop-flex-air-xor-ing-a-fill/583242#583242">Christophe Herreman</a>! Changing the code to:</p>
<pre><code>g.beginFill(0xFF0000);
g.drawRect(0, 0, 50, 50);
g.endFill();
g.beginFill(0xFF0000);
g.drawRect(25, 25, 50, 50);
g.endFill();
</code></pre>
<p>Worked just as intended! I'd be interested to know if this was "intended behaviour" or an actual bug though! </p>
| <p>All calls prior to endFill() will just store the points of the polygon you want to draw and connect them once endFill() is called. Since the code in your example has an overlapping part, it will be filtered out when the actual lines of the polygon are drawn. I actually don't know if this is intended behavior of the Flash player or a bug.</p>
<p>To solve this, just add a new call to beginFill() before drawing the new rectangle.</p>
<pre><code>g.beginFill(0xFF0000);
g.drawRect(0, 0, 50, 50);
g.beginFill(0xFF0000);
g.drawRect(25, 25, 50, 50);
g.endFill();
</code></pre>
|
how to exclude external jar while creating executable jar in eclipse or commandline? <p>I have written a program in Eclipse IDE which uses BouncyProvider class of BouncyCastle.jar. So to compile my class I added BouncyCastle.jar in my project classpath and it compiles perfectly.</p>
<p>Now I want to export my project as Runnable JAR so when I do that from Eclipse, it by default adds the classes of BouncyCastle.jar also in that runnable jar.</p>
<p>But I want to keep my application jar and BouncyCastle.jar different from each other. </p>
<p>How can I achieve this? Can anybody please help?</p>
| <p>It sounds like you want to use the "Export JAR File" wizard instead of the "Export Runnable JAR File" wizard. When exporting a <em>runnable</em> jar file, Eclipse attempts to pack everything needed to run the application into a single archive. On the other hand, the "Export JAR File" wizard gives you more control over what is packaged in the archive. You can still create a runnable jar file, but you must make sure to include BouncyCastle.jar on the classpath when you execute the jar. Here are step-by-step instructions:</p>
<ol>
<li>Click "File | Export". The Export
dialog pops up.</li>
<li>Expand the "Java" folder and select
"JAR file" (not "Runnable JAR
file"). Click Next. On the JAR file
specification page, choose the
classes you want included in the jar
file, and specify the name of the
JAR file to create. Click Next.</li>
<li>On the JAR Packaging Options page,
select options appropriate for you.
The defaults are probably fine.
Click Next.</li>
<li>On the JAR Manifest Specification,
<strong>make sure to select the "Main class" for your jar file</strong>. This is
the class that will be executed when
you execute the jar file. <strong>If you
leave this blank, the jar file will
not be runnable</strong>. Click Finish to
create the jar file.</li>
</ol>
<p>You should be able to execute the jar file by executing "<em>java -jar myjarfile.jar -classpath BouncyCastle.jar</em>" from a command line. </p>
|
SVN Merge Branch from one Repo into Trunk of other Repo <p>I have two repositories which live on separate servers, call them repo-1 and repo-2.</p>
<p>To start both "trunks" were equal:</p>
<p>repo-1/trunk == repo-2/trunk</p>
<p>Meanwhile changes were being commited to repo-1/trunk and I was working on and commiting changes to repo-2/trunk.</p>
<p>Now I need to merge changes from repo-1/trunk into repo-2/trunk.</p>
<p>I thought I would copy repo-1/trunk into repo-2/tags/r1_20090224, then merge that tag into my local working copy of repo-2/trunk (i.e. c:\dev\repo2-trunk).</p>
<p>Any suggestions on how to do this? I'm trying to use TortoiseSVN and performing "Merge two different trees", I used the following settings:</p>
<p>From: repo-2/trunk
To: repo-2/tags/r1_20090224
Working Copy: c:\dev\repo2-trunk</p>
<p>I also tried swapping the "from" and "to"...but no luck. By trying either of those two merge options I either end up with the following outcome:</p>
<ol>
<li><p>If I merge from trunk to tag (into my local copy of repo-2/trunk) I lose my trunk changes and get the tag changes.</p></li>
<li><p>If I merge from tag to trunk (into my local copy of repo-2/trunk) I lose my tag changes and keep my trunk changes.</p></li>
</ol>
<p>Any suggestions on to do this??</p>
| <p>First figure out the revision where the trees were the same. Then merge that from that revision to HEAD of the repo-1 repository to your repo-2 working copy.</p>
<p>Using the commandline client it's similar to this, if you want to merge changes between r123 and r456</p>
<pre><code>svn merge http://domain.tld/repos1@123 http://domain.tld/repos1@456 repos2-workingcopy
</code></pre>
|
SharePoint WebPart Permissions <p>Hi I am using the SharePoint namespace for a webpart and I encounter some permission errors when I try to use the System account. Is there a way I can use a defined user instead of the system account?</p>
<p>Right now I have:</p>
<pre><code>SPUserToken sysToken = SPContext.Current.Site.SystemAccount.UserToken;
using (SPSite site = new SPSite(_SPSite, sysToken))
</code></pre>
<p>I want to be able to use an account on the domain instead of the System account, thanks for any advice.</p>
| <p>You may need to use RunWithElevatedPermissions to get access to the System account to work, as per the following blog post:</p>
<p><a href="http://solutionizing.net/2009/01/06/elegant-spsite-elevation/" rel="nofollow">http://solutionizing.net/2009/01/06/elegant-spsite-elevation/</a></p>
|
GCC without Xcode on OS X <p>I've just unwrapped my new MacBook Pro (<em>yay</em>!) and am now setting it up properly for development. Since I want to avoid clutter, I'm wondering if I really need to install the Xcode tools at all (I never use the IDE or Mac specific tools), since I'll install a newer version of GCC anyway, using <a href="http://www.macports.org/">MacPorts</a>.</p>
<p>So, is there any benefit in installing Xcode? Is it necessary? What kind of set-up does it do behind the scenes? Basically: <strong>can I skip this or will it come back to haunt me because some Unix development tools just assume that OS X is always set up in this way?</strong></p>
| <p>In order to perform an easy and successful install of MacPorts, already having tools from the xCode installer is necessary. You only need the install option that places a copy of the unix/header files outside of xcode; everything else can remain uninstalled.</p>
|
Spring-modules caching not working... silently <p>I'm trying to use declarative caching from the Spring Modules project. </p>
<p>It's not working ie. nothing appears to be getting cached. </p>
<p>Here's my configuration:</p>
<pre><code><bean id="cacheManager"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
</bean>
<bean id="cacheProviderFacade"
class="org.springmodules.cache.provider.ehcache.EhCacheFacade">
<property name="cacheManager" ref="cacheManager" />
</bean>
<bean id="cacheableService"
class="org.springmodules.cache.interceptor.proxy.CacheProxyFactoryBean">
<property name="cacheProviderFacade" ref="cacheProviderFacade" />
<property name="cachingModels">
<props>
<prop key="get*">cacheName=default</prop>
</props>
</property>
<property name="flushingModels">
<props>
<prop key="update*">cacheNames=default</prop>
</props>
</property>
<property name="target" ref="myServiceBean" />
</bean>
</code></pre>
<p>And then, here's the logging from when Spring loads up the application context...</p>
<pre><code>24 Feb 2009 14:26:20,785 INFO org.springframework.cache.ehcache.EhCacheManagerFactoryBean - Initializing EHCache CacheManager
24 Feb 2009 14:26:20,801 DEBUG net.sf.ehcache.CacheManager - Configuring ehcache from classpath.
24 Feb 2009 14:26:20,801 WARN net.sf.ehcache.config.ConfigurationFactory - No configuration found. Configuring ehcache from ehcache-failsafe.xml found in the classpath: zip:C:/bea/weblogic81/server/bin/myserver/.wlnotdelete/extract/myserver_threeoneoneonline_threeoneoneonline/jarfiles/WEB-INF/lib/ehcache-1.3.0.jar!/ehcache-failsafe.xml
24 Feb 2009 14:26:20,801 DEBUG net.sf.ehcache.config.ConfigurationFactory - Configuring ehcache from URL: zip:C:/bea/weblogic81/server/bin/myserver/.wlnotdelete/extract/myserver_threeoneoneonline_threeoneoneonline/jarfiles/WEB-INF/lib/ehcache-1.3.0.jar!/ehcache-failsafe.xml
24 Feb 2009 14:26:20,801 DEBUG net.sf.ehcache.config.ConfigurationFactory - Configuring ehcache from InputStream
24 Feb 2009 14:26:20,816 DEBUG net.sf.ehcache.config.DiskStoreConfiguration - Disk Store Path: C:\DOCUME~1\bpapa\LOCALS~1\Temp\
24 Feb 2009 14:26:20,832 DEBUG net.sf.ehcache.config.ConfigurationHelper - No CacheManagerEventListenerFactory class specified. Skipping...
24 Feb 2009 14:26:20,832 DEBUG net.sf.ehcache.config.ConfigurationHelper - No CachePeerListenerFactoryConfiguration specified. Not configuring a CacheManagerPeerListener.
24 Feb 2009 14:26:20,847 DEBUG net.sf.ehcache.config.ConfigurationHelper - No CachePeerProviderFactoryConfiguration specified. Not configuring a CacheManagerPeerProvider.
24 Feb 2009 14:26:20,863 DEBUG net.sf.ehcache.config.ConfigurationHelper - No BootstrapCacheLoaderFactory class specified. Skipping...
</code></pre>
<p>After this, I hit a page that calls a method prefixed with "get" from the "myServiceBean" bean. But, nothing is logged that any caching is going on. I've turned logging all the way up to debug for springmodules, spring's cache package, and DEBUG... since Spring Modules examples are pretty few and far between on the web, I was wondering if anybody has seen this before...</p>
| <p>You should create an ehcache.xml file for your config since I don't believe the fail safe cache works with declarative caching. We set up our caching using the ehcache Spring modules XML schema and annotations. If using an explicit ehcache.xml does not solve your issue, then I can dig up some code that does it (close to) your way.</p>
|
How would I search through a DataSet and change data in it before it gets bound? <pre><code>Try
Dim ds As DataSet = SqlHelper.ExecuteDataset(ConfigurationManager.ConnectionStrings("connstr").ConnectionString, CommandType.StoredProcedure, "Get_All", New SqlParameter("@userid", Session("userid")))
rptBundles.DataSource = ds.Tables(0)
Catch ex As Exception
showerror(ex, Me)
End Try
</code></pre>
<p>That is the code, I want to be able to parse through it and find certain rows that have a certain boolean set to 1 and then edit other variables in that row accordingly, how would I do this, I tried making a For Each row nested in a For Each table but when I tested it the repeater never populates with data...</p>
<pre><code> For Each ds_table As DataTable In ds.Tables
For Each ds_row As DataRow In ds_table.Rows
If ds_row("isScorm") = 1 Then
ds_row("totalLessons") = 100
ds_row("TotalQuestions") = 100
ds_row("lessonscompleted") = 50
ds_row("TotalCorrect") = 50
End If
Next
Next
</code></pre>
<p>Only when I remove that code does the repeater populate as expected, but I got no errors!</p>
| <p>If you're using a Repeater, or whatever datasource bound control, I would use the ItemDataBound event and set those values to your controls.</p>
<p>If this was your basic HTML</p>
<pre><code><html>
<asp:Repeater id="repeater" runat="server" OnItemDataBound="repeater_ItemDatabound">
<ItemTemplate>
<span><%# DataBinder.Eval(Container.DataItem, "isScorm") %></span>
<span id="totalLessonsSpan" runat="server"><%# DataBinder.Eval(Container.DataItem, "totalLessons") %></span>
</ItemTemplate>
</asp:Repeater>
</html>
</code></pre>
<p>I would have this in the code behind</p>
<pre><code>protected void repeater_ItemDatabound(object sender, RepeaterItemEventArgs e)
{
DataRow row = e.Item.DataItem as DataRow;
if (row == null) { }
else
{
int isScorm = 0;
int.TryParse(Convert.ToString(row["isScorm"]), out isScorm);
if (isScorm > 0)
{
HtmlGenericControl totalLessonsSpan = e.Item.FindControl("totalLessonsSpan") as HtmlGenericControl;
totalLessonsSpan.Text = "100";
}
}
}
</code></pre>
<p>You probably don't want to loop through the data and swap it there, then bind when you can do it during the bind.</p>
<p>Alternately, something I hate that DB's do because of my need for data integrity, is change it in your SQL select with case statements.</p>
|
ASP.NET Gridview with all records editable <p>I thought this would be simple, but I sure am having a lot of trouble doing this:</p>
<p>The title of this question may be a bit misleading. I don't have to use a gridview. In fact, I know the GridView is probably not the way to go on this. I just didn't know how else to title it. But, for now just consider:</p>
<p>I have a very simple class called Student. It has 4 properties:
int ID
string FirstName
string LastName
string Email</p>
<p>I want to keep a generic collection of these in memory (session state):
List students;</p>
<p>Ok, now the problem:
I want the user to create as many of these Student objects as they want. For displaying these I just want a simple table of some kind with the 3 textboxes on each row. I would like every row to have textboxes insead of labels so that any record can be edited at anytime.</p>
<p>When the user is finished created their student objects, then they proceed on to do other things. But, I am just having trouble finding a way to display the records this way. Do I use the ListView(3.5), html table, gridview, repeater, etc.? </p>
<p>How would you do it?</p>
| <p>I would be inclined to use the ListView personally for this, since you can insert Rows with it. Your LayoutTemplate would be a table with a <tr runat="server" ID="itemPlaceHolder" /> in it. Your ItemTemplate would have your TextBox's (and optional a save button per row. Then you could have an InsertItemTemplate if you need inserts as well.</p>
<p>Anywhere on the page you can add a button to Save all items by looping through the ListView.Item collection and calling ListView.Update(itemIndex, validate).</p>
<pre><code><asp:ListView runat="server" ID="lv" InsertItemPosition="LastItem" DataKeyNames="id">
<LayoutTemplate>
<asp:LinkButton runat="server" OnClick="SaveAll" Text="Save All" />
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
<tr runat="server" id="itemPlaceHolder" />
</table>
<asp:LinkButton runat="server" OnClick="SaveAll" Text="Save All" />
</LayoutTemplate>
<ItemTemplate>
<tr>
<td><asp:TextBox runat="server" ID="firstName" Text='<%#Bind("firstName") %>' /></td>
<td><asp:TextBox runat="server" ID="firstName" Text='<%#Bind("lastName") %>' /></td>
<td><asp:TextBox runat="server" ID="firstName" Text='<%#Bind("email") %>' /></td>
<td><asp:LinkButton runat="server" CommandName="update" Text="Save" /></td>
</tr>
</ItemTemplate>
<InsertItemTemplate>
<tr>
<td><asp:TextBox runat="server" ID="firstName" Text='<%#Bind("firstName") %>' /></td>
<td><asp:TextBox runat="server" ID="firstName" Text='<%#Bind("lastName") %>' /></td>
<td><asp:TextBox runat="server" ID="firstName" Text='<%#Bind("email") %>' /></td>
<td><asp:LinkButton runat="server" CommandName="insert" Text="Save" /></td>
</tr>
</InsertItemTemplate>
</asp:ListView>
protected void SaveAll(object sender, EventArgs e)
{
lv.Items.ToList().ForEach(li => lv.UpdateItem(li.DataItemIndex, true)_;
}
</code></pre>
|
What is LenB actually doing on none string parameters <p>I have this bit of code that is being converted from vb6 to vb.net. I need to know what LenB is doing in this bit of code.</p>
<pre><code>Dim singleValue As Single 'var for conversion use(4byte -> 1single)'
Dim bytes() As Byte
Dim valueB() As Byte 'this gets set elsewhere and is redim-d to its size'
For n = 0 To CDbl(ItemNumberCombo.Text) - 1
'bytes() -> single'
'UPGRADE_ISSUE: LenB function is not supported.'
ReDim bytes(LenB(singleValue) - 1)
bytes(3) = valueB(n * 4)
bytes(2) = valueB(n * 4 + 1)
bytes(1) = valueB(n * 4 + 2)
bytes(0) = valueB(n * 4 + 3)
'UPGRADE_ISSUE: LenB function is not supported.'
'UPGRADE_ISSUE: VarPtr function is not supported. '
Call memcpy(VarPtr(singleValue), VarPtr(bytes(0)), LenB(singleValue))
'display the result'
DText(n).Text = VB6.Format(singleValue, "0.000000E+00") 'CStr(singleValue)'
If DataSaveCheckBox.CheckState = 1 And FileNameText.Text <> "" Then
csvOutput = csvOutput & DText(n).Text & ","
End If
Next n
</code></pre>
<p>Am I right in thinking that bytes is always ReDim'ed to the same size? By the looks of it 4 elements.</p>
<p>Why then use LenB to ReDim if you could just use a number? And why ReDim in the loop at all?</p>
| <p>LenB() returns the length in bytes of a variable. The most common example is for strings, where it returns the size of the string in bytes rather than the number of characters, regardless of character encoding. For other types it returns the size of an object- the size of a single being 4. The reason they would do this is that they wanted the code to survive if a future version of visual basic ever changed the size of a single (never mind hard-coding the number 4 when assigning to the byte array).</p>
<p>When upgrading LenB() to .Net, for strings use <code>System.Text.Encoding.Unicode.GetBytes()</code> to get an array already populated with your string text bytes. Remember that .Net always uses Unicode for strings internally. If you really need a different encoding there are a number of alternatives in the Encoding namespace. For other types use the <code>BitConverter</code> class. Either way, don't go line by line as the newer methods take away a lot of the busy work. </p>
<p>Here — I'll help you out with the conversion some:</p>
<p>(earlier)</p>
<pre><code>Dim csvOutput As New StringBuilder()
</code></pre>
<p>(later)</p>
<pre><code>Dim valueB() As Byte 'this gets set elsewhere and is redim-d to its size'
Dim singleValue As Single 'var for conversion
' Included because the original developer was concerned the size of a single could change
Dim singleSize As Integer = BitConverter.GetBytes(singleValue).Length
Dim NumberItems As Double
If Double.TryParse(ItemNumberCombo.Text, NumberItems) Then
For n As Integer = 0 To NumberItems - 1
singleValue = BitConverter.ToSingle(valueB, n * singleSize)
'display the result
DText(n).Text = singleValue.ToString("E6") 'CStr(singleValue)
If DataSaveCheckBox.CheckState = 1 AndAlso Not String.IsNullOrEmpty(FileNameText.Text) Then
csvOutput.Append(DText(n).Text & ",")
End If
Next n
Else
' Handle Invalid ComboBox value here- may not be an issue for you
End If
</code></pre>
<p>Note that this code also demonstrates a <code>StringBuilder</code> as a <em>much</em> better way to build your csv data, the <code>AndAlso</code> operator, the <code>.TryParse()</code> methods, <code>String.IsNullOrEmpty()</code>, and Standard Format Strings, all of which are intended to replace constructs or techniques from vb6.</p>
|
Linking classes in Geany <p>I am writing a CLI application for Linux in Geany (a C++ IDE). I want to link a simple config file reader class so it can be used in my program. Just including it doesn't work, I get undefined reference errors. I know how to do this in Dev-C++ on Windows, but not Geany. Thanks for helping!</p>
| <p>You are not linking in appropriate libraries. There must be something called Linker Options. Check the documentation out.</p>
|
Django development server shutdown error <p>Hey all,
Whenever i shut down my development server (./manage.py runserver) with CTRL+c i get following message:</p>
<pre><code>[24/Feb/2009 22:05:23] "GET /home/ HTTP/1.1" 200 1571
[24/Feb/2009 22:05:24] "GET /contact HTTP/1.1" 301 0
[24/Feb/2009 22:05:24] "GET /contact/ HTTP/1.1" 200 2377
^C
Error in atexit._run_exitfuncs:
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/atexit.py", line 24, in _run_exitfuncs
func(*targs, **kargs)
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/logging/__init__.py", line 1354, in shutdown
h.flush()
TypeError: flush() takes exactly 2 arguments (1 given)
Error in sys.exitfunc:
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/atexit.py", line 24, in _run_exitfuncs
func(*targs, **kargs)
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/logging/__init__.py", line 1354, in shutdown
h.flush()
TypeError: flush() takes exactly 2 arguments (1 given)
</code></pre>
<p>I recently moved the project to another directory, but everything else works fine, so i don't know if that has anything to do with it ...</p>
<p>If i just start the development server and then shut it down immediately, i do not see the error. Only when i click around some in the browser and then shut down the server...</p>
<p>Can anyone point me in the right direction to sort this one out plz? </p>
<p>Thanks in advance.</p>
| <p>It appears that you are using the Mac's default python install. I know this has been reputed to have odd issues from time to time. I would recommend install MacPython and installing Django into that python instance. </p>
|
If Quartz Scheduler dies, how do I stop the child Java processes that it started? <p>I'm currently using Quartz Scheduler as a replacement for Cron on our Windows 2003 Server Box.
I have two specific Jobs that needed to be started in a new VM, so I'm using the ProcessBuilder object in Java 5 to get my "Process" object.
The problem I'm running into is when our Quartz Scheduler JVM stops, the 2 jobs in separate JVM's keep going. </p>
<pre><code> Process process = Runtime.getRuntime().exec(command);
try
{
while (true)
{
Thread thread1 = new Thread(new ReaderThread(process.getInputStream()));
Thread thread2 = new Thread(new ReaderThread(process.getErrorStream()));
thread1.start();
thread2.start();
thread1.join();
thread2.join();
</code></pre>
<p>Is there a way to Kill these threads when the parent JVM associated with my Quartz Scheduler dies? Even if I knew of a way to kill them from a different process manually, I could figure out how to do it through Quartz.</p>
<p>Thank you in advance</p>
| <p>If the Quartz JVM exits normally, you can just destroy the processes in a finally block. This may obviate the need for a shutdown hook. A shutdown hook may not execute on abnormal JVM termination. The Runtime javadocs state, </p>
<blockquote>
<p>If the virtual machine aborts then no guarantee can be made about whether or not any shutdown hooks will be run. </p>
</blockquote>
<p>Here is the modified code (I've added a timeout and a method call to wait for the process to exit)</p>
<pre><code> private static final long TIMEOUT_MS = 60000;
Process process = Runtime.getRuntime().exec(command);
try
{
while (true)
{
Thread thread1 = new Thread(new ReaderThread(process.getInputStream()));
Thread thread2 = new Thread(new ReaderThread(process.getErrorStream()));
thread1.start();
thread2.start();
process.waitFor();
thread1.join(TIMEOUT_MS);
thread2.join(TIMEOUT_MS);
...
}
} finally {
process.destroy();
}
</code></pre>
<p>In general I've found that processes spawned from Java are clunky and not very resilient, as you've probably discovered given the need for the two ReaderThreads. In particular, subprocesses that freeze up can be difficult to terminate from within Java. As a last resort, you can use the Windows "<a href="http://technet.microsoft.com/en-us/library/bb491009.aspx" rel="nofollow">taskkill</a>" command to nuke the process from a command line or a scheduled task:</p>
<blockquote>
<p>taskkill /IM MySpawnedProcess.exe</p>
</blockquote>
|
Need to monitor directory change, and perform action <p>1st of all: I'm not programmer, neither Linux guru, just have to work with Linux, Oracle, shell scripts.</p>
<p>My current task is to monitor a table in Oracle (tool: sqlplus), and if it contains a certain row, then watch a linux directory for a growing tmp file, and log its attributes (e.g. <code>ls -l</code>), in every 5 second. </p>
<p>The most important part is: this tmp file will be deleted if the above record is deleted from the oracle table, and I need the last contents of this tmp file.</p>
<p>I can't control the Oracle data, just got query rights.</p>
<p>The available tools are: bash, awk, sed, some old version of perl, ruby (not 1.9*), and python (2.5). I don't have install rights, so most of the outside libraries are not accessible. I know I can run some libraries from my $HOME, but I don't have internet connection on that machine: so can't download any library. </p>
<p>Inotify is not available (older kernel).</p>
<p>Any idea where to start/how to do it? Thanks in advance.</p>
| <p>How about creating a hard link in another directory, then, when the file "disappears" in the original location, the hard link will still have access to the content.</p>
|
WebForm_SaveScrollPositionSubmit is undefined - ASP.NET <p>I'm upgrading an ASP.NET 1.1 app and have things working but am seeing the Javascript error referenced in the title. From research it appears that ASP.NET is not spitting out the javascript that is used to maintain scroll position between postbacks.</p>
<p>I did some googling and have checked the various issues mentioned but can't seem to find what might be going on.</p>
<p>Environment details:</p>
<ul>
<li>IIS 6 on Win Server 2003</li>
<li>The virtual directory is running ASP.NET 2.0.50727</li>
<li>I have set maintainScrollPositionOnPostBack="True" in the section of web.config</li>
</ul>
<p>Any ideas?</p>
| <p>Do you have any httphandlers or httpmodules that do any kind of request filtering or re-writing ? or anything special in global.asax that would prevent the javascript from coming down ? I would guess that something is blocking the built in axd request to get the javascript that deals with WebForm_SaveScrollPositionSubmit.</p>
<p>To find out for sure fire up <a href="http://www.fiddlertool.com/fiddler/" rel="nofollow">Fiddler</a> and watch the HTTP requests and make sure they are all happening correctly.</p>
<p>Also make sure there is at least 1 and only 1 form on the page.</p>
|
MulticastSocket not responding after failure <p>I get a SocketException when trying to call joinGroup(addr) on MulticastSocket. This is only happening on a Windows machine that we have setup to auto start our appliction when the machine is booted up.</p>
<p>It seems like the exception is thrown because Windows has not completely finished its startup process and here is the exception.</p>
<pre><code>java.net.SocketException: error setting options
at java.net.PlainDatagramSocketImpl.join(Native Method)
at java.net.PlainDatagramSocketImpl.join(Unknown Source)
at java.net.MulticastSocket.joinGroup(Unknown Source)
</code></pre>
<p>On startup of our app, if we wait a minute before trying to join the group, everything works fine.</p>
<p>So we decided to put in a retry loop so that it will connect as soon as the network is available which seemed to work. After two failures, the third attempt to join the group works.</p>
<p>The problem is, now the MulticastSocket does not receive any messages from the group, even though it joined up fine.</p>
<p>I am creating a new MulticastSocket after each failure and discarding the old one.</p>
<p>Why would a failure to join the group on one MulticastSocket affect the one that joined without any errors, and how could I possibly work around this?</p>
| <p>I never did find out WHY the socket would not recieve messages after joining the group successfully. I did come up with a work around, however.</p>
<p>I loop through all the network interfaces and make sure there is a valid one in the list and it is up and running. The next thing I do is try setting that network interface on a MulticastSocket. If these tests pass, then I let the socket try to join the group. It seems to work, but I still would like to know more about what is going on behind the scenes.</p>
<pre><code>private void validateNetworkInterfaces() throws IOException {
Enumeration nis = NetworkInterface.getNetworkInterfaces();
List<NetworkInterface> nics = new ArrayList<NetworkInterface>();
while (nis.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) nis.nextElement();
logger.debug("nic name: " + ni.getDisplayName());
logger.debug("nic isLoopback(): " + ni.isLoopback());
logger.debug("nic isPointToPoint(): " + ni.isPointToPoint());
logger.debug("nic isVirtual(): " + ni.isVirtual());
logger.debug("nic isUp(): " + ni.isUp());
logger.debug("nic supportsMulticast(): " + ni.supportsMulticast());
if (!ni.isLoopback() && !ni.isPointToPoint() && !ni.isVirtual() && ni.isUp() && ni.supportsMulticast()) {
logger.debug("adding nic: " + ni.getDisplayName());
nics.add(ni);
}
}
//check to make sure at least one network interface was found that supports multicast.
if (nics.size() == 0) throw new SocketException("No network interfaces were found that support multicast.");
//make sure the network interface can be set on a multicast socket
for (NetworkInterface nic : nics) {
logger.debug("attempting to set network interface on nic: " + nic.getDisplayName());
MulticastSocket ms1 = new MulticastSocket(45599);
ms1.setNetworkInterface(nic);
}
}
</code></pre>
|
Need loop to copy chunks from byte array <p>I have to process a large byte array that is passed to my function. I need to copy the content from this incoming byte array in smaller "chunks" to an outbound byte array.</p>
<p>For every "chunk" of data created in the outbound array, I need to call a web service.</p>
<p>Upon return, I need to resume looping through the incoming byte array, continuing to pass a whole or partial chunk of data until the complete incoming array is processed (i.e. sent to the web service in chunks).</p>
<p>I am very new to C# and I am struggling with a loop that works. I know how to call the web service to handle a "chunk" but I can't get the looping correct. Here is a sketch of the pathetic mess I currently have:</p>
<pre><code>int chunkSize = 10000;
byte[] outboundBuffer = new byte[chunkSize];
while (BytesRead > 0)
{
long i = 0;
foreach (byte x in incomingArray)
{
BytesRead += 1;
outboundBuffer[i] = incomingArray[i]
i++;
}
uploadObject.Size = BytesRead;
uploadObject.MTOMPayload = outboundBuffer;
// call web service here and pass the uploadObject
// get next "chunk" until incomingArray is fully processed
}
</code></pre>
<p>I know this is a mess and won't work; could someone sketch a proper loop to get this done? Thanks very much. </p>
| <p>You might want to look into <a href="http://msdn.microsoft.com/en-us/library/system.array.copy.aspx">Array.Copy</a> or <a href="http://msdn.microsoft.com/en-us/library/system.buffer.blockcopy.aspx">Buffer.BlockCopy</a>; this will clean things up a bit, since you won't have to copy all of the bytes individually:</p>
<pre><code>int incomingOffset = 0;
while(incomingOffset < incomingArray.Length)
{
int length =
Math.Min(outboundBuffer.Length, incomingArray.Length - incomingOffset);
// Changed from Array.Copy as per Marc's suggestion
Buffer.BlockCopy(incomingArray, incomingOffset,
outboundBuffer, 0,
length);
incomingOffset += length;
// Transmit outbound buffer
}
</code></pre>
|
Continuing a statement on the next line WITH A COMMENT <p>If I have a statement in Ruby that I want to continue on the next line, normally I would add a backslash at the end of the line like this:</p>
<pre><code>print x \
+ y
</code></pre>
<p>But if I have comments on the line, it doesn't work:</p>
<pre><code>print x #show x
+ y # show y
</code></pre>
<p>Is there a way around this?</p>
<p>(Edit: Squeegy's solution is correct and, actually, I knew you could do that but I was wondering particularly whether there is a way to have a comment on the same line as the backslash).</p>
| <p>You need to plus sign on the first line. I dont think comments work with the blackslash</p>
<pre><code>puts 'abc' + #Start abc
'def' #Add def
</code></pre>
|
Visual Studio 2008 Debugger Has Gone South <p>Dell Dimension 5621 - Win XP SP2 VS Studio 6.0 & 2008. We support ASP pages. </p>
<p>Usually I have had no problems using Visual Studio 2008 debugger with ASP pages from VStudio 6.0. In fact, up until last week, worked great. I was actually commenting to boss week ago wish that debugger had been around when VS 6.0 came out 10 years or so ago. </p>
<p>Then the system degraded. Started getting crashes with Debugger. Thought perhaps might be symantec AV. So I disabled those services. Now, when a bug happens, the debugger loads and ask me if I want to attach to dllhost.exe to debug. </p>
<p>You can attach or say no. If you attach, the system will debug; however, upon exiting will crash devenv.exe and kill most of the time the debugger and VS 6.0 sometimes which is annoying when your editing script based code to say the least. </p>
<p>Similiar to this issue this user reported here: </p>
<p>https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=352867</p>
<blockquote>
<p>Error: </p>
<p>AppName: devenv.exe AppVer: 9.0.30729.1 AppStamp:488f2b50</p>
<p>ModName: vsdebug.dll ModVer: 9.0.30729.1 ModStamp:488f2c04</p>
<p>fDebug: 0 Offset: 0001f1c2</p>
</blockquote>
<p>This system did not exhibit these issues up until about a week ago. As far as we are aware, there have been no changes to this system. Scanned with several AV programs as well. </p>
<p>When attaching to debugger: </p>
<blockquote>
<p>Attaching to this process can potentially harm your computer. If the information below looks suspicious or you are unsure, do not attach to this process. </p>
<p>Name: C:\Windows\system32\dllhost.exe</p>
<p>User: \IWAM_</p>
<p>Do you wish to attach to this process? </p>
<p>Attach Don't Attach. </p>
</blockquote>
<p>As far as I know nothing has been done to this system. We've scanned with AV programs and clean. I would think if this were a virus the debugger would never even fire up and/or the dllhost.exe would be reporting from the wins directory like I've read about dllhost.exe viruses. </p>
<p>Any suggestions would be helpful. Thank you. </p>
| <p>The standard <strong>bad</strong> answer usually is uninstall and then reinstall visual studio. Annoying answer too as it doesn't really explain what happened.</p>
|
asp.net Authorization: location and IPrincipal.IsInRole <h2>Scenario</h2>
<p>I'm using a Custom <code>IPrincipal</code> and <code>IIdentity</code> to do asp.net authorization. I set the <code>Principal</code> and <code>Identity</code> during the <code>PostAuthenticateRequest</code> event using an <code>IHttpModule</code>.</p>
<p>The web.config looks approximately like the following:</p>
<pre><code><system.web>
<authorization>
<allow verbs="GET,POST" roles="domain\group"/>
<deny verbs="*" users="*"/>
</authorization>
</system.web>
<location path="~/admin/user_search.aspx">
<system.web>
<authorization>
<allow verbs="GET,POST" roles="admin"/>
<deny verbs="*" users="*"/>
</authorization>
</system.web>
</location>
</code></pre>
<h2>The Problem</h2>
<p>When making a request the <code>IPrincipal.IsInRole</code> method gets called once to check <code>domain\group</code> but doesn't get called again to check the <code>admin</code> role. What is causing this? Do I have the <code>location</code> syntax incorrect or is there a deeper issue?</p>
<h2>Notes</h2>
<p>I thought initially that the web.config in the admin directory was overriding the web.config in the root directory, but I've tried removing it altogether as well as using it for the <code>location</code> element. Neither have worked so far.</p>
| <p>Don't use the tilde (~) at the start of paths for <location> elements, as they are not interpreted there. In your example, path="admin/user_search.aspx" should be correct.</p>
|
Visual Studio Builds per day <p>Is there any way to log the number of builds done during a development day in Visual Studio, or anywhere we can hook into something to get at the metadata?</p>
<p>I'm curious how many times on average I build/day * how long it takes per build... </p>
<p>Any thoughts?</p>
<p>UPDATE: sorry for the lack of details...and this exercise is purely academic</p>
<p>With a solution that has 14 different projects (1 is a web site). I am constantly building the entire solution (Ctrl + Shift + B). It would be interesting to find out not only the number of times I build during the day, but how much time is spent waiting for a build to complete...</p>
<p>The optimal solution would be one that doesn't require a change to the solution's projects itself. (pre/post build events) I don't want to have to add/undo changes before/after check-ins.</p>
<p>(The nant/other solution is sounding like the answer, I guess I could map that to a shortcut key and not have to leave VS to do the build)</p>
<p>Any other suggestions?</p>
| <p>One option would be to create a couple of scripts in your favorite scripting language and add them to the <em>pre and post build events</em> of the project settings.</p>
<p>Now every time you run a build the scripts will be run and you can have the scripts track whatever information you require.</p>
<p>But naturally this will only work at a <em>project level</em> and not automatically across all projects.</p>
|
ASP.NET: Button Outside UpdatePanel Fails to PostBack <p>I have a donation form that contains an update panel that contains a dropdown for predetermined amounts plus the "Other" option". When "Other" is selected the dropdown has triggered the partial postback and renders the update panel with the additional "Other" textbox for the amount. Outside this update panel I have a additional server control form fields such as textboxes and a button for submission.</p>
<p>The bug I run into is when "Other" is selected the button "onclick" event fails to fire a full postback.</p>
<p>Example:</p>
<pre><code><asp:UpdatePanel ID="updatePanelAmount" runat="server">
<ContentTemplate>
<table style="width: 500px;">
<tbody>
<tr>
<th style="width: 200px;"><asp:Label ID="lblAmount" runat="server" CssClass="required" Text="Donation Amount: " /></th>
<td>
<asp:DropDownList ID="selAmount" runat="server" />
<asp:CustomValidator ID="valDonationAmount" runat="server" ControlToValidate="selAmount" ErrorMessage="Donation Amount" Display="None" />
</td>
</tr>
</tbody>
</table>
<asp:Panel ID="panelOther" runat="server" Visible="false">
<table style="width: 500px;">
<tbody>
<tr>
<th style="width: 200px;"><asp:Label ID="lblOther" runat="server" Text="Other Amount: " /></th>
<td>
$<asp:TextBox ID="txtOther" runat="server" />
<asp:RequiredFieldValidator ID="valOther" runat="server" ControlToValidate="txtOther" Display="None" ErrorMessage="Other Amount" Enabled="false" />
<asp:RegularExpressionValidator ID="valOtherExpress" runat="server" ControlToValidate="txtOther" Display="None" ErrorMessage="Other Amount: Invalid" ValidationExpression="[1-9][0-9]+(\.[0-9]{2})?" Enabled="false" />
</td>
</tr>
</tbody>
</table>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
<ctl:CreditCardForm ID="ctlCreditCardForm" runat="server" />
<asp:Button ID="btnSubmit" runat="server" Text="Donate" />
</code></pre>
<p>EDIT: Posting the code-behind might make is easier for everyone</p>
<pre><code>public partial class _Default : System.Web.UI.Page
{
private ArrayList _donations;
protected void Page_Init(object sender, EventArgs e)
{
valDonationAmount.ServerValidate += new ServerValidateEventHandler(valDonationAmount_ServerValidate);
selAmount.AutoPostBack = true;
selAmount.SelectedIndexChanged += new EventHandler(selAmount_SelectedIndexChanged);
updatePanelAmount.UpdateMode = UpdatePanelUpdateMode.Conditional;
updatePanelAmount.ChildrenAsTriggers = true;
btnSubmit.Click += new EventHandler(btnSubmit_Click);
}
void selAmount_SelectedIndexChanged(object sender, EventArgs e)
{
if (selAmount.SelectedItem.Text == "Other")
{
panelOther.Visible = true;
valOther.Enabled = true;
valOtherExpress.Enabled = true;
}
else
{
panelOther.Visible = false;
valOther.Enabled = false;
valOtherExpress.Enabled = false;
}
}
void valDonationAmount_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = true;
if (args.Value == "0")
{
args.IsValid = false;
}
}
void btnSubmit_Click(object sender, EventArgs e)
{
Page.Validate();
if (Page.IsValid)
{
}
}
protected void Page_Load(object sender, EventArgs e)
{
_donations = new ArrayList();
double[] donations = new double[] { 20.00, 50.00, 100.00, 250.00, 500.00 };
_donations.AddRange(donations);
if (!IsPostBack)
{
foreach (Double d in _donations)
{
selAmount.Items.Add(new ListItem(String.Format("{0:c}", d), String.Format("{0:c}", d)));
}
selAmount.Items.Insert(0, new ListItem("Select Donation Amount","0"));
selAmount.Items.Add(new ListItem("Other", "Other"));
}
}
}
</code></pre>
| <p>Is this possibly a validator blocking you? Is your button supposed to ignore any validators? If so, you should set CausesValidation="false" on the button so that it will fire even if the validators in the panel are invalid.</p>
<p>Otherwise, the button's click event will be stopped by the validators in the panel.</p>
|
Unix O_CREAT flag without mode specified <p>The definition of the UNIX <em>open()</em> function when used with the O_CREAT flag is that it requires a third argument named <em>mode</em> in order to set the files' privileges. </p>
<p>What if that <em>mode</em> is not specified?</p>
<pre><code>int file;
static const char filename[] = "test.test";
if ((file = open(filename, O_RDWR | O_CREAT | O_TRUNC)) == 1)
{
perror("Error opening file.");
exit(EXIT_FAILURE);
}
close(file);
</code></pre>
<p>What happens with the file that is created using those flags? On my system I get:</p>
<pre><code>-r--r-s--- 1 hyperboreean hyperboreean 0 2009-02-25 01:40 test.test
</code></pre>
<p>A theory is that the open function looks on the stack and checks for the mode parameter and ends up using a random integer it finds.</p>
<p>What does the standard say about this?</p>
| <p>The POSIX standard (IEEE 1003.1:2008) prototypes <code>open()</code> as:</p>
<pre><code>int open(const char *path, int oflag, ...);
</code></pre>
<p>The section describing the behaviour of <code>O_CREAT</code> doesn't say what will happen if you omit the necessary third argument, which means the behaviour is undefined - anything is possible.</p>
<p>In practice, the use of part of the stack that was intended to be stack frame or return address or something similar is quite likely - unto a reasonable approximation, that can be considered a random integer.</p>
<p>The <a href="http://www.opengroup.org/onlinepubs/9699919799/toc.htm">POSIX 2008</a> standard has some interesting new (and useful) flags for <code>open()</code>, including:</p>
<ul>
<li><code>O_FDCLOEXEC</code> to specify close-on-exec at open.</li>
<li><code>O_DIRECTORY</code> to specify that the file must be a directory.</li>
<li><code>O_NOFOLLOW</code> to specify not to chase symlinks.</li>
</ul>
|
Using Excel (Or Calc) as a web-app frontend or embedded widget <p><strong>Problem:</strong> When dealing with web-applications that require grid-based input (but is not a fullblown spreadsheet like Google's) there is a common problem. Either the web-GUI sucks, or it is tied behind some heavily-specialized API that takes way too much training and time to use effectively (not to mention the price tag tends to be high for these kinds of things).</p>
<p><strong><em>Question</em>:</strong> Assuming all the target users have Excel or OpenOffice (or can be told to get a copy) has anyone out there tried using a spreadsheet as an input form for a live web application?</p>
<p><strong>Scenario:</strong> User X comes to your website, she gets to a page where she downloads a spreadsheet to continue some complex number crunching in the midst of using your webapp. When she is done, she presses a button on your specially constructed spreadsheet, and the spreadsheet itself submits its payload via POST to your website, then the website does whatever with the recently-crunched numbers.</p>
<p><strong>Motivation:</strong> The motivation for this question stems from huge frustration with all the various "grid control" widgets out there for use in web pages. They either are not enough, or not sufficiently capable of being "embedded" as a control in a web page.</p>
| <p>This is common practice for data-heavy intranet applications. In the past, you would have used VB for Applications. Today, the Open XML SDK offers a very elegant way of hooking into the open and close events of the document. Excel will execute your managed code upon open (to populate the spreadsheet) and upon close/save (to extract the data from the spreadsheet and write it back to the database).
The Excel document can be served from a Web server that does not need to have Office installed.</p>
|
Looking for a radial coordinates description of gear teeth <p>I don't need a physically accurate function, but something that hints at the involute curves, etc. I was just using <code>r = 2 + sin^2</code>, which gets the idea across, but it looks like - ahem. Googling around, you can find plenty of information on how to draft a 'correct' gear, but nothing in the way of a bare-bones approximation.</p>
<p>EDIT: The 'look' that I'm after: <a href="http://www.cartertools.com/involute.html" rel="nofollow">http://www.cartertools.com/involute.html</a></p>
| <pre><code>from pylab import *
nteeth = 30
inner = 10
outer = 12
# these are in teeth-hundredths, but half the actual measurement
bottom_width = 22
top_width = 15
def involute_r(angle):
'''angle is given in teeth-hundredths'''
angle = angle % 100
if angle > 50:
# symmetry
angle = 100 - angle
if angle < bottom_width:
return inner
if angle > (50 - top_width):
return outer
halfway = (inner + outer) / 2.0
transition_width = 50 - top_width - bottom_width
curve = 1.0 - (angle - (50 - top_width))**2 / (transition_width ** 2)
return halfway + curve * (outer - halfway)
fig = figure()
ax = fig.add_subplot(111, polar=True)
theta = np.arange(0, 2*pi, 0.001)
r = [involute_r(t * nteeth * 100 / (2 * pi)) for t in theta]
ax.plot(theta, r)
ax.set_ylim(inner, outer+1)
show()
</code></pre>
|
How do I make an HTML element repaint within a Javascript loop? <p>I have some Javascript which "animates" a colour change on an HTML element, as follows:</p>
<pre><code>var element = document.getElementById("someid");
while (i < 255) {
element.style.color = 'rgb(' + i + ',' + i + ',' + i + ')';
i++;
slowMeDown(); // This function runs for a few ms to slow the process down
}
</code></pre>
<p>As you can see, this changes the color from black to white going through 255 shades of grey in between. I would like to make it visibly "fade" so that the user can see the text gradually disappear.</p>
<p>However, the browser (Chrome and IE - not tested on Firefox yet) only refreshes at the end of the function, so the color simply changes from black to white. Does anyone know how to make the browser repaint during the loop so that I can see the text fade?</p>
| <pre><code>function changeColor()
{
changeColorIncremental(0);
}
function changeColorIncremental(i)
{
var element = document.getElementById("someid");
element.style.color = 'rgb(' + i + ',' + i + ',' + i + ')';
if (i < 255) {
// Note the 50 millisecond wait below. Decrease this to speed up
// the transition, and increase it to slow it down.
setTimeout('changeColorIncremental(' + (i + 1) + ')', 50);
}
}
</code></pre>
|
Why are there self-duplicating curly brackets in persisted WPF RichTextBox? <p>Our tester threw curly brackets at our persisting WPF RichTextBoxes. On save and reopen, there are magically more curly brackets.</p>
<p>I've condensed the issue / code down.</p>
<pre><code><Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<RichTextBox x:Name="rtb1" />
<Button Grid.Row="1" Click="Button_Click">Draw a fish</Button>
<RichTextBox x:Name="rtb2" Grid.Row="2"/>
</Grid>
</Window>
</code></pre>
<p>Two rich text boxes. On button click, the bottom one gets set to the result of the first one after persist and restore.</p>
<pre><code>namespace WpfApplication1
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
rtb1.Document = new FlowDocument(new Paragraph(new Run("{")));
}
public static FlowDocument CreateFlowDocumentFromByteArray(byte[] byteArray)
{
return (FlowDocument)XamlReader.Load(new MemoryStream(byteArray));
}
public static byte[] CreateByteArrayFromFlowDocument(FlowDocument flowDocument)
{
MemoryStream mStream = new MemoryStream();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = false;
settings.OmitXmlDeclaration = true;
XamlDesignerSerializationManager dsm = new XamlDesignerSerializationManager(XmlWriter.Create(mStream, settings));
dsm.XamlWriterMode = XamlWriterMode.Value;
XamlWriter.Save(flowDocument, dsm);
mStream.Close();
return mStream.ToArray();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
rtb2.Document = CreateFlowDocumentFromByteArray(CreateByteArrayFromFlowDocument(rtb1.Document));
}
}
}
</code></pre>
<p>Why is this happening? How do we stop it?</p>
| <p>I'll test the code more thoroughly tonight, but does it happen when the braces are not at the start of the text? E.g., if your run was "Hello{World}" does it still do this?</p>
<p>As you probably know, curly braces are significant in WPF because they are used for markup extensions. The following markup wouldn't work:</p>
<pre><code><Button Content="{Hello}" />
</code></pre>
<p>To get the right output, you'd usually escape it with:</p>
<pre><code><Button Content="{}{Hello}" />
</code></pre>
<p>Since you're using XamlReader.Load, there may be some confusion around the use of {}'s in the XAML, so they are being escaped. But that's just a guess. Out of interest, what does the XAML which is written out look like? </p>
|
Code Contracts, will you use them? <p>Microsoft just released <a href="http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx" rel="nofollow">Code Contracts</a>, a tool that integrates with Visual Studio and allows you to define contracts for your .Net code and get runtime <em>and</em> compile time checking.</p>
<p>Watch the <a href="http://channel9.msdn.com/posts/Peli/Getting-started-with-Code-Contracts-in-Visual-Studio-2008/" rel="nofollow">video on Channel 9</a> that shows how it being used.</p>
<p>For now it's an add-on but it will be part of the Base Class Library in .Net 4.0</p>
<p>Is this something you see yourself using?</p>
<p>I wonder if this means the death of <a href="http://research.microsoft.com/en-us/projects/specsharp/" rel="nofollow">Spec#</a>?</p>
<p><strong>Update</strong></p>
<p>What I mean by the death of Spec# is that we now have 2 different projects for writing contracts:<br />
Spec# is an evolution of C# and it introduces new keywords and behaviours; on the other hand, what Microsoft just released is a library that can be used with any .Net language.<br />
Since the latter looks like it's going to become the de-facto standard, I wonder where that leaves Spec#</p>
| <p>I think the majority of developers using c# 4.0 will use them myself included especially when creating a library that you plan to expose to anyone. It may make your code more verbose in areas but the advantages it has should outweigh the lines of code and time spent.</p>
|
Why does my repeater keep crashing on Eval(NULL) values? <pre><code><asp:Repeater ID="rptLessons" runat="server">
<ItemTemplate>
<tr>
<td><%#Eval("fullname")%></td>
<td><%#isCompleted(Eval("totallessons"), Eval("completedlessons"), Eval("totalNumAvail"), Eval("totalNumCorrect"))%></td>
<td><%#FormatPercent(Eval("totalnumcorrect") / Eval("totalNumAvail"))%> <%-- (<%#Eval("totalnumcorrect")%> / <%#Eval("totalNumAvail")%>) --%></td>
<td><%#FormatPercent(Eval("completedlessons") / Eval("totallessons"))%> <%-- (<%#Eval("completedlessons")%> / <%#Eval("totallessons")%>) --%></td>
<td><%#Eval("lastaccessed")%></td>
</tr>
</ItemTemplate>
</asp:Repeater>
</code></pre>
<p>I can't figure it out but as soon as it hits some NULL data it refuses to move on to drawing the next elements.</p>
| <p>You need to give a stack trace to be sure.</p>
<p>But I can see several issues:</p>
<ol>
<li>DIV#0 errors inside FormatPercent</li>
<li>NULL errors.</li>
</ol>
<p>Example Solution</p>
<p><%#isCompleted(System.Convert.ToInt32(Eval("totallessons")), System.Convert.ToInt32(Eval("completedlessons")), System.Convert.ToInt32(Eval("totalNumAvail")), System.Convert.ToInt32(Eval("totalNumCorrect")))%></p>
<p>(System.Convert.ToInt32 should convert DBNull/NULL to 0)</p>
<p>Or alter isCompleted to accept Object paramters and do your NULL / DBNull checking inside the function.</p>
|
Test whether a property is declared in the derived class <p>I have two classes</p>
<pre><code>public class A
{
public int BaseA
{get;set;}
}
public Class B: A
{
public int BaseB
{get;set;}
}
</code></pre>
<p>I can get the Properties for the Class B by using typeof(B).GetProperties(). However, this would include both the BaseA and BaseB properties. But I want to obtain the BaseB property only. </p>
<p>Note: I found the solution, it's </p>
<pre><code> B boy = new B();
var pList = boy.GetType().GetProperties(BindingFlags.Public |
BindingFlags.DeclaredOnly |
BindingFlags.Instance);
Assert.AreEqual(1, pList.Length);
</code></pre>
<p>A similar solution <a href="http://stackoverflow.com/questions/245401/how-do-i-get-the-properties-of-an-object-using-reflection">can be found here</a>. </p>
| <p>Look at using BindingFlags.DeclaredOnly when calling Type.GetProperties().</p>
|
How would I get a cron job to run every 30 minutes? <p>I'm looking to add a <code>crontab</code> entry to execute a script every 30 minutes, on the hour and 30 minutes past the hour or something close. I have the following, but it doesn't seem to run on 0.</p>
<pre><code>*/30 * * * *
</code></pre>
<p>What string do I need to use?</p>
<p>The cron is running on OSX.</p>
| <p>Do:</p>
<pre><code>0,30 * * * * your_command
</code></pre>
|
How to hide back button in the first view on iPhone? <p>I add 3 views for an application and they need to switch from 1-2-3.</p>
<p>Now I add a toolBar and a button 'OK' on the bottom of SwitchViewController, so they can share the button to go to next view. </p>
<p>But how to add a 'Back' button so that I can switch from 2-1 or 3-2 and the button shouldn't be seen in the first view?
Are there any other ways to switch views without sharing the same tool bar button?</p>
| <p>It sounds like what you're trying to do is use a UINavigationController. If you instantiate a UINavigationController with the <code>initWithRootViewController</code> initializer you can pass it your first UIViewController. Then you just need to tie whatever action you want to a method that calls <code>[myUINavigationController pushViewController:myOtherViewController animated:YES]</code> to get it to slide over to the second view. The UINavigationController will automatically set up the UINavigationBar and back button you are looking for. </p>
|
How do you perform a left outer join using linq extension methods <p>Assuming I have a left outer join as such:</p>
<pre><code>from f in Foo
join b in Bar on f.Foo_Id equals b.Foo_Id into g
from result in g.DefaultIfEmpty()
select new { Foo = f, Bar = result }
</code></pre>
<p>How would I express the same task using extension methods? E.g.</p>
<pre><code>Foo.GroupJoin(Bar, f => f.Foo_Id, b => b.Foo_Id, (f,b) => ???)
.Select(???)
</code></pre>
| <pre><code>var qry = Foo.GroupJoin(
Bar,
foo => foo.Foo_Id,
bar => bar.Foo_Id,
(x,y) => new { Foo = x, Bars = y })
.SelectMany(
x => x.Bars.DefaultIfEmpty(),
(x,y) => new { Foo=x.Foo, Bar=y});
</code></pre>
|
What is the best approach to calculate a formula which changes value each day? <p>I use the following columns stored in a SQL table called tb_player:</p>
<p>Date of Birth (Date), Times Played (Integer), Versions (Integer)</p>
<p>to calculate a "playvalue" (integer) in the following formula:</p>
<p>playvalue = (Today - Date of Birth) * Times Played * Versions</p>
<p>I display upto 100 of these records with the associataed playvalue on a webpage at any time.</p>
<p>My question is, what is the most efficient way of calculating this playvalue given it will change only once a day, due to the (today-date of birth) changing? The other values (times played & versions) remain the same.</p>
<p>Is there a better way than calculating this on the fly each time for the 100 records? If so, is it more efficient to do the calculation in a stored proc or in VB.NET/C#?</p>
| <p>In a property/method on the object, in C#/VB.NET (your .NET code).</p>
<p>The time to execute a simple property like this is <strong>nothing</strong> compared to the time to call out-of-process to a database (to fetch the rows in the first place), or the transport time of a web-page; you'll <strong>never</strong> notice it if just using it for UI display. Plus it is on your easily-scaled-out hardware (the app server), and doesn't involve a huge update daily, and is only executed for rows that are actually displayed, and only if you actually query this property/method.</p>
|
Is there a way to determine what configuration file MySQL is using? <p>Is there a command I can run within MySQL to determine where/which configuration file MySQL is using?</p>
| <p>As of ver 5.0, no. But look at <a href="http://stackoverflow.com/questions/580331/mysql-how-to-determine-which-config-file-is-being-used">http://stackoverflow.com/questions/580331/mysql-how-to-determine-which-config-file-is-being-used</a> for how to look from <em>outside</em> MySQL.</p>
|
Why âNo database selectedâ SQLException? <p>why this program is not executing when it goes in to the do while loop second time and why it is giving the exception "Exception java.sql.SQLException: [MySQL][ODBC 5.1 Driver][mysqld-5.0.51a-community-nt]No database selected"</p>
<pre><code>//import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
import java.util.Vector;
public class DataBase {
public void LoadDriver() {
// Load the JDBC-ODBC bridge driver
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (ClassNotFoundException ee) {
ee.printStackTrace();
}
}
// 2.open a data source name by means of the jdbcodbcdriver.
static void connect() throws SQLException {
// Connect to the database
Connection con = DriverManager.getConnection("jdbc:odbc:MySQL", "root", "admin");
Statement stmt = con.createStatement();
// Shut off autocommit
con.setAutoCommit(false);
System.out.println("1.Insert 2.Delete 3.Update 4.Select");
Scanner s = new Scanner(System.in);
int x;
x = s.nextInt();
String query; // SQL select string
ResultSet rs; // SQL query results
boolean more; // "more rows found" switch
String v1, v2; // Temporary storage results
Vector<Object> results = new Vector<Object>(10);
if (x == 1) {
try {
stmt.executeUpdate("INSERT INTO employee( emp_id,emp_name ) VALUES ( '122','shiva' ) ");
} catch(Exception e){System.out.println("Exception " +e);e.printStackTrace();}
}
if (x == 2) {
try {
stmt.executeUpdate("DELETE from employee where emp_id='102' ");
}catch(Exception e){System.out.println("Exception "+e);e.printStackTrace();}
}
if (x == 3) {
try {
stmt
.executeUpdate("UPDATE employee SET emp_name = 'madavan' where emp_id='20'; ");
} catch(Exception e){System.out.println("Exception "+e);e.printStackTrace();}
}
query = "SELECT * FROM employee ";
try {
rs = stmt.executeQuery(query);
// Check to see if any rows were read
more = rs.next();
if (!more) {
System.out.println("No rows found.");
return;
}
// Loop through the rows retrieved from the query
while (more) {
v1 = "ID: " + rs.getInt("emp_id");
v2 = "Name: " + rs.getString("emp_name");
System.out.println(v1);
System.out.println(v2);
System.out.println("");
results.addElement(v1 + "\n" + v2 + "\n");
more = rs.next();
}
rs.close();
} catch (SQLException e) {
System.out.println("" + results.size() + "results where found.");
}
finally{stmt.close();}
}
public static void main(String[] args) throws SQLException {
String str = "y";
do {
DataBase s = new DataBase();
s.LoadDriver();
DataBase.connect();
Scanner sc = new Scanner(System.in);
System.out.println("DO u Want to PROCEED TO QUERY : ");
str = sc.next();
} while (str !="n");
}
}
</code></pre>
| <p>Unless you have to use the jdbc/odbc driver I would use the straight mysql jdbc driver. You can download it free from mysql.</p>
<p>then </p>
<pre><code>public void LoadDriver() {
// Load the JDBC-ODBC bridge driver
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ee) {
ee.printStackTrace();
}
}
static void connect() throws SQLException {
// Connect to the database
Connection con = DriverManager.getConnection("jdbc:mysql:host/databasename", "root", "admin");
Statement stmt = con.createStatement();
...
</code></pre>
|
What's better at freeing memory with PHP: unset() or $var = null <p>I realise the second one avoids the overhead of a function call (<strong>update</strong>, is actually a language construct), but it would be interesting to know if one is better than the other. I have been using <code>unset()</code> for most of my coding, but I've recently looked through a few respectable classes found off the net that use <code>$var = null</code> instead.</p>
<p>Is there a preferred one, and what is the reasoning?</p>
| <p>As (it was in 2009) mentioned in <a href="http://us2.php.net/manual/en/function.unset.php#86347">unset</a> (now 2013, that man page don't include that anymore)</p>
<blockquote>
<p><code>unset()</code> does just what its name says - unset a variable. It does not force immediate memory freeing. PHP's garbage collector will do it when it see fits - by intention as soon, as those CPU cycles aren't needed anyway, or as late as before the script would run out of memory, whatever occurs first.</p>
<p>If you are doing <code>$whatever = null;</code> then you are rewriting variable's data. You might get memory freed / shrunk faster, but it may steal CPU cycles from the code that truly needs them sooner, resulting in a longer overall execution time.</p>
</blockquote>
<p>Note that until php5.3, if you have <a href="http://paul-m-jones.com/?p=262">two objects in circular reference</a>, such as in a parent-child relationship, calling unset() on the parent object will not free the memory used for the parent reference in the child object. (Nor will the memory be freed when the parent object is garbage-collected.) (<a href="http://bugs.php.net/bug.php?id=33595">bug 33595</a>)</p>
<hr>
<p>The question "<a href="http://stackoverflow.com/q/13667137/6309">difference between unset and = null</a>" details some differences:</p>
<hr>
<p><code>unset($a)</code> also removes <code>$a</code> from the symbol table; for example:</p>
<pre class="lang-php prettyprint-override"><code>$a = str_repeat('hello world ', 100);
unset($a);
var_dump($a);
</code></pre>
<blockquote>
<p>Outputs:</p>
</blockquote>
<pre class="lang-php prettyprint-override"><code>Notice: Undefined variable: a in xxx
NULL
</code></pre>
<blockquote>
<p>But when <code>$a = null</code> is used:</p>
</blockquote>
<pre class="lang-php prettyprint-override"><code>$a = str_repeat('hello world ', 100);
$a = null;
var_dump($a);
Outputs:
NULL
</code></pre>
<blockquote>
<p>It seems that <code>$a = null</code> is a bit faster than its <code>unset()</code> counterpart: updating a symbol table entry appears to be faster than removing it.</p>
</blockquote>
<hr>
<ul>
<li>when you try to use a non-existent (<code>unset</code>) variable, an error will be triggered and the value for the variable expression will be null. (Because, what else should PHP do? Every expression needs to result in some value.) </li>
<li>A variable with null assigned to it is still a perfectly normal variable though.</li>
</ul>
|
How to create a check constraint between two columns in SQL? <p>I am trying to create a Basic pay (BP) table with</p>
<pre><code>CREATE TABLE bp (
bpid VARCHAR(5),
FOREIGN KEY (bpid) REFERENCES designation(desigid),
upperlimit DECIMAL(10,2) NOT NULL,
lowerlimit DECIMAL(10,2) NOT NULL,
increment DECIMAL(10,2) NOT NULL
CONSTRAINT llvalid CHECK (upperlimit > lowerlimit)
);
</code></pre>
<p>As you can see near the ending, I want to check if <code>upperlimit</code> is greater than <code>lowerlimit</code>, how can I do that?</p>
| <p>It might (probably does) depend on the data base you use.</p>
<p>Comparing to the oracle syntax (e.g. here: <a href="http://www.techonthenet.com/oracle/check.php" rel="nofollow">http://www.techonthenet.com/oracle/check.php</a>), what you are missing might be a ',' between NULL and CONSTRAINT</p>
|
Storing username that last modified database row via EJB3.0 and JPA <p>I'd like to store username that has last modified table row to as a field in every table.</p>
<p>I have following setup: an user logs in, web layer calls some EJB 3.0 beans. Those EJB beans create and modify some JPA entities.
Now, I'd like that username (from weblayer) would be automatically stored to every JPA entity (and database row) that is created or modified during EJB method call. </p>
<p>I have this kind of table, (that is: every table has field modifier):</p>
<pre><code>CREATE TABLE my_table (
some_data INTEGER,
modifier VARCHAR(20)
);
</code></pre>
<p>By automatically I mean, that I wouldn't need to set manually username to each entity inside EJB methods.</p>
<p>You could achive this by storing username to ThreadLocal variable and fetching username from ThreadLocal in JPA entity's EntityListener.
However this works only you are using a local EJB call, it will not work with EJB calls that cross JVM boundaries. I'd like to make this work over remote EJB method calls.</p>
<p>It this possible at all? </p>
<p>I am using Weblogic Server 10.3, EJB3.0 and EclipseLink JPA. I am also interested in hearing if this works with other JPA implementations.</p>
| <p>You can use an EJB interceptor (@Around) on the EJB class to get the current user (using standard EJB api) and storing the name in the threadlocal variable. This would work transparently for remote and local calls.</p>
|
ASP.NET 2.0 add styles dynamically to page in a control <p>I need to add to the page from within a custom control. I can't use a stylesheet (.css) because I'm using a url(...) and need to resolve the url.</p>
<p>Right now I'm doing:</p>
<pre><code>Page.Header.Controls.Add(new LiteralControl("<style type='text/css'>.xyz { color: blue; }</style>"));
</code></pre>
<p>But I'm hoping for something a touch more elegant?</p>
| <p>I guess it's not a bad solution for the problem. If you had an <em>external stylesheet file</em>, this piece of code will do the work:</p>
<pre><code>HtmlLink cssRef = new HtmlLink();
cssRef.Href = "styles/main.css";
cssRef.Attributes["rel"] = "stylesheet";
cssRef.Attributes["type"] = "text/css";
Page.Header.Controls.Add(cssRef);
</code></pre>
<p>Another idea is to write <strong>your own ASP.NET ServerControl</strong> "HtmlInlineStyle", so you could call it this way (script tags would be done by your server control):</p>
<pre><code>Page.Header.Controls.Add(
New HtmlInlineStyle(".xyz { width:300px;padding-left:10px }");
</code></pre>
<p>This <a href="http://www.west-wind.com/WebLog/posts/158367.aspx" rel="nofollow">blog entry</a> and the comments show some alternatives (ScriptManager.RegisterClientScriptBlock). But in my opinion your solution is okay.</p>
|
LINQ Query to insert data into the database <p>In my database, I have a table named Students, with 3 Columns (SNo, SName, Class).</p>
<p>I want to insert the value of only SName. </p>
<p>Can anybody tell me how to write the LINQ Query for this.</p>
<p>Thanks,
Bharath. </p>
| <p>Do you mean you want to <em>query</em> only the name? In which case:</p>
<pre><code>var names = ctx.Students.Select(s=>s.Name);
</code></pre>
<p>or in query syntax:</p>
<pre><code>var names = from s in ctx.Students
select s.Name;
</code></pre>
<p>To <em>insert</em> you'd need to create a number of <code>Student</code> objects - set the names but not the other properties, and add them to the context (and submit it). LINQ is a <em>query</em> tool (hence the Q); insertions are currently object oriented.</p>
|
How can I implement conditional updating in Oracle? <p>I'm new to oracle and having a problem with one of my SQL Queries.</p>
<p>There are 2 Users: <code>User1</code> and <code>User2</code>:</p>
<pre>
Tab1 Tab2
-------- --------
EmpNo EmpNo
EmpName EmpName
ContactNo Salary
Location
</pre>
<p>User2 has all privileges in User1.Tab1, and there is no foreign key relationship between the two tables.</p>
<h3>The Problem:</h3>
<p>I wanted to add a column in tab2 "<code>NameDesignation</code>" And I wanted to insert the value in this column after checking the following condition:</p>
<pre><code>WHEN User1.Tab1.EmpNo = User2.Tab2.EmpNo THEN
INSERT INTO Tab2 VALUES (&designation)
</code></pre>
<p>I really have no idea how to do this, and was hoping for a little help. Any thoughts?</p>
| <pre><code>UPDAT UZRTOO.TABTOO.IMPKNOW TEATOO
SETT DEZIGNASHUN IZ EQL DOTZ
WHAR IS HVING (SLEKT NUTHN
FRUM UZRWON.TABWON TEAWON
WAR IS HVING TEAWON.IMPKNOW IZ EQL TEATOO.IMPKNOW)
</code></pre>
<p><strong>Update</strong></p>
<p>A word of explanation; the original phrasing of the question was full of text-message-style abbreviations, and included a LOLCAT photo. So, in good fun, it seemed OK to translate the SQL to SQLOLCODE. No offense intended to anyone.</p>
|
Implementing ridge detection <p>I'm trying to write a ridge detection algorithm, and all of the sources I've found seem to conflate edge detection with ridge detection. Right now, I've implemented the Canny edge detection algorithm, but it's not what I want: for example, given a single line in the image, it will effectively translate it to a double line of edges (since it will record <em>both</em> sides of the line) - I just want it to read the one line.</p>
<p>The <a href="http://en.wikipedia.org/wiki/Ridge_detection" rel="nofollow">wikipedia article</a> about ridge detection has a bunch of math, but this kind of this doesn't help me as a programmer (not that I'm averse to math, but it's not my field, and I don't understand how to translate their differential equations into code). Is there a good source for actually implementing this? Or, for that matter, is there a good open source implementation?</p>
<p>Edit: here's the simple example. We start with a simple line:</p>
<p><a href="http://img24.imageshack.us/my.php?image=linez.png" rel="nofollow"><img src="http://img24.imageshack.us/img24/8112/linez.th.png"></a><br><br></p>
<p>and run the Canny Algorithm to get:</p>
<p><a href="http://img12.imageshack.us/my.php?image=canny.png" rel="nofollow"><img src="http://img12.imageshack.us/img12/1317/canny.th.png"></a><br><br></p>
<p>(you can see that it's thicker here - if you click on the image, you'll see that it really is two adjacent lines with a blank in between)</p>
<p>Also, I'm writing in C++, but that shouldn't really matter. But I want to code the <em>algorithm</em>, not just write <code>SomePackage::findRidges()</code> and be done with it.</p>
| <p>Maybe you need to think in terms of cleaning up the line you already have, rather than a Canny-like edge detection. It feels like you should be able to do something with <a href="http://en.wikipedia.org/wiki/Morphological%5Fimage%5Fprocessing"><strong>image morphology</strong></a>, in particular I'm thinking of the skeletonize and ultimate eroded points type operations. Used appropriately these should remove from your image any features which are not 'lines' - I believe they're implemented in Intel's OpenCV library. </p>
<p>You can recover a single line from your double line generated using the Canny filter using one dilate operation followed by 3 erodes (I tried it out in ImageJ) - this should also remove any edges.</p>
|
Breaking an interface <p>What are the most important guidelines to follow if you need to break an interface in a .NET application? How do these guidelines change before and after your application has been deployed?</p>
<p>I know there are other questions that debate when/where interfaces should be used, however I don't want to get into that. I just want to know some effective approaches to mitigating effects on the rest of your application when you need to do this.</p>
<p>If I am just adding new method/s to an interface, will only implementors need modification/recompile, while all clients continue to operate happily with no change required?</p>
<p>What about renaming methods and variables, is this ever going to break an interface?</p>
<p>One strong recommendation I've come across in the past is "never break an interface". But doesn't this produce a messy design such as IDocument, IDocument2, IDocument3, IDocument4, IDocument5, IDocument6 etc, as seen in the mshtml COM library?</p>
| <p>It depends on the contract (implied or explicit) with the consumers of your interface.</p>
<p>If all consumers are rebuilt when you rebuild the interface then <strong>managing</strong> changing it is simple, simply change it and fix all the breaks (fixing the breaks themselves <em>may</em> be complex).</p>
<p>If you expect consumers to to a recompile whenever you release a new library/app then you will need to provide some assistance to them to indicate what changes are required, how you manage this is dependent on whther the change can happen whilst maintaining the old functions/properties. If you can then judicious use of [Obsolete("Use the new Blah method instead", false)] in at least one release followed by [Obsolete("...", true)] in the next release will provide a clean migration path</p>
<p>If you try to maintain binary compatibility then the Obsolete attributes allow for this while still stopping people continuing to use the deprecated functionality when they recompile.</p>
<p>If your contract implies that binary and source compatibility is to be maintained for, say 5 years (a short period of time for OS platform APIs) then you have little choice but to go with an entirely new interface, adding methods to an interface will break code implementing it (either at compile, at type validation or at method invocation depending on the strictness of the type loader).</p>
|
MSBuild exec task with for <p>I am trying to run the following commands as part of an MSBuild script:</p>
<pre><code>for /R . %f in (*.targets) do copy /Y "%f" "C:\Program Files (x86)\MSBuild\Microso
ft\VisualStudio\TeamBuild"
</code></pre>
<p>The commands is implemented in an exec the following way:</p>
<pre><code><Exec WorkingDirectory="$(SolutionRoot)" Command="for /R . %f in (*.targets) do copy /Y &quot;%f&quot; &quot;$(MSBuildExtensionsPath)\Microsoft\VisualStudio\TeamBuild&quot;" />
</code></pre>
<p>The command works fine from console, but when trying to run it from MSBuild I get the error: </p>
<pre><code>Task "Exec"
Command:
for /R . %f in (*.targets) do copy /Y "%f" "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\TeamBuild"
f" "C:\Program was unexpected at this time.
C:\Users\rd-build\AppData\Local\Temp\OH Test2\Continuous.BuildTargets\BuildType\TFSBuild.proj(98,5): error MSB3073: The command "for /R . %f in (*.targets) do copy /Y "%f" "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\TeamBuild"" exited with code 255.
Done executing task "Exec" -- FAILED.
</code></pre>
<p>Any suggestions?</p>
| <p>I have just explained in your previous question. In that case you need to add extra % in front of your variables. It is explained in help of FOR command as follows</p>
<blockquote>
<p>To use the FOR command in a batch
program, specify %%variable instead of
%variable.</p>
</blockquote>
|
How do I do conditional validation in ActiveRecord with n conditions? <p>I am providing a web service to be called by external companies. The required data covers several models including person, address etc. I want to validate the received data conditionally based upon some fields within the request. I will eventually have many differing sets of validation data, although currently I only have one and I am about to add the second.</p>
<p>My current model looks something like this</p>
<pre><code>class Person < ActiveRecord::Base
validates_length_of :first_name, :within => 1..32, :allow_blank => true
...
...
end
</code></pre>
<p>Conceptually my model now needs to do something like this.</p>
<pre><code>class Person < ActiveRecord::Base
validate :first_name?
def first_name?
if country == 'UK'
if company_name == 'ABC'
validates_length_of :first_name, :within => 1..32
else if company_name == 'DEF'
validates_length_of :first_name, :within => 2..20
end
else if country == 'DE'
if company_name == 'ABC'
validates_length_of :first_name, :within => 1..32
else if company_name == 'DEF'
validates_length_of :first_name, :within => 2..20
end
end
end
</code></pre>
<p>This would obviously work fine for 2 companies/countries but will not work well as the number of companies and/or countries increases. I am now considering keeping the validation data either in the database or in a YAML file and then performing the validations manually for each field based upon the minimum, maximum, format values stored externally from the model.</p>
<p>I am thinking that I could store the validation data in a structure similar to the following</p>
<pre>
country: UK
companyname: ABC
field: first_name
minimum_length: 2
maximum_length: 20
required: true
field: middle_name
minimum_length: 1
maximum_length: 10
field: email_address
minimum_length: 10
format: /someregexforemail addresses/
companyname: DEF
field
...
country: DE
companyname: XYZ
field:
....
</pre>
<p>and so on. </p>
<p>I could then load this validation data and use this within my own hand-rolled validator.</p>
<p>Has anyone done similar things in the past and what methods did you use? I am particularly interested to know how you approached the following.</p>
<ul>
<li>Where did you store your configuration data i.e. DB or YAML?</li>
<li>Did you load and parse the configuration data for each request or once as the server loaded?</li>
<li>How did you structure the actual method that did validation?</li>
</ul>
| <p>I did something similar with phone numbers. Your approach is very similar to what I did myself. To answer your questions:</p>
<ol>
<li>I stored the validation configuration in a YAML file. Hovewer, if your data is going to grow to a large extent, you should consider using database.</li>
<li>I load and parse data on each request. I don't think that's the best approach, though and plan to rewrite this part.</li>
<li>I wrote my own validation. You can get come clue how to do that <a href="http://marklunds.com/articles/one/312" rel="nofollow">here</a>.</li>
</ol>
<p>Did that help you?</p>
|
Exception when destroying TReader <p>The following code throws an EZDecompressionError with message 'Invalid ZStream operation' whenever the line</p>
<pre><code>Reader.Free
</code></pre>
<p>is executed. Can someone tell me what's wrong with this code?</p>
<pre><code>Reader := nil;
Decompressor := nil;
InputFile := TFileStream (FileName, fmOpenRead);
try
Decompressor := TDecompressionStream.Create (InputFile);
Reader := TReader.Create (Decompressor, 1024);
SomeString := Reader.ReadString;
finally
Reader.Free
Decompressor.Free;
InputFile.Free;
end;
</code></pre>
<p>I tested to change the order of the memory freeing commands but that doesn't seem to help. Leaving out the Reader.Free line of course results in a memory leak.</p>
| <p>Smasher </p>
<p>TReader does a <strong>FStream.Seek(FBufPos - FBufCount, soCurrent)</strong> in its destructor.</p>
<p>The error get's raised because of a backwards seek. If you call <strong>Reader.FlushBuffer</strong> and <strong>Reader.Position := soFromBeginning</strong> before freeing the reader, does the error disappear?</p>
<p><hr /></p>
<p>From the comments of TDecompressionstream. <em>TDecompressionStream is read-only and unidirectional; you can seek forward in the stream, but not backwards.</em></p>
<p>Regards,<br />
Lieven</p>
|
Trying to store password to database <p>Hi
i'm doing a test how hash and salt passwords.
Well , i can add hash and salt password to the Database but i got stuck to store passwords from database.
i have a simple Database :</p>
<pre><code> Table
_______
ProvaHS
--------
(PK) LoginID int
UserName nvarchar(50)
Password nvarchar(50)
Salt nvarchar(50)
</code></pre>
<p>So i create a form to add new record to the database with this code:</p>
<pre><code> public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
#region SALT
public static class PasswordCrypto
{
private static SHA1CryptoServiceProvider Hasher = new SHA1CryptoServiceProvider();
//Private Hasher As New MD5CryptoServiceProvider()
static internal string GetSalt(int saltSize)
{
byte[] buffer = new byte[saltSize + 1];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(buffer);
return Convert.ToBase64String(buffer);
}
static internal string HashEncryptString(string s)
{
byte[] clearBytes = Encoding.UTF8.GetBytes(s);
byte[] hashedBytes = Hasher.ComputeHash(clearBytes);
return Convert.ToBase64String(hashedBytes);
}
static internal string HashEncryptStringWithSalt(string s, string salt)
{
return HashEncryptString(salt + s);
}
}
#endregion
private void GetSalt()
{
this.textBoxSalt.Text = PasswordCrypto.GetSalt(16);
}
private void GetSaltHash()
{
// It's how i salt and hash the password before to save it to the Database
this.textBoxPassword.Text = PasswordCrypto.HashEncryptStringWithSalt(this.textBoxClear.Text, this.textBoxSalt.Text);
}
private void GetHash()
{
//Demo purposes -- this is an unsalted hash
this.textBoxClear.Text = PasswordCrypto.HashEncryptString(this.textBoxPassword.Text);
}
private void Add(object sender, RoutedEventArgs e)
{
DataClasses1DataContext dc = new DataClasses1DataContext();
try
{
if (textBoxUserName.Text.Length > 0)
{
ProvaH tab = new ProvaH();
tab.UserName = textBoxUserName.Text;
tab.Password = textBoxPassword.Text;
tab.Salt = textBoxSalt.Text;
dc.ProvaHs.InsertOnSubmit(tab);
dc.SubmitChanges();
}
}
catch (Exception ex)
{
MessageBox.Show("Error!!!");
}
}
private void HashButton(object sender, RoutedEventArgs e)
{
GetHash();
}
private void SaltButton(object sender, RoutedEventArgs e)
{
GetSalt();
}
private void HashSaltButton(object sender, RoutedEventArgs e)
{
GetSaltHash();
}
private void Close_W(object sender, RoutedEventArgs e)
{
this.Close();
}
}
</code></pre>
<p>}</p>
<ul>
<li>with this method i can salt,hash and save password to the database..(following advices StackOverflow's member ) thanks..</li>
</ul>
<p>Now i'm testing how store password from the database and here i got a trouble...</p>
<pre><code> public partial class Login : Window
{
public Login()
{
InitializeComponent();
}
#region SALT
public static class PasswordCrypto
{
private static SHA1CryptoServiceProvider Hasher = new SHA1CryptoServiceProvider();
//Private Hasher As New MD5CryptoServiceProvider()
static internal string GetSalt(int saltSize)
{
byte[] buffer = new byte[saltSize + 1];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(buffer);
return Convert.ToBase64String(buffer);
}
static internal string HashEncryptString(string s)
{
byte[] clearBytes = Encoding.UTF8.GetBytes(s);
byte[] hashedBytes = Hasher.ComputeHash(clearBytes);
return Convert.ToBase64String(hashedBytes);
}
static internal string HashEncryptStringWithSalt(string s, string salt)
{
return HashEncryptString(salt + s);
}
}
#endregion
private void closs(object sender, RoutedEventArgs e)
{
this.Close();
}
public bool ValidateApplicationUser(string userName, string password)
{
bool OK = false;
DataClasses1DataContext dc = new DataClasses1DataContext();
object saltValue = from c in dc.ProvaHs where c.UserName == userName select c.Salt;
if (!(saltValue == System.DBNull.Value))
{
password = PasswordCrypto.HashEncryptStringWithSalt(passwordTextBox.Password, saltValue.ToString());
}
var query = from c in dc.ProvaHs where c.UserName == userName && c.Password == password select new { c.LoginID, c.UserName, c.Password };
if (query.Count() != 0)
{
return true;
}
return false;
}
private void Confirm(object sender, RoutedEventArgs e)
{
bool authenticated = true;
if (usernameTextBox.Text != "" && passwordTextBox.Password.ToString() != "")
{
authenticated = ValidateApplicationUser(usernameTextBox.Text, passwordTextBox.Password.ToString());
}
if (!authenticated)
{
MessageBox.Show("Invalid login. Try again.");
}
else
{
MessageBox.Show("Aaaaahhhh.JOB DONE!!!!....");
}
}
}
</code></pre>
<p>when i debug the application i receive always an error at this code line :
if (query.Count() != 0) in "query" = Empty :"Enumeration yielded no results"
Do you have any suggest how work out this error and store password from database in my case?
Thanks</p>
| <p>Try:</p>
<pre><code>public bool ValidateApplicationUser(string userName, string password)
{
DataClasses1DataContext dc = new DataClasses1DataContext();
var saltValue = dc.ProvaHs.Where(c => c.UserName == userName)
.Select(c => c.Salt)
.SingleOrDefault();
if (saltValue == null) return false;
password = PasswordCrypto.HashEncryptStringWithSalt(passwordTextBox.Password, saltValue.ToString());
return dc.ProvaHs.Any(c => c.UserName == userName && c.Password == password);
}
</code></pre>
|
STEP/EXPRESS tools for .NET <p>Has anyone had any experience with using the <a href="http://en.wikipedia.org/wiki/Standard%5Ffor%5Fthe%5FExchange%5Fof%5FProduct%5Fmodel%5Fdata/">STEP</a> and <a href="http://en.wikipedia.org/wiki/EXPRESS%5F%28data%5Fmodeling%5Flanguage%29/">EXPRESS</a> formats in a .Net environment?</p>
<p>I am looking for a tool that will generate a c# class structure based on an EXPRESS schema. I would also like the tool to create a parser/file generator for importing and exporting to STEP-files.</p>
<p>Does anyone know of a tool that does this? Any tools that will bring me closer to my own implementation would also be useful.</p>
<p>Thanks</p>
| <p>I know this is an old question, but I thought I'd answer for anyone else who stumbles upon it.</p>
<p>If you need to work with <code>STEP</code> and <code>EXPRESS</code> and don't want CAD libraries, or if you need an uncommon or custom schema, take a look at (<strong>shameless plug!</strong>) <a href="http://github.com/stepcode/stepcode" rel="nofollow">STEPcode</a>, which uses the BSD license. </p>
<p>It generates <code>C++</code>, not <code>C#</code> - but IMO it would be far easier to modify SCL than to start from scratch.</p>
<p>Note that this was formerly known as Step Class Library, the same <code>SCL</code> that @roch mentions above. A group of people are improving it, and the NIST version is very dated.</p>
<p><strong>edit:</strong> new name, new URL</p>
|
Subclassing classes with completely independent inheritance trees that cannot be modified <p>How would someone join two classes each with independent inheritance trees to bridge context boundaries, given the restrictions that neither class's inheritance trees can be modified to inherit from the other?</p>
<p>i.e., if an item that is an entity saved to a database, let's say:</p>
<pre><code>public class Stockitem : StockItemBase {
...
}
</code></pre>
<p>needs to be displayed using a drawing component, let's say:</p>
<pre><code>Public class GraphicNode : BaseNode { ... }
</code></pre>
<p>It would be nice to simply have a subclassed <code>stockitemgraphicnode</code> as there are many common members.</p>
<p>What is the best way to design a solution?</p>
| <p>Composition.</p>
<p>Create a new class that inherits from neither but has an instance of both the classes you want to use within it, then expose the methods you want to call.</p>
<p>Google "Composition over Inheritence" for much better ramblings on the subject than mine</p>
|
Contraint - unique or empty <p>There is a nvarchar column in a table that allows empty values. Once there is a none-empty value it must be uniqe. </p>
<p>Is it possible to define this rule without a trigger?</p>
<p>EDIT: </p>
<p><a href="http://decipherinfosys.wordpress.com/2007/11/30/multiple-null-values-in-a-unique-index-in-sql-serverdb2-luw/" rel="nofollow">http://decipherinfosys.wordpress.com/2007/11/30/multiple-null-values-in-a-unique-index-in-sql-serverdb2-luw/</a></p>
<p>is a nice workaround. The only issue I see is that the primary key might at some point be the same as one of the values in the column I want to be unique. Thats why I added a fixed string that I know never occurs in the constrained column.</p>
| <p>There is a work-around for the multiple NULL values in a unique key column in <a href="http://decipherinfosys.wordpress.com/2007/11/30/multiple-null-values-in-a-unique-index-in-sql-serverdb2-luw/" rel="nofollow">http://decipherinfosys.wordpress.com/2007/11/30/multiple-null-values-in-a-unique-index-in-sql-serverdb2-luw/</a></p>
<p>Basically in the article they make an extra column that they keep unique. In case your original column is <em>not</em> null, its content is copied into the unique column. Whenever it is null, the primary key is copied into the column. This is a bit of a workaround, but it should work.</p>
|
(Fluent) NHibernate : One entity composed of fields from different tables <p>Is there a way of writing an NHibernate mapping so that you can have an entity that is composed of fields from different DB tables?</p>
<p>For Example is I have a Person and Address table, I want address fields to appear in my person object.</p>
<p>I want an entity like this:</p>
<pre><code>public class person
{
public virtual Guid Key{get; set;}
public virtual string Name {get; set;}
public virtual string Age {get; set;}
public virtual string Address1 {get; set;} //from address table
public virtual string Address2 {get; set;} //from address table
}
</code></pre>
| <p>If you are using Fluent NHibernate you can use WithTable, as in this example:</p>
<pre><code>public class PersonMap : ClassMap<Person>
{
public PersonMap()
{
Id(x => x.Key, "[Key]"); // Explicitly specify escaped column name to
// avoid problems with reserved words
Map(x => x.Name);
Map(x => x.Age);
WithTable("Address", m =>
{
m.Map(x => x.Address1);
m.Map(x => x.Address2);
});
}
}
</code></pre>
|
Should NullRefs ever be caught? <p>I recently made the statement to a colleague that:</p>
<blockquote>
<p>NullReferenceExceptions should <em>never</em>
be explicitly caught</p>
</blockquote>
<p>I used the word never.... hmmm. I've never seen a appropriate use case myself for catching them but I wanted to check if anyone else has?</p>
<p>Never is such a strong word after all.....</p>
| <p>It depends on why; see Eric Lippert's <a href="http://blogs.msdn.com/ericlippert/archive/2008/09/10/vexing-exceptions.aspx" rel="nofollow">blog entry</a>.
If they are "boneheaded exceptions", then no - just fix the calling code. In the rare case that they are "vexing exceptions" (i.e. the code you are calling has traps that are hard to avoid), then I guess you'd have to.</p>
|
iPhone Development Related Podcasts? <p>Anyone have any suggestions for good iPhone development related podcasts?</p>
<p>Only one I've run across is <a href="http://www.mobileorchard.com/" rel="nofollow">http://www.mobileorchard.com/</a> and was looking for some others.</p>
| <p>Just came across a reference to a new podcast, <a href="http://itunes.apple.com/podcast/build-and-analyze/id404064215" rel="nofollow">Build and Analyse</a>.</p>
|
Update several columns at once in Derby <p>DB2 supports this syntax:</p>
<pre><code>UPDATE DEST D SET (AAA,BBB) = (
SELECT MAX(Z.AAA), MAX(Z.BBB) FROM OTHER O WHERE O.ID = D.ID
)
</code></pre>
<p>i.e. I can run a select which returns more than one column and copy the results into various columns of the destination table (the one to update).</p>
<p>Derby only allows the syntax:</p>
<pre><code>UPDATE table-Name [[AS] correlation-Name]
SET column-Name = Value
[ , column-Name = Value} ]*
[WHERE clause]
</code></pre>
<p>which means I can run into problems when I need to group the results of the select in some way. Is there a better solution than splitting the update into two statements or doing this locally in a loop in Java (i.e. submitting millions of UPDATE statements)?</p>
| <p>Presumably, you can do this:</p>
<pre><code>UPDATE DEST D
SET AAA = (SELECT MAX(Z.AAA) FROM OTHER O WHERE O.ID = D.ID),
BBB = (SELECT MAX(Z.BBB) FROM OTHER O WHERE O.ID = D.ID)
</code></pre>
<p>I didn't say anything about efficient - but it is likely more efficient than either splitting the update into two statements or doing it locally in a loop.</p>
|
how to access SVN using VBScript <p>We'r maintaing some test scripts written in VBScript in SVN and everyday morning we get the latest copy of these files and run the tests. We are doing this manually at the moment. However we want to automated this whole operation. </p>
<p>How do we access SVN using VBScript to copy the latest code back to the test machine? Is there any API that we can use to access SVN and get the latest files?</p>
| <p>So long as svn is in your path...</p>
<pre><code>Set objShell = WScript.CreateObject("WScript.shell")
objShell.exec ("cmd svn update C:\Projects\Project1 --username buildrobot --password IAmARobot1")
</code></pre>
|
How to get some interactivity with a JTable <p>I Have a JTable where the data model contains information from a sql query. Want to get the added ability to take me to a new jpanel by double-clicking a row in the jtabel.</p>
<p>Thnx</p>
| <p>You can add a MouseListener to a JTable and then handle the mouseClicked event.</p>
<p>The following code shows a mouseClicked implementation that finds out what row was double clicked. You can then navigate to a panel using this information.</p>
<pre><code>public void mouseClicked(MouseEvent event)
{
if (event.getClickCount() == 2)
{
JTable source = (JTable)event.getSource();
int rowIndex = source.rowAtPoint(event.getPoint());
// get data from table model using row index
// navigate to panel
}
}
</code></pre>
|
Implement map in javascript that supports object methods as mapped functions? <p>I recently tried to use an implementation of map in javascript to create a bunch of items, then apply them to an objects add method.</p>
<p>Firstly with a bog standard implementation of map.</p>
<pre><code>var map = function (fn, a)
{
for (i = 0; i < a.length; i++)
{
a[i] = fn(a[i]);
}
}
</code></pre>
<p>Setup.</p>
<pre><code>var translateMenu = new Menu;
var languages = [ ['Chinese' , 'zh-CN']
, ['German' , 'de']
, ['French' , 'fr']
, ['Portugese' , 'pt']
, ['Hindi' , 'hi']
];
</code></pre>
<p>And my function... (not anonymous, as it's later used when adding the translateMenu to mainMenu.)</p>
<pre><code>var langItem = function (language, subMenu)
{
return new MenuItem(language[0], 'http://translate.google.com/translate?u=www.example.com&hl=en&ie=UTF-8&tl=en&sl=' + language[1] , "" , subMenu);
}
map ( langItem , languages );
</code></pre>
<p>This all worked fine, I now had an array of MenuItems to throw around.</p>
<p>Trying to call <code>map( Menu.add , languages )</code> would result in internal variables of Menu being undefined, and the call failing.<br />
Now I'm certain this has to do with the scope of the <code>Menu.add()</code> method, so i thought if I passed in the object as well, it might work. </p>
<p>I tried creating a new map function that would accept objects and functions, but had the same undefined error.</p>
<pre><code>objMap (fn , obj , a) {
for (i = 0; i < a.length; i++)
{
obj.fn(a);
}
}
objMap ( add , translateMenu , languages ); // failed
</code></pre>
<p>I worked around this by extending Menu with addAll() to take an array, which works fine...</p>
<pre><code>Menu.prototype.addAll = function (items){
for (i = 0; i < items.length; i++)
{
this.add(items[i]);
}
}
translateMenu.addAll( languages ); // yay! but I want a more elegant solution.
</code></pre>
<p>Anyway, my question is, <strong>how could I implement map (or a similar generic function) to actually support using object methods as my mapped functions?</strong>.</p>
| <blockquote>
<p>Trying to call map( Menu.add , languages )</p>
</blockquote>
<p>Here your problem is almost certainly that of JavaScript's lack of bound methods.</p>
<p>The setting of âthisâ for a function is determined only at call-time, by examining how the method was obtained. If you say one of:</p>
<pre><code>obj.method();
obj['method']();
</code></pre>
<p>JavaScript will pick up the reference to âobjâ and set âthis= objâ inside the method call. But if you say:</p>
<pre><code>obj2.method= obj.method;
obj2.method();
</code></pre>
<p>Now âthisâ inside the function will be obj2, <em>not</em> obj!</p>
<p>Similarly, if you pick the method off its object and refer to it as a first-class object:</p>
<pre><code>var method= obj.method;
method();
</code></pre>
<p>There will be no object for âthisâ to get set to, so JavaScript sets it to the global object (aka âwindowâ for web browsers). This is probably what is happening in your case: the âMenu.addâ method loses all reference to its owner âMenuâ, so when it gets called back it is most likely unknowingly writing to members of the âwindowâ object instead of a menu.</p>
<p>This is of course highly unusual for an OO language, and almost never what you want, but hey, that's how JavaScript rolls. Causing silent, hard-to-debug errors is all part of the language's rationale.</p>
<p>To get around this problem you could pass an object reference in to your map function, then use Function.call()/apply() to set the âthisâ reference correctly:</p>
<pre><code>function mapMethod(fn, obj, sequence) {
for (var i= 0; i<sequence.length; i++)
sequence[i]= fn.call(obj, sequence[i]);
}
mapMethod(Menu.add, Menu, languages)
</code></pre>
<p>A more general way would be to bind function references manually, using a closure:</p>
<pre><code>function bindMethod(fn, obj) {
return function() {
fn.apply(obj, arguments)
};
}
map(bindMethod(Menu.add, Menu), languages)
</code></pre>
<p>This capability will be built into a future version of JavaScript:</p>
<pre><code>map(Menu.add.bind(Menu), languages)
</code></pre>
<p>And it is possible to add this facility to current browsers by writing to Function.prototype.bindâââindeed, some JS frameworks do already. However note:</p>
<ul>
<li><p>ECMAScript 3.1 promises you'll also be able to pass extra arguments into bind() to do partial function application, which requires a little more code than bindMethod() above;</p></li>
<li><p>IE loves to leak memory when you start leaving references like bound methods on DOM objects like event handlers.</p></li>
</ul>
|
String.Join vs. StringBuilder: which is faster? <p>In a <a href="http://stackoverflow.com/questions/585215/can-i-rewrite-this-more-elegantly-using-linq">previous question</a> about formatting a <code>double[][]</code> to CSV format, Marc Gravell <a href="http://stackoverflow.com/questions/585215/can-i-rewrite-this-more-elegantly-using-linq/585223#585223">said</a> that using <code>StringBuilder</code> would be faster than <code>String.Join</code>. Is this true?</p>
| <p>Short answer: it depends.</p>
<p>Long answer: <strong>if you already have an array of strings to concatenate together (with a delimiter), String.Join is the fastest way of doing it.</strong></p>
<p>String.Join can look through all of the strings to work out the exact length it needs, then go again and copy all the data. This means there will be <em>no</em> extra copying involved. The <em>only</em> downside is that it has to go through the strings twice, which means potentially blowing the memory cache more times than necessary.</p>
<p>If you <em>don't</em> have the strings as an array beforehand, it's <em>probably</em> faster to use StringBuilder - but there will be situations where it isn't. If using a StringBuilder means doing lots and lots of copies, then building an array and then calling String.Join may well be faster.</p>
<p>EDIT: This is in terms of a single call to String.Join vs a bunch of calls to StringBuilder.Append. In the original question, we had two different levels of String.Join calls, so each of the nested calls would have created an intermediate string. In other words, it's even more complex and harder to guess about. I would be surprised to see either way "win" significantly (in complexity terms) with typical data.</p>
<p>EDIT: When I'm at home, I'll write up a benchmark which is as painful as possibly for StringBuilder. Basically if you have an array where each element is about twice the size of the previous one, and you get it just right, you should be able to force a copy for every append (of elements, not of the delimiter, although that needs to be taken into account too). At that point it's nearly as bad as simple string concatenation - but String.Join will have no problems.</p>
|
Data files not deployed with ClickOnce application <p>I have a WinForms app that I deploy using ClickOnce. In the application project I have some files marked as Content which is also marked as "Data File" in the Application Files dialog in the Publish settings. I have also some content files that are marked as "Include Auto".</p>
<p>When I publish, install the application and then execute it crashes immediately on startup with a DirectoryNotFoundException (full stacktrace below).</p>
<p>Looking into the application folder I can find all files that was marked "Include Auto", neatly placed along with the executables. The files marked as "Data File" though is not installed (I have checked both the executable folders and the Data folder).</p>
<p>Note that publish and install is both done from a folder on my local machine, not via a website.</p>
<p>If I change from "Data File" to standard include on all content files, everything works as a charm. </p>
<p>I'm running (gasp) Windows XP SP3 and .Net 3.5 SP1.</p>
<p>System.IO.DirectoryNotFoundException was unhandled
Message="The system cannot find the path specified. (Exception from HRESULT: 0x80070003)"
Source="mscorlib"
StackTrace:
at System.Deployment.Internal.Isolation.IActContext.SetApplicationRunningState(UInt32 dwFlags, UInt32 ulState, UInt32& ulDisposition)
at System.ActivationContext.SetApplicationState(ApplicationState s)
at System.AppDomain.SetupDomainForApplication(ActivationContext activationContext, String[] activationData)
at System.AppDomain.SetupApplicationHelper(Evidence providedSecurityInfo, Evidence creatorsSecurityInfo, ApplicationIdentity appIdentity, ActivationContext activationContext, String[] activationData)
at System.AppDomain.SetDomainManager(Evidence providedSecurityInfo, Evidence creatorsSecurityInfo, IntPtr parentSecurityDescriptor, Boolean publishAppDomain)
at System.AppDomain.SetDefaultDomainManager(String fullName, String[] manifestPaths, String[] activationData)
InnerException: </p>
| <p>After some more trial and error I found that the DirectoryNotFound exception occurs when my data files are located in subfolders of a subfolder. If data files are located in the project root or in a first level subfolder everything works as expected.</p>
<p>The problem seems also to be related to the fact that in some of these subfolders I had some files marked as Include and some as Data. This probably causes some confusion during deployment in which the data files doesn't get deployed.</p>
<p>Finally, what I had to do to get things the way I wanted was to uninstall any previous version of the app. Next, organizing my data files in the project like this:</p>
<pre>
\Testfiles\Filegroup1\data1.txt
\Testfiles\Filegroup1\data2.txt
\Testfiles\Filegroup2\moredata1.txt
\Testfiles\Filegroup2\moredata2.txt
</pre>
<p>Then I mark all files within each folder as Data. Now everything gets deployed nice and dandy and the loader doesn't crash at startup.</p>
|
How do I get my Threads to not block one another? <p>I have 2 Threads, one that's polling a mailbox for messages then sleeping <code>while (!quit)</code> and another that's supposed to change the <code>quit</code> flag should the user enter <code>'Q'</code>. It seems that the scanning Thread blocks the other Thread from executing until there's some input (usually 2 lines). I've tried changing the priority of the Threads and the order in which they start, to no avail.</p>
<pre><code>class quitThread extends Thread {
public void run() {
char c;
Scanner scanner = new Scanner(System.in);
do {
c = scanner.nextLine().toUpperCase().charAt(0);
} while (c != 'Q');
quit = true;
}
}
class recieveThread extends Thread {
public void run() {
System.out.println("thread started");
while (!quit) {
try {
MailHandler handler = new MailHandler();
handler.recieve();
System.out.println("Sleeping");
sleep(_sleepinterval);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
</code></pre>
<p>I know I have to worry about mutex and synchronisation, but I want the Threads to at least work before I start worrying about it.
EDIT:
This is how I'm starting the threads:</p>
<pre><code>void go() throws Exception{
char c;
System.out.println("S or R");
Scanner s = new Scanner(System.in);
c = s.nextLine().toUpperCase().charAt(0);
MailHandler handler = new MailHandler();
QuitThread q = new QuitThread();
q.setPriority(java.lang.Thread.MIN_PRIORITY);
RecieveThread rc = new RecieveThread();
rc.setPriority(java.lang.Thread.MAX_PRIORITY);
switch (c){
case 'S':
handler.send("blah@blah.net", "hello there");
break;
case 'R':
rc.start();
q.start();
break;
default :
break;
}
}
</code></pre>
<p>Note: the priorities weren't originally there, it's something i just tried and it didn't make any difference.</p>
| <p>How are two different instances of two different classes sharing the <code>quit</code> variable?
Try using an AtomicBoolean, shared between your two threads.</p>
<p>Also, how do you know the scanning thread is blocking the other one? From your code, I can't see them sharing any resources except for the <code>quit</code> variable.</p>
<p>Maybe you see the "thread started" message and then you don't see the "sleeping" message for a while because the receiveThread is stuck in the handler.receive() method...</p>
|
Is it possible to program for Sony Ericsson mobile phones(symbian) using Visual Studio? <p>This question is just out of curiosity, I own a P1i and it would be nice to play with it :)</p>
<p>A link to some documentation would be fine :)</p>
| <p>It isn't officially supported, but apparently you can get it to work:</p>
<p><a href="http://www3.symbian.com/faq.nsf/7b5405edb1250e7c802569ee005d054e/30398b3e9500a24d80256c7f00693a91?OpenDocument" rel="nofollow">http://www3.symbian.com/faq.nsf/7b5405edb1250e7c802569ee005d054e/30398b3e9500a24d80256c7f00693a91?OpenDocument</a></p>
<p>Plus there are some 3rd party solutions out there if you google</p>
|
App.config and ConfigurationManager <p>If I call the OpenMappedExeConfiguration() method and specify a config file (filemap) as a parameter, does this mean that the ConfigurationManager will use the newly specified config file from that point onwards and ignore app.config?</p>
<p>I know that ConfigurationManager looks for app.config by default, but because the OpenMappedExeConfiguration() method returns a Configuration object, its almost as if the instance returned is the only applicable to the config file specified, but I'm not 100% sure.</p>
| <p>As far as I remember it will just open the configuration and return the <code>Configuration</code> object, its not going to change the default one.</p>
|
.NET: Hitting the back button messes up my event handler <p>Hey all. I have a ASP.NET page that lists a bunch of user accounts.</p>
<p>If I click on a user, an event called LinkChosen is fired, which opens the account view page for that user.</p>
<p>I can also search for users, which narrows down the list. This event is called btnSearch_click</p>
<p>If I click on a user, LinkChosen() is called, and I'm taken to a new page. If I hit the back button, and try to do a search, instead of firing btnSearch_click(), it will still fire the LinkChosen() event and take me to the account I was viewing before pushing back.
Doing a search before clicking an account works like it should.</p>
<p>I'm using C# and ASP.NET, and this error appears in IE, but not Firefox.</p>
<p>Does anyone have any ideas?</p>
<p>Thanks.</p>
<p><strong>Clarification edit:</strong> The "show single account" action is a hyperlink, not a button. :)</p>
| <p>Are you pressing the "Enter Key" when you do a search. If so the first button in the page is usually the one that will get submitted on an Enter keypress.</p>
<p>You can set DefaultButton on the page, or on a panel.</p>
<p>So if you need two buttons to both respond to Enter presses in their respective portions of the page, wrape them both in their own asp:Panel with DefaultButton set.</p>
|
Discovering linux disk configurations from the command line <p>How can I discover if a remote machine is configured with or without hardware or software RAID? All I know is i have 256GB at present, I need to order more space but before I can I need to know how the drives are configured.</p>
<p><em>df</em> lists the drive as: </p>
<pre>/dev/sdb1 287826944 273086548 119644 100% /mnt/db</pre>
<p>and <em>hdparm</em>:</p>
<pre>/dev/sdb:
HDIO_GET_MULTCOUNT failed: Invalid argument
readonly = 0 (off)
readahead = 256 (on)
geometry = 36404/255/63, sectors = 299439751168, start = 0 </pre>
<p>What else should I run and what should I look for?</p>
| <p>Software RAID would not be /dev/sdb - dev/md0. Nor is it LVM.</p>
<p>So it's either real hardware RAID, or a raw disk.</p>
<p><code>lspci</code> might show you and RAID controllers plugged in.</p>
<p><code>dmesg | grep sdb</code> might tell you some more about the disk.</p>
<p><code>sdparm /dev/sdb</code> might tell you something? Particularly if it really is a SCSI disk.</p>
|
I want to hide system commands issued from system() <p>Writing a program in c++ and I want to issue a system command from the system() function but I don't want the user to see the command (because the command includes a pwd) in the executable window. I need to copy a file from the user's directory onto the server without allowing user access to the server or displaying the pwd. Figured having a .exe that does this is the easiest way.</p>
<p>Ex:</p>
<p>system("FILETRANSFER_SW.exe -pw helloWORLD11!@ C:/temp.txt F:/tempfolder/")</p>
<p>But the executable window is showing this command, hence defeating the purpose of trying to hide the password.</p>
<p>I tried issuing
system("@echo OFF")
at the beginning of the program but that does not suppress the following commands, they still show up in the executable window.</p>
<p>Any suggestions?</p>
<p>Thanks...</p>
| <p>The command line of running processes is considered public information in most operating systems.</p>
<p>Therefore it is a very bad idea to pass passwords on the command line.</p>
<p>There are two common workarounds to this problem, both of which require the support of the executable being called:</p>
<ul>
<li>instead of passing the username/password on the command line, pass the name of a file containing the username/password</li>
<li>re-set the command line of the running process from within the called executable.</li>
</ul>
<p>The first solution is easy and universally possible, the second one has a race condition and is harder to implement, because there's no cross-platform way to do it (on some OSes, changing argv will help).</p>
|
How do I replace outbound link URLs in a PDF document, using PHP <p>I have a PDF document with some external links.</p>
<p>I'd like to parse the document, replace the destination of the links then close (and serve) the PDF document, all using PHP</p>
<p>I know I can do this with PDFLib but I don't want to incur this cost.</p>
<p>I could re-write the document with FPDF or DomPDF, but some of these PDFs are quite complex so this would be a major time investment.</p>
<p>Surely there must be a way to do this directly to PDF docs, using native PHP?</p>
<p>TIA</p>
| <p>I don't think there is a text/hyperlink changer class for PHP. The closest products, like <a href="http://www.accesspdf.com/pdftk/" rel="nofollow">pdftk</a>, only does higher-level stuff like merging, splitting and applying watermarks.</p>
<p>Changing a pdf is much more difficult than generating it, so you need to use a pdf editor like <a href="http://www.nitropdf.com/professional/edit-pdf.htm" rel="nofollow">Nitro PDF</a> (untested), or why not Acrobat/Illustrator/InDesign.</p>
<p>If you must use PHP, regenerating the PDF:s with one of the free classes seems to be your best choice. I like FPDF very much, it gets my recommendation. If you decide to use it, check out <a href="http://www.setasign.de/products/pdf-php-solutions/fpdi/" rel="nofollow">FPDI</a> as well, it can use existing PDF files as a template, maybe it will help you. Good luck!</p>
|
How can I reverse a NSArray in Objective-C? <p>I need to reverse my <code>NSArray</code>.</p>
<p>As an example:</p>
<p><code>[1,2,3,4,5]</code> must become: <code>[5,4,3,2,1]</code></p>
<p>What is the best way to achieve this?</p>
| <p>There is a much easier solution, if you take advantage of the built-in <code>reverseObjectEnumerator</code> method on <code>NSArray</code>, and the <code>allObjects</code> method of <code>NSEnumerator</code>:</p>
<pre><code>NSArray* reversedArray = [[startArray reverseObjectEnumerator] allObjects];
</code></pre>
<p><a href="https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSEnumerator_Class/#//apple_ref/occ/instp/NSEnumerator/allObjects"><code>allObjects</code> is documented</a> as returning an array with the objects that have not yet been traversed with <code>nextObject</code>, in order:</p>
<blockquote>
<p>This array contains all the remaining objects of the enumerator <strong>in enumerated order</strong>.</p>
</blockquote>
|
Can I generate values for a custom parameter such as a timestamp for a Visual Studio Item Template? <p>I would like to include the current timestamp as part of a Visual Studio Item Template (the timestamp of when the file is created by the user). Is this possible?</p>
| <p>You can cause code to be executed when a template is expanded by implementing a wizard. The wizard need not have a user interface, but can populate a dictionary of name/value pairs. The values can then be substituted into the template.</p>
<p>Look in the Visual Studio SDK documentation for the topic named "How to: Use Wizards with Project Templates". I believe you can also use a wizard in an item template.</p>
<p>Also, take a look at the Guidance Automation Toolkit, which provides a declarative way to create wizards, among many other things.</p>
|
Table layout using std::cout <p>How do I format my output in C++ streams to print fixed width left-aligned tables? Something like </p>
<pre><code>printf("%-14.3f%-14.3f\n", 12345.12345, 12345.12345);
</code></pre>
<p>poducing</p>
<pre><code>12345.123 12345.123
</code></pre>
| <p>Include the standard header <a href="http://www.cplusplus.com/query/search.cgi?q=iomanip"><code><iomanip></code></a> and go crazy. Specifically, the <code>setw</code> manipulator sets the output width. <code>setfill</code> sets the filling character.</p>
|
Javascript encoding question <p>We have an external .js file that we want to include in a number of different pages. The file contains code for sorting a table on the client-side, and uses the â² and â¼ characters in the script to indicate which column is sorted and in which direction.</p>
<p>The script was originally written for an ASP.Net page to offload some sorting work from the server to client (prevent sorting postbacks when javascript is enabled). In that case, the encoding is pretty much always UTF-8 and it works great in that context. </p>
<p>However, we also have a number of older Classic ASP pages where we want to include the script. For these pages the encoding is more of a hodgepodge depending on who wrote the page when and what tool they were using (notepad, vs6, vs2005, other html helper). Often no encoding is specified in the page so it's up to the browser to pick, but there's really no hard rule for it that I can see.</p>
<p>The problem is that if a different (non-UTF8) encoding is used the â¼ and â² characters won't show up correctly. I tried using html entities instead, but couldn't get them to work well from the javascript.</p>
<p>How can I make the script adjust for the various potential encodings so that the "special" characters always show up correctly? Are there different characters I could be using, or a trick I missed to make the html entities work from javascript?</p>
<p>Here is the snippet where the characters are used:</p>
<pre><code>// get sort direction, arrow
var dir = 1;
if (self.innerHTML.indexOf(" â²") > -1)
dir = -1;
var arrow = (dir == 1)?" â²":" â¼";
// SORT -- function that actually sorts- not relevant to the question
if (!SimpleTableSort(t.id, self.cellIndex, dir, sortType)) return;
//remove all arrows
for (var c = 0,cl=t.rows[0].cells.length;c<cl;c+=1)
{
var cell = t.rows[0].cells[c];
cell.innerHTML = cell.innerHTML.replace(" â²", "").replace(" â¼", "");
}
// set new arrow
self.innerHTML += arrow;
</code></pre>
<p>For the curious, the code points I ended up using with the accepted answer were \u25B4 and \u25BC.</p>
| <p>The encoding of the JavaScript file depends on the encoding of the HTML page, where it is embedded. If you have a UTF-8 JavaScript file and a ISO-8859-1 HTML page the JavaScript is interpreted as ISO-8859-1.</p>
<p>If you load the JavaScript from as a external file you could specify the encoding of the JavaScript:</p>
<pre><code><script type="text/javascript" charset="UTF-8" src="externalJS.js"></script>
</code></pre>
<p>Anyway the best option is to save all files related to a webproject in one encoding, UTF-8 recommended.</p>
|
ASP.NET Membership/Roles/FormsAuth - how can I login as a super-user? <p>I'm working on a web application that uses the ASP.NET 2.0 Membership and Roles providers with Forms Authentication. There are various roles in the system. I need to have a user role that is essentially a super-user that can "login" as any user account (in effect impersonating the user).</p>
<p>Does anyone know if this is possible using the providers? Any ideas?</p>
<p>One approach I was thinking of was to logout the super-user and sign them in as the desired user with</p>
<pre><code>FormsAuthentication.SetAuthCookie(username, false);
</code></pre>
<p>And adding a variable to their Session to flag them as a super-user. I think this would work, but I was just wondering if there's a smarter way to do it without directly using the Session object?</p>
| <p>Why don't you have a SuperUser role that can do anything? Then the user can be just part of that role.</p>
<p>If what you really need to have is an ability for an administrator to impersonate someone else, I don't know what is the additional flag for? If it marks the currently logged in user giving him super powers the same will be achieved by setting up a role. If you, however, need to just impersonate someone else (e.g. this is help desk and you need to see exactly the same as the end user sees) - I would just check the credentials normally, then check if a superuser is logging in and who they want to impersonate and based on that just authenticate the logging in user as the one that he's willing to impersonate.</p>
<p>I hope what I wrote makes sense...</p>
|
How can I use "using" in C# without getting "InvalidOperationException"? <p>I am trying to replce the follwing code that works fine</p>
<pre><code>TcpClient oC = new TcpClient(ip, port);
oC = new TcpClient(ip, port);
StreamReader messageReader;
try {
messageReader = new StreamReader(oC.GetStream(), Encoding.ASCII);
reply = messageReader.ReadLine();
}
</code></pre>
<p>with</p>
<pre><code>try {
using (messageReader = new StreamReader(oC.GetStream(), Encoding.ASCII))
{
reply = messageReader.ReadLine();
}
}
</code></pre>
<p>But I get an <code>InvalidOperationException</code> saying </p>
<blockquote>
<p>The operation is not allowed on
non-connected sockets.</p>
</blockquote>
<p>What is the problem and how can I fix it?</p>
<p><strong>More:</strong> I have oc.Connect before this code, so I am connected and when It wants to be used for the first time is works fine, it is only after that that I get that Exception, I played around a bit with it and now I get:</p>
<blockquote>
<p>Cannot access a disposed
object.\r\nObject name:
'System.Net.Sockets.Socket'.</p>
</blockquote>
| <p>Try calling oc.Connect before creating a StreamReader. Until a socket is connected, there is nothing to actually read and hence the exception.</p>
|
Subversion: how to nuke a repository? <p>Is there a way to <strong>completely</strong> erase a Subversion repository so that users can't access to old revisions?</p>
<p>PS: I have root access on the repositories machine.</p>
| <p>Just remove the root folder of the repository, but saving the <code>conf/</code> folder it has inside. Then, create a new repository with <code>svnadmin create</code>, and overwrite the old configuration folder on it.</p>
<p>EDIT (for completeness): as Tunnuz and Jim T have pointed out, you may want to save also the contents of the <code>hooks/</code> folder if it contains custom scripts.</p>
|
Obtaining selected item, value or index from drop down list in formview after button press <p>I have a formview with an insertion template. In this template there is a drop down list with a number of items I want users to be able to select from. Beside the drop down list there is a button which I am using to add the selected item from the drop down list to a gridview which also exists in the insertion template.</p>
<p>My problem is that when I click the button to add the selected item from the drop down list the selected item, index or value from the drop down list are not available. I am using a OnClick event handler to catch the event from the button click but I suspect there is some kind of refresh of the template going on here which I am not understanding as nothing appears to be accessible from the button event handler. I don't believe a postback is occurring as I have disabled the CausesValidation property for my button.</p>
| <p>It seems like you are binding your DDL on postbacks as well. If the ddl data isnt hardcoded and you have the call for your ddl databind function in the Page_Load, you need to call the function like this to ensure it is not bound on postback:</p>
<pre><code>if(!IsPostBack)
{
BindDDL();
}
</code></pre>
<p>Otherwise we need more information to help you and please post your code.</p>
|
Eliminating temporary ASP.Net Files <p>How do you prevent ASP.NET from creating too many temporary files? My website creates gigabytes of temporary files, and that overflows the main partition on the server. How do I prevent this from happening?</p>
| <p>Where are these temp files beeing generated? </p>
<p>If it's in the "Temporary ASP.NET Files" folder, it's a result of your application beeing recompiled. Checkout <a href="http://msdn.microsoft.com/en-us/library/ms366723.aspx">MSDN</a> for more information on dynamic compilation. One possible solution could be to <a href="http://blog.cwa.me.uk/2007/10/15/relocating-temporary-aspnet-files/">relocate</a> the temp directory.</p>
<p>You could try <a href="http://msdn.microsoft.com/en-us/library/ms227976.aspx">pre-compiling</a> your site to avoid the generation of temp-files.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.