input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Java keeps lock on files for no apparent reason <p>Despite closing streams in finally clauses I seem to constantly run into cleaning up problems when using Java. File.delete() fails to delete files, Windows Explorer fails too. Running System.gc() helps sometimes but nothing short of terminating the VM helps consistently and that is not an option.</p>
<p>Does anyone have any other ideas I could try? I use Java 1.6 on Windows XP.</p>
<p>UPDATE: FLAC code sample removed, the code worked if I isolated it.</p>
<p>UPDATE:
More info, this happens in Apache Tomcat, Commons FileUpload is used to upload the file and could be the culprit, also I use Runtime.exec() to execute LAME in a separate process to encode the file, but that seems unlikely to cause this since ProcessExplorer clearly indicates that java.exe has a RW lock on the file and LAME terminates fine.</p>
<p>UPDATE: I am working with the assumption that there is a missing close() or a close() that does not get called somewhere in my code or external library. I just can't find it!</p>
| <p>The code you posted looks good - it should not cause the issues you are describing. I understand you posted just a piece of the code you have - can you try extracting just this part to a separate program, run it and see if the issue still happens?
My guess is that there is some other place in the code that does <code>new FileInputStream(path);</code> and does not close the stream properly. You might be just seeing the results here when you try to delete the file.</p>
|
Best way to implement "Post Card Sized" Web Pages <p>If I wanted to create a web page with content about the size of a post card, how would I go about positioning it on the screen?</p>
<p>Horizontally isn't an issue (margins auto); however, centering it vertically is a an issue. </p>
<p>What's the best way of centering the container vertically? Javascript? Should I even be trying to center it vertically, or would you in general prefer a page to start near the top?</p>
<p>Thanks!</p>
| <p>You can do this with CSS. Center a container DIV using 50% left and top. Then simply offset your contained postcard 50% of its width & height back.</p>
<pre><code><div id="postcard_container">
<div id="postcard">
Postcard here
</div>
</div>
#postcard_container {
position:absolute;
display:block;
width:1px;
height:1px;
left:50%;
top:50%;
}
#postcard {
position:absolute;
width:800px;
height:600px;
left:-400px;
top:-300px;
}
</code></pre>
|
VS Builtin web server sends images as octet-stream <p>I am debugging an ASP.NET website which has a lot of javascripts and images using Visual Studio 2008 development web server.</p>
<p>One of the many scripts try to create an <code><img></code> tag on the fly and supply it with a proper <code>src</code> attribute. However, none of the images are loaded and instead alt text are displayed in Firefox, IE and Opera.</p>
<p>Digging further, I copied one of the image link and then paste it in Firefox's address bar and this is what comes up in live headers window:</p>
<pre><code>GET /images/nav/zoomin.png HTTP/1.1
Host: localhost:7777
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6 (.NET CLR 3.5.30729)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
HTTP/1.x 200 OK
Server: ASP.NET Development Server/9.0.0.0
Date: Wed, 25 Feb 2009 16:59:23 GMT
X-AspNet-Version: 2.0.50727
Cache-Control: private
Content-Type: application/octet-stream
Content-Length: 292
Connection: Close
</code></pre>
<p>The problematic part is the <code>Content-Type</code> header which is somehow set to "application/octet-stream" forcing a download operation instead of showing normally inside the <code><img></code> tag.</p>
<p>I am quiet sure that it isn't the javascript that is the problem, because it is code that has been copied verbatim from another application that worked just fine.</p>
<p>I believe I might have misconfigured something somewhere. But I could be wrong, so here's the code that create the HTML tag:</p>
<pre><code>var zin = document.createElement("img");
zin = $Img.Png(zin, Settings.ImageHost + "zoomin.png");
zin.style.top = (this.y + zoomPaddingY) + "px";
zin.style.left = (this.x + zoomPaddingX) + "px";
zin.style.position = "absolute";
$Img.Swap(zin, Settings.ImageHost + "zoomin.png", Settings.ImageHost + "zoomin_active.png");
zin.alt = zin.title = "zoom in";
zin.style.cursor = this.hand;
$Evt.addListener(zin, "click", this.zoomIn, this, true);
// long long scroll ...
controlDiv.appendChild(zin);
</code></pre>
<p>The <code>$Img.Png</code> part is working fine for other PNG images, so it shouldn't be the source of the problem.</p>
<p>What did I did wrong?!?</p>
<p>Thanks for any help!</p>
<p>It's already midnight here... and I'm still working on this little app...</p>
| <p>Are you using a GenericHandler that renders the image?</p>
<p>It would seem like an easy choice to do so.</p>
<p>Eg.</p>
<pre><code>public class RenderImage : IHttpHandler, IReadOnlySessionState
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/png";
context.Response.Clear();
// TODO: Write image data
Bitmap bitmap = ...
bitmap.Save(Response.OutputStream,ImageFormat.Png);
context.Response.End();
}
public bool IsReusable { get { return false; } }
}
</code></pre>
|
iPhone SDK: UIWebView to stop images from loading/downloading <p>How can I use the UIWebView in Xcode so that when it loads up pages it DOESN'T download the images (to cause a faster loading page)?</p>
| <p><code>UIWebView</code> is a pale, poor little shadow of WebKit's full <code>WebView</code>, for which this is easy. <code>-webView:shouldStartLoadWithRequest:navigationType:</code> only gets called for navigation. It doesn't get called for every request like <code>WebPolicyDelegate</code> does on mac. With <code>UIWebView</code>, here's how I would attack this problem:</p>
<p>Implement <code>-webView:shouldStartLoadWithRequest:navigationType:</code> and set it to always return <code>NO</code>. But you'll also take the request and spawn an <code>NSURLConnection</code>. When the <code>NSURLConnection</code> finishes fetching the data, you're going to look through it for any IMG tags and modify them to whatever placeholder you want. Then you will load the resulting string into the <code>UIWebView</code> using <code>-loadHTMLString:baseURL:</code>.</p>
<p>Of course parsing the HTML is not a trivial task on iPhone, and Javascript loaders are going to give you trouble, so this isn't a perfect answer, but it's the best I know of.</p>
|
BinarySearch not having expected results <p>I have populated a sorted list of dates(stored as strings in the format dd/mm/yyyy) from an xml file using xpath.</p>
<p>However when querying the list to see if a date exists within the list I always get negative result(i.e. doesnt exist) even though i have hardcode the query string to match a date within the list.</p>
<p>However, when doing a string compare on the index which contains the queried string I get 0 indicating the strings are identical.</p>
<p>What can cause this odd behaviour?</p>
<p>As requested here is the code</p>
<p>Holidays is populated by:</p>
<pre><code>while (iter.MoveNext())
{
XPathNavigator nav2 = iter.Current;
XPathNodeIterator iter2 = nav2.SelectDescendants("date", "", false);
while (iter2.MoveNext())
{
date = iter2.Current.ToString();
holidays.Add(date);
}
}
return holidays;
</code></pre>
<p>And the search is:</p>
<pre><code>holidays = list.getHolidays();
if(holidays.BinarySearch(DateTime.Now.ToShortDateString()) > 0)
</code></pre>
<p>With the following XML being returned:</p>
<pre><code><date>01/01/2009</date>
<date>25/02/2009</date>
<date>10/04/2009</date>
<date>13/04/2009</date>
<date>04/05/2009</date>
<date>25/05/2009</date>
<date>31/08/2009</date>
<date>25/12/2009</date>
<date>28/12/2009</date>
</code></pre>
| <p>I believe it has to do with the format of the strings. You list is being sorted by day, month, then year, which isn't correct.</p>
<p>You need to format your strings like so:</p>
<p>yyyy/mm/dd</p>
<p>And then sort the list, and your search should work.</p>
<p>If these were dates (as in <a href="http://msdn.microsoft.com/en-us/library/system.datetime.aspx" rel="nofollow"><code>DateTime</code></a>) then the list would sort itself correctly, but since they are strings, and your format doesn't support sorting based on the natural properties of strings, your sort order is all messed up.</p>
|
Test IE6 on Mac OS X <p>I like to be able to fully test compatibility of my web pages on Mac OS X. I have installed Parallels desktop. It works fine, but it uses a lot a of resources...</p>
<p>So I would like to be able to test everything inside OS X. In fact I am looking for Explorer 6 for the Mac.</p>
<p>Any suggestions around?</p>
| <p>IE 6 was never written for the Mac. </p>
<p>You might try VMWare Fusion instead of Parallels; you might have better results with resource usage.</p>
<p>The other solution, as other posters will indicate, is to run IE on OS X via Wine. However, IE 6 on Wine is nothing like guaranteed to be the same as running it on Windows via a VM (VMWare or Parallels). The Wine Apps DB lists IE 6 at the Bronze level (lowest level) of compatibility for Wine. This may not be how you want to validate your application on the IE platform.</p>
|
Using a Delegate with Messages <p>I'm learning about delegates and think I may have found a use for one. Basically what I have is a series of string properties that take in a minimum value and a maximum value, like so:</p>
<pre><code>string weightInvalid(min as int32, max as int32)
</code></pre>
<p>There are several messages like this, all with unique messages but all sharing the same signature of minimum and maximum. I think that a delegate could be used here, but how would I go about doing so? It would really help me to see some code so I could get a grasp on this delegate stuff.</p>
| <p>on c#:</p>
<pre><code>delegate string weightInvalid(int min, int max);
string MyWeightInvalid(int min, int max)
{
return "";
}
string SomeMethod()
{
weightInvalid myFunc = new weightInvalid(MyWeightInvalid);
return myFunc(0, 1);
}
</code></pre>
|
C++ constructor syntax <p>Simple question: are the following statements equivalent? or is the second one doing more implicit things behind the scenes (if so, what?)</p>
<pre><code>myClass x(3);
myClass x = myClass(3);
</code></pre>
<p>Thanks!</p>
| <p>They are not completely identical. The first is called "direct initialization" while the second is called "copy initialization". </p>
<p>Now, the Standard makes up two rules. The first is for direct initialization and for copy initialization where the initializer is of the type of the initialized object. The second rule is for copy initialization in other cases. </p>
<p>So, from that point of view both are termed in one - the first - rule. In the case where you have copy initialization with the same type, the compiler is allowed to elide a copy, so it can construct the temporary you create directly into the initialized object. So you can end up very well with the same code generated. But the copy constructor, even if the copy is elided (optimized out), must still be available. I.e if you have a private copy constructor, that code is invalid if the code in which it appears has no access to it. </p>
<p>The second is called copy-initialization, because if the type of the initializer is of a different type, a temporary object is created in trying to implicitly convert the right side to the left side:</p>
<pre><code>myclass c = 3;
</code></pre>
<p>The compiler creates a temporary object of the type of myclass then when there is a constructor that takes an int. Then it initializes the object with that temporary. Also in this case, the temporary created can be created directly in the initialized object. You can follow these steps by printing messages in constructors / destructors of your class and using the option <code>-fno-elide-constructors</code> for GCC. It does not try to elide copies then. </p>
<p>On a side-note, that code above has nothing to do with an assignment operator. In both cases, what happens is an initialization. </p>
|
What kind of data can apps store in the Mesh (and how) <p>Currently one of our applications is being deployed using ClickOnce
and it creates a SQL Server Compact 3.5 database in the user profile Application Directory (roaming).</p>
<p>I am wondering if Live Mesh would enable us to store this data in the Mesh instead?
Either by storing and accessing the database file directly in/from the Mesh or by
storing the raw data in the Mesh.</p>
<p>Is this something that can be done and how, or is it something that should not be done?
I'm trying to get my head around this whole Live Mesh thing (aside from syncing files).</p>
<p>Any advise, feedback, etc... would be appreciated.</p>
| <p>You can currently use Live Mesh (www.mesh.com) to sync files including database files if you choose. However, be aware that synchronization can result in conflicts if the database is changed in two different locations at the same time. I don't think you want your conflict resolution to happen at the entire-database level...</p>
<p>You can also try the Live Framework CTP (developer.mesh-ctp.com - sign-up required) and change your app's data access logic to store your data as entries in feeds. The feed-based data model is quite a bit different from a relational database, so this would be a non-trivial effort. There is no referential integrity, and instead of foreign keys you have hyperlinks to resources. Custom user data is stored as DataContract-serialized XML. There is query support, but only for certain generic fields, not for arbitrary user data. Synchronization conflicts can still occur at the individual entry level, but a detailed history of all conflicts is maintained and you can display this to the user to let them choose which entry to use to resolve the conflict.</p>
<p>Your app can choose to program directly against the cloud API, or you can install the Live Framework Client and program against an identical local API.</p>
<p>The following blog post details the various options for storing data in Live Framework <a href="http://nmackenzie.spaces.live.com/blog/cns!B863FF075995D18A!163.entry" rel="nofollow">http://nmackenzie.spaces.live.com/blog/cns!B863FF075995D18A!163.entry</a></p>
<p>You can check out the documentation for Live Framework <a href="http://msdn.microsoft.com/en-us/library/dd156996.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/dd156996.aspx</a></p>
<p>There are a number of other good resources (training videos, screencasts, walkthroughs, hands-on-labs, blog posts, etc.) in the sticky threads on the Live Framework forum <a href="http://social.msdn.microsoft.com/Forums/en-US/liveframework/threads/" rel="nofollow">http://social.msdn.microsoft.com/Forums/en-US/liveframework/threads/</a></p>
|
Good ASP.NET excel-like Grid control? <p>We are looking for an ASP.NET compatible data grid that allows for multi-line editing similar to Excel or a WinForms data grid. It must also support very basic keyboard input (tab, arrow keys, return). Note that we are <strong>not</strong> looking for Excel capabilities (functions, formatting, formulas) ... just a grid for fast data entry.</p>
<p>I've looked at Telerik, Infragistics, ComponentOne, DevExpress, and many others ... all their support teams have said that the controls either do not support multi-line, or do so in such a clunky way that it would be unusable. </p>
<p>Has anyone used any Excel-like grids that they can recommend? The client-side grids seemed closer to what we needed, with Sigma Widgets ( <a href="http://www.sigmawidgets.com/products/sigma%5Fgrid2/demos/example%5Fcolumn%5Feditor.html">example</a> ) being the closest I've found so far. Extjs's grid was too inflexible, and the jQuery grid was too buggy. </p>
| <p>It does not exist today. There are products such as those you have mentioned which have tried, but in my experience none of them will make an experienced Excel user happy.</p>
<p>My company makes Excel compatible spreadsheet components for use with Windows Forms and ASP.NET. We have been getting this question for years, so we have of course considered building one because it looks like a good business. But HTML / JavaScript is just not a suitable platform for building something which "feels right" to users who want it to work like Excel - IMO.</p>
<p>We have settled on the idea of building a spreadsheet control for Silverlight. I believe this will give you the best of both worlds - cross platform rich interactive spreadsheet in the browser which any Excel user would be comfortable with. Unfortunately, that is not going to happen this month or next...</p>
<p>At my previous company, we actually built a spreadsheet component as a Netscape Plugin, as an ActiveX control and as a Java Applet. They had a little bit of success, but none of these technologies ever became ubiquitous in the enterprise for various reasons. I believe Microsoft is finally getting it right with Silverlight and that Silverlight will become the gold standard for browser based Line of Business applications in the Enterprise.</p>
<p>EDIT:</p>
<p>I should have mentioned that the product I alluded to above is Formula One / NET (Netscape Plugin released ~1995), Formula One / ActiveX and Formula One for Java - which is now sold by Actuate as e.Spreadsheet. I left in 2002, but AFAIK they still maintain the Java Applet which is probably the best example of an Excel like UI in the browser (I have no interest in the product any more - in fact we compete to some extent with e.Spreadsheet and intend to have a better answer with a Silverlight control in the future). I did not mention it by name in my original answer because it is a Java product - not a .NET product - but it is a potential answer even for an ASP.NET web site.</p>
<p>Lloyd Cotten correctly comments that Google Docs is an example of a spreadsheet built with HTML / JavaScript. Lloyd says Google Docs "definitely 'feels right' in its similarity to Excel". While I respect Lloyd's opinion, in my experience Google Docs does not 'feel right'. Perhaps this is because I'm a spreadsheet guy. I do know that we talk to potential customers almost every day who are trying to solve the problem of the OP, and they have all looked and cannot find one they are happy with - but of course they would not be calling us if they had so we are dealing with a biased sample and I understand that.</p>
<p>So I just want to clarify that there are in fact plenty of examples of HTML / JavaScript grids and spreadsheets which are usable. It's just that I don't want to have to use them because I expect certain keys to do certain things and a particular level of responsiveness which is just not there today with any of the HTML / JavaScript solutions I have tried (and I look at them regularly because my company could definitely sell such a product if it were feasible to build one that we could be proud of).</p>
|
Why does this code cause an "illegal start of expression" exception? <p>These are my questions:</p>
<ol>
<li><p>I'm getting a couple of errors on the line "public static boolean validNumCheck(String num){" - "illegal start of expression", "';' expected", and "')' expected".</p></li>
<li><p>How can I give the user 3 tries in total for each number? I believe right now the programme asks the user for 3 numbers and gives them 3 tries in total to get the numbers correct (My explanations suck... read the code to get a better idea of what I mean).</p></li>
</ol>
<p>This is my code:</p>
<pre><code>import javax.swing.JOptionPane;
public class Assignment3 {
public static void main (String[] args){
final int MAX_TRIES = 3;
int[] attempts= new int[2];
String[] getNumber= new String [2];
//Ask the user for 3 integers.
while(attempts[0]<MAX_TRIES){
getNumber[0]= JOptionPane.showInputDialog(null,"Please enter an integer between 0-200.");
//Pass the value to validNumChek
validNumCheck (getNumber);
//If it is not a valid number give the user 3 more tries.
if (getNumber== false){
while(attempts[1]<MAX_TRIES){
getNumber[1]= JOptionPane.showInputDialog(null,"Please enter an integer between 0-200.");
attempts[1]++;}
}
attempts[0]++;
}
//Parse the string to an integer and check if it is a valid number.
public static boolean validNumCheck(String num){
int number;
try {
number = Integer.parseInt(num);
return number >= 0 && number <= 200;
}catch(NumberFormatException e){
//If it is not a valid number return false.
return false;
}
}
}
</code></pre>
| <p>I think it is important to create a pseudo code or algorithm of the problem <strong>first</strong> and then if it works deal with the programming <strong>later</strong>. Otherwise you'll be solving two things at the same time 1. Problem logic and 2. Implementation details.</p>
<p>This is how I would do it.</p>
<pre><code>//The three numbers should be entered by a user in the main method.
MAIN PROGRAM starts
declare a , b , c as numbers
//The numbers should be positive and less than 200.
// see validNumCheck below.
//part 1.If not, the program asks the user to renter the number.
//part 2.The user will have three chances to enter a valid number for each number.
//part 3. If the number is still invalid after the three trials, the program displays an error message to the user and ends.
// ok then read a number and validate it.
attempts = 0;
maxAttempts = 3;
//part 2. three chances... .
loop_while ( attemtps < maxAttempts ) do // or 3 directly.
number = readUserInput(); // part 1. reenter the number...
if( numcheck( number ) == false ) then
attempts = attempts + 1;
// one failure.. try again.
else
break the loop.
end
end
// part 3:. out of the loop.
// either because the attempts where exhausted
// or because the user input was correct.
if( attempts == maxAttemtps ) then
displayError("The input is invalid due to ... ")
die();
else
a = number
end
// Now I have to repeat this for the other two numbers, b and c.
// see the notes below...
MAIN PROGRAM ENDS
</code></pre>
<p>And this would be the function to "validNumCheck" </p>
<pre><code> // You are encouraged to write a separate method for this part of program â for example: validNumCheck
bool validNumCheck( num ) begin
if( num < 0 and num > 200 ) then
// invalid number
return false;
else
return true;
end
end
</code></pre>
<p>So, we have got to a point where a number "a" could be validated but we need to do the same for "b" and "c"</p>
<p>Instead of "copy/paste" your code, and complicate your life trying to tweak the code to fit the needs you can create a function and delegate that work to the new function. </p>
<p>So the new pseudo code will be like this:</p>
<pre><code>MAIN PROGRAM STARTS
declare a , b , c as numbers
a = giveMeValidUserInput();
b = giveMeValidUserInput();
c = giveMeValidUserInput();
print( a, b , c )
MAIN PROGRAM ENDS
</code></pre>
<p>And move the logic to the new function ( or method ) </p>
<p>The function giveMeValidUserInput would be like this ( notice it is almost identical to the first pseudo code ) </p>
<pre><code>function giveMeValidUserInput() starts
maxAttempts = 3;
attempts = 0;
loop_while ( attemtps < maxAttempts ) do // or 3 directly.
number = readUserInput();
if( numcheck( number ) == false ) then
attempts = attempts + 1;
// one failure.. try again.
else
return number
end
end
// out of the loop.
// if we reach this line is because the attempts were exhausted.
displayError("The input is invalid due to ... ")
function ends
</code></pre>
<p>The validNumCheck doesn't change.</p>
<p>Passing from that do code will be somehow straightforward. Because you have already understand what you want to do ( analysis ) , and how you want to do it ( design ).</p>
<p>Of course, this would be easier with experience. </p>
<p>Summary </p>
<p>The <a href="http://stackoverflow.com/questions/137375/process-to-pass-from-problem-to-code-how-did-you-learn">steps to pass from problem to code are</a>:</p>
<ol>
<li><p>Read the problem and understand it ( of course ) .</p></li>
<li><p>Identify possible "functions" and variables.</p></li>
<li><p>Write how would I do it step by step ( algorithm )</p></li>
<li><p>Translate it into code, if there is something you cannot do, create a function that does it for you and keep moving.</p></li>
</ol>
|
How do I get intellisense for WCF Ajax Services? <p>I've finally got Intellisense working for JQuery by applying patch KB958502 to Visual Studio 2008 and including this line:</p>
<pre><code>/// <reference path="JQuery\jquery-1.3.2.js"/>
</code></pre>
<p>at the top of my .js files. Now I'm trying to figure out how to get JavaScript intellisense for the client proxies generated by the ScriptManager's ScriptReference elements (as shown here):</p>
<pre><code> <asp:ScriptManager ID="ScriptManager1" runat="Server" EnablePartialRendering="false" AsyncPostBackTimeout="999999">
<Services>
<asp:ServiceReference path="../Services/DocLookups.svc" />
</Services>
</asp:ScriptManager>
</code></pre>
<p>The client proxies are working -- i.e. I can make calls through them, but I'm getting no Intellisense.</p>
<p>My service is defined with a .svc file:</p>
<pre><code><%@ ServiceHost Language="C#" Debug="true" Service="Documents.Services.DocLookups" CodeBehind="~/App_Code/DocLookups.cs" %>
</code></pre>
<p>The code behind file looks like:</p>
<pre><code>[ServiceContract(Namespace = "Documents.Services", Name = "DocLookups")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class DocLookups {
...
</code></pre>
<p>a sample method in this class is:</p>
<pre><code> //Called at the begining of the page to fill in the category list
[OperationContract]
public SelectOption[] GetCategoriesForSelectList()
{
SelectOption[] Result;
IDocumentRepository repository = new DocumentEntityRepository(ConnectionString);
Result = (from cat in repository.GetDocCategories()
select new SelectOption(cat.Category_ID.ToString(), cat.CategoryName)).ToArray();
if (Result.Length > 0)
Result[0].Selected = true; //Select first item
return Result;
}
</code></pre>
<p>and it uses a data contract defined like this:</p>
<pre><code>namespace Documents.Services {
[DataContract]
public class SelectOption
{
//A useful DTO to use when filling a <select> element with options
public SelectOption(string optionValue, string optionText) {
OptionValue = optionValue;
OptionText = optionText;
Selected = false;
}
public SelectOption(string optionValue, string optionText, bool selected) {
OptionValue = optionValue;
OptionText = optionText;
Selected = selected;
}
[DataMember]
public string OptionValue { get; set; }
[DataMember]
public string OptionText { get; set; }
[DataMember]
public bool Selected { get; set; }
}
</code></pre>
<p>}</p>
<p>In my javascript files, a call to this service looks like:</p>
<pre><code>Documents.Services.DocLookups.GetCategoriesForSelectList(...
</code></pre>
<p>but I get no Intellisense (for example, if I type Documents. nothing pops up). I don't get intellisense for either the generated methods or the [DataContract] types used by the methods. </p>
<p>I believe that I am <strong>supposed</strong> to get Intellisense for these proxies and types, but can't figure out what I might be doing wrong. TIA.</p>
| <p>Did
<code>/// <reference path="../Services/DocLookups.svc" /></code>
not work?</p>
|
PHP Warning: Too many open files -- any ideas? <p>I'm running PHP 5.2 on Fedora, and I keep getting this warning after about 1000 iterations of my loop, which means the program has stopped working and needs to be restarted. I could set this up to exit after 1000 iterations and restart via a cron shortly thereafter, but that feels like the coward's way out. The loop follows; I should add that <code>get_load()</code> preforms a <code>file_get_contents()</code> call.</p>
<pre><code>while ($row = select_row($sql))
{
while (($load = get_load()) > 10)
{
echo "Going to sleep (load: ".$load.")\n";
sleep(60*3);
}
$id = $row['id'];
foreach ($sizes as $abbr=>$size)
{
if($row[$size] != "yes")
{
continue;
}
$filename = "/images/".$abbr."/".$id.".jpg";
$tmp_file = "/tmp/".$id.".jpg";
if ($size == "large")
{
//We want to progressively interlace our large bookcovers because it saves on filesave above 10K.
$cmd = "convert -strip -interlace Plane ".$filename." ".$tmp_file;
}
else
{
$cmd = "convert -strip ".$filename." ".$tmp_file;
}
$convert = popen($cmd." 2>&1", "r");
if (is_resource($convert))
{
echo fgets($convert);
if(pclose($convert) == 0)
{
//Upload converted file to remote server
}
unlink($tmp_file);
}
}
</code></pre>
<p>Edit: After reading the first two answers, I realized that in taking out the file uploading code that wasn't relevant to my problem, I took out my <code>pclose()</code> statement. Put in the <code>pclose()</code> as it appears in my code.</p>
<p>Further edit: Posted <code>get_load()</code> as requested</p>
<pre><code>function get_load()
{
$load = explode(" ", file_get_contents("/proc/loadavg"));
return $load[0];
}
</code></pre>
| <p>You should close the pointer after using it with <a href="http://docs.php.net/pclose" rel="nofollow"><code>pclose</code></a>.</p>
|
IIS7 - only serves up one page at a time. It's a making me crAzY! <p>Situation: Classic ASP application, using a custom Application Pool. Default settings.</p>
<p>On <em>some</em> IIS7 machines, IIS decides to serve only one page at a time. So if multiple load any pages from a site, each one has to load in succession.</p>
<p>e.g. If I load <a href="http://foo.com/default.asp">http://foo.com/default.asp</a> from one browser, and from another machine I load <a href="http://foo.com/differenturl.asp">http://foo.com/differenturl.asp</a>, the first has to finish before the other will load. It's almost like the w3p process is single threaded.</p>
<p>Note, there is a setting called MaxProcesses in the Advanced Settings for IIS that says "Set this to greater than 1 to create a Web Garden" (whatever that is). This does NOT solve the problem because this spawns multiple processes with their own session state etc, and when you load <a href="http://foo.com/default.asp">http://foo.com/default.asp</a> there's no way to guarantee you get assigned to the same process.</p>
<p>The problem revealed itself because we have a diagnostic page which is written in ASP that creates and ActiveX control which loads a url on the website and returns the results.</p>
<p>So, diagnostics.asp loads and in the code on the server side it creates a small web control that loads (think XMLHTTP control) default.asp on the same server.</p>
<p>This page will NEVER finish loading, because the server is waiting for the diagnostics.asp page to finish before it serves the default.asp page. Deadlock!</p>
<p>This works fine on every IIS6 machine out there, and I believe there are some IIS7 servers where it works fine too.</p>
<p>I've verified it's not a result of our quirky diagnostic either. Loading multiple tabs from one machine, or even separate machines will show that the web process handles them one at a time.</p>
<p><hr /></p>
<p><strong>Correct Answer</strong> by AnthonyWJones: Server Side debugging was turned on in IIS7. This puts IIS into single threaded mode.</p>
| <p>In IIS manager click on the application in the tree.</p>
<p>Double click ASP under the IIS section.</p>
<p>Expand "Debugging Properties"</p>
<p>Ensure both "Enable Client-side Debugging" and "Enable Server-side debugging" are set to false.</p>
<p>When debugging is enabled ASP is limited to processing one request at a time in a single threaded manner.</p>
|
How to get at contents of Forms Authentication ticket with PHP <p>I need to undo the following ASP.Net processes in PHP so I can get at the username and expiration date in a ticket. I've decrypted the 3DES encryption (step 3 below) but I'm not sure what I need to do next. Is the string that results from decryption a byte array? Should I be able to convert it to ascii? (Because it doesn't).</p>
<p>What ASP.Net does to create ticket: </p>
<ol>
<li>Serialize username, expiration, other data (which I don't care about). Create a byte array. </li>
<li>Sign the ticket using SHA1 (the sig is the last 20 bytes) </li>
<li>Encrypt the ticket with 3DES (which I've unencrypted).</li>
</ol>
<p>I get back something that looks like this: </p>
<blockquote>
<p>6E 85 A4 39 71 31 46 BB A3 F6 BE 1A 07 EE A4 CE 5F 03 C8 D1 4C 97 5D 6A 52 D1 C4 82 75 5E 53 06 7B 1D D2 4D BF 22 40 F7 F4 B8 8D B0 C3 EC E5 BE F7 52 C2 DF 00 7A D1 CB BC 76 4B 10 33 2D 1A B4 15 A7 BB D6 9D BF 41 69 D2 C4 43 4A 26 95 01 F2 06 AA 46 2C 96 CC AD DC 08 59 C0 64 B6 EE 2C 5F CA ED 8B 92 1C 80 FD FF DC 61 67 28 59 CB E6 71 C6 C3 72 0E D0 32 69 22 57 4E 40 2B DA 67 BA 7F F1 C5 78 BC DF 80 8C D8 F2 8B 19 E2 A4 4F 7C 8C D9 97 37 BD B5 5B 0A 66 9B DD E7 DC 7B 78 F4 F8 </p>
</blockquote>
<p>It doesn't map to ascii, what do I do next? I have the SHA1 validation key. Thanks for any help!</p>
| <p>I don't think this is possible...</p>
<p><strong>A few pre-requisite questions:</strong></p>
<ul>
<li>Are you sure you have decrypted the string correctly, with the correct <code>MachineKey</code> value and decryption algorithm? I know ASP.NET 1.0 used 3DES but newer versions generally use AES by default.</li>
<li>Why are you accessing this data in the first place? The <code>FormsAuthenticationTicket</code> was not intended to be "broken", and if you were going to access these values from a different language you may consider rolling your own scheme.</li>
</ul>
<p><strong>Some noteworthy observations:</strong></p>
<p>Buried <code>in FormsAuthentication.Decrypt()</code> is a call to <code>UnsafeNativeMethods.CookieAuthParseTicket(...)</code>. Here is the signature:</p>
<pre><code>[DllImport("webengine.dll", CharSet=CharSet.Unicode)]
internal static extern int CookieAuthParseTicket(byte[] pData, int iDataLen, StringBuilder szName, int iNameLen, StringBuilder szData, int iUserDataLen, StringBuilder szPath, int iPathLen, byte[] pBytes, long[] pDates);
</code></pre>
<p>This parses what looks to be a byte array returned from <code>MachineKeySection.HexStringToByteArray()</code> (apparently a function that appears to decode the string using UTF-8) into the individual members of the <code>FormsAuthenticationTicket</code>.</p>
<p>I can only assume that no matter which decoding method you use (ASCII, UTF-16, etc.) you're not going to get the data back unless you know Microsoft's implementation hidden in this native method.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms998288.aspx#paght000007%5Fformsauthenticationtickets" rel="nofollow">MSDN</a> may also offer some help.</p>
|
How to detect if an aspx page was called from Server.Execute? <p>I have the following example page structure:</p>
<ul>
<li>Webpage.aspx</li>
<li>Script.aspx</li>
</ul>
<p>If I call <code>Server.Execute("Script.aspx")</code> from Webpage.aspx, how can I detect in Script.aspx that it was called from Webpage.aspx and not directly from a web browser?</p>
<p><em>I've tried checking the Referrer but this only seems to return domain and not the script.</em></p>
<p><em>I'm using ASP.NET Web Forms on .NET 3.5</em></p>
| <p>Since Server.Execute runs the new page with the same context as the original page, all the properties of Request should still reflect the original request to Webpage.aspx (except for CurrentExecutionFilePath, which hopefully contains "/Script.aspx"). Request.Path should contain "/Webpage.aspx", while Request.Url will give the full Uri object if you need to see the domain or querystring.</p>
<p>You can also add values to Context.Items before calling Server.Execute and read them in Script.aspx</p>
|
How can I login to Active Directory with C#? <p>How can I login to AD without logout from current user and get new logged user's rights. (OS: Windows XP)</p>
<h3>Note:</h3>
<p>Not to Modify AD or something like this.Only wanna to login with another user from C# and getting new login's permissions/rights. (I wanna use this rights not only in current thread but also whole explorer. Like deleting files, creating directories, changing Network options.)</p>
<p>Is this possible?</p>
| <p>You can use impersonation to change thread identity to a different user, given a valid username and password. There is no way to change the user identity for the whole shell other than logging in as a different user manually, but anything executed on the thread you impersonate on will receive the new rights.</p>
<p>The .NET 1.1 way, using P/Invoke:</p>
<ul>
<li><a href="http://www.codeproject.com/KB/cs/cpimpersonation1.aspx" rel="nofollow">Windows Impersonation using C#</a></li>
<li><a href="http://www.codeproject.com/KB/cs/zetaimpersonator.aspx" rel="nofollow">A small C# Class for impersonating a User</a></li>
</ul>
<p>The .NET 2+ way, using Thread.CurrentPrincipal:</p>
<ul>
<li><a href="http://alt.pluralsight.com/wiki/default.aspx/Keith.GuideBook/HowToImpersonateAUserGivenHerToken.html" rel="nofollow">How To Impersonate A User Given Her Token</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/wefzhcez.aspx" rel="nofollow">Directly Accessing a Principal Object</a></li>
</ul>
|
Extract an object schema from wsdl <p>I have an wsdl file that describes a group of objects, but I want to extract the definition just from a subset of them, is this possible, and if so what's the best way to achieve this?
My goal is to generate an XSD schema for that subset.</p>
<p>What if you are not using the WSDL generation tools in .NET? Is there a good way to accomplish this using other tools? I am using Java, trying to interface with a web service. I have a library for manipulating xml documents, which requires an xsd. I also have a library for simple SOAP interactions, which makes using Axis overkill. It would be great if I could easily extract an XSD from the WSDL.</p>
| <p>If you know precisely what objects you want to extract from the schema you could take the wsdl file, run it through a XSL tranformation to keep the pieces you want (or remove the things you don't). </p>
|
DotNetNuke module development with webservices <p>I need to deploy a webservice as part of a DotNetNuke 4.x module that I'm creating - but am not sure how I can do that and know that it'll always stay in the same place. How can I add an asmx file to my module project, and when I create my .DNN file specify where the webservice will end up? I want to reference the webservice from inside the ascx file in the module using the "~/webservices/webservice.asmx" format. </p>
<p>Does DotNetNuke have a way to specify in the .DNN file where the webservices will end up on the site? And if so, will I still be able to reference them with root anchored tags like ~/myservice.asmx?</p>
| <p>You can include the ASMX file by including a element in the <code><files></code> section:</p>
<pre><code><files>
<file>
<name>YourWebService.asmx</name>
<path></path>
</file>
</files>
</code></pre>
<p>Generally, you don't need to specify a path.</p>
<p>Alternatively, you can include a Resources.zip file with your package which will include any files other than those that DNN needs to process during installation (e.g. Assemblies and SqlDataProvider files).</p>
<p>The benefit of this is maintainability. Using Resources.zip will keep you from having to edit the manifest file over and over...</p>
<p>The contents of the zip file will simply be unpacked into the root module directory (e.g. /DesktopModules/YourModule/*). If there is a file structure within your zip file it will be maintained.</p>
<p>You'll want to add TheNameOfYourFile.zip To your manifest file under the element.</p>
<p><code>[snip]</code></p>
<pre><code><folder>
<name>Your Module</name>
<friendlyname>Your Module</friendlyname>
<foldername>YourModule</foldername>
<modulename>YourModule</modulename>
<description>A module for DotNetNuke websites.</description>
<version>01.00.00</version>
<resourcefile>Resources.zip</resourcefile>
<businesscontrollerclass></businesscontrollerclass>
<modules>
<module>
</code></pre>
<p><code>[/snip]</code></p>
<p>As for referencing it in your module - I suggest using:</p>
<pre><code><%=ResolveUrl("~/DesktopModules/YourModule/Services.asmx")%>
</code></pre>
|
Entity Framework: Update multiple rows in set with data from other set <p>I simply want to achieve this line of SQL:</p>
<pre><code>UPDATE table1
SET table1.col = table2.col
FROM table2 INNER JOIN
table1 ON table2.id = table1.id
</code></pre>
<p>How can that be done using Entity Framework with minimal number of round-trips?
All I can think of is using foreach to loop through my <code>table2</code> and update it's related entry in <code>table1</code>, but that leads to a whole lot of round-trips, doesn't it?</p>
| <p>There is, unfortunately, <a href="http://msdn.microsoft.com/en-us/library/bb387145.aspx" rel="nofollow">no UPDATE in Entity SQL</a> at present. A workaround is to <a href="http://blogs.msdn.com/alexj/archive/2007/12/07/rolling-your-own-sql-update-on-top-of-the-entity-framework-part-1.aspx" rel="nofollow">use regular SQL</a>. Without this, keep the number of round trips to a minimum by loading all required rows from both tables at once and calling SaveChanges as few times as possible.</p>
|
How to distinguish between multiple input devices in C# <p>I have a barcode scanner (which acts like a keyboard) and of course I have a keyboard too hooked up to a computer. The software is accepting input from both the scanner and the keyboard. I need to accept only the scanner's input. The code is written in C#. Is there a way to "disable" input from the keyboard and only accept input from the scanner?</p>
<p>Note:
Keyboard is part of a laptop...so it cannot be unplugged. Also, I tried putting the following code
protected override Boolean ProcessDialogKey(System.Windows.Forms.Keys keyData)
{
return true;
}
But then along with ignoring the keystrokes from the keyboard, the barcode scanner input is also ignored.</p>
<p>I cannot have the scanner send sentinal characters as, the scanner is being used by other applications and adding a sentinal character stream would mean modifying other code.</p>
<p>Also, I cannot use the timing method of determining if the input came from a barcode scanner (if its a bunch of characters followed by a pause) since the barcodes scanned could potentially be single character barcodes.</p>
<p>Yes, I am reading data from a stream.</p>
<p>I am trying to follow along with the article: Distinguishing Barcode Scanners from the Keyboard in WinForms. However I have the following questions:</p>
<ol>
<li>I get an error NativeMethods is inaccessible due to its protection level. It seems as though I need to import a dll; is this correct? If so, how do I do it? </li>
<li>Which protected override void WndProc(ref Message m) definition should I use, there are two implementations in the article?</li>
<li>Am getting an error related to [SecurityPermission( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] error CS0246: The type or namespace name 'SecurityPermission' could not be found (are you missing a using directive or an assembly reference?). How do I resolve this error?</li>
<li>There is also an error on the line containing: if ((from hardwareId in hardwareIds where deviceName.Contains(hardwareId) select hardwareId).Count() > 0) Error is error CS1026: ) expected.</li>
<li>Should I be placing all the code in the article in one .cs file called BarcodeScannerListener.cs?</li>
</ol>
<p>Followup questions about C# solution source code posted by Nicholas Piasecki on <a href="http://nicholas.piasecki.name/blog/2009/02/distinguishing-barcode-scanners-from-the-keyboard-in-winforms/">http://nicholas.piasecki.name/blog/2009/02/distinguishing-barcode-scanners-from-the-keyboard-in-winforms/</a>:</p>
<ol>
<li>I was not able to open the solution in VS 2005, so I downloaded Visual C# 2008 Express Edition, and the code ran. However, after hooking up my barcode scanner and scanning a barcode, the program did not recognize the scan. I put a break point in OnBarcodeScanned method but it never got hit. I did change the App.config with the id of my Barcode scanner obtained using Device Manager. There seems to be 2 deviceNames with HID#Vid_0536&Pid_01c1 (which is obtained from Device Manager when the scanner is hooked up). I don't know if this is causing the scanning not to work. When iterating over the deviceNames, here is the list of devices I found (using the debugger):</li>
</ol>
<p>"\??\HID#Vid_0536&Pid_01c1&MI_01#9&25ca5370&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}"</p>
<p>"\??\HID#Vid_0536&Pid_01c1&MI_00#9&38e10b9&0&0000#{884b96c3-56ef-11d1-bc8c-00a0c91405dd}"</p>
<p>"\??\HID#Vid_413c&Pid_2101&MI_00#8&1966e83d&0&0000#{884b96c3-56ef-11d1-bc8c-00a0c91405dd}"</p>
<p>"\??\HID#Vid_413c&Pid_3012#7&960fae0&0&0000#{378de44c-56ef-11d1-bc8c-00a0c91405dd}"<br />
"\??\Root#RDP_KBD#0000#{884b96c3-56ef-11d1-bc8c-00a0c91405dd}"
"\??\ACPI#PNP0303#4&2f94427b&0#{884b96c3-56ef-11d1-bc8c-00a0c91405dd}"
"\??\Root#RDP_MOU#0000#{378de44c-56ef-11d1-bc8c-00a0c91405dd}"
"\??\ACPI#PNP0F13#4&2f94427b&0#{378de44c-56ef-11d1-bc8c-00a0c91405dd}"</p>
<p>So there are 2 entries for HID#Vid_0536&Pid_01c1; could that be causing the scanning not to work?</p>
<p>OK so it seems that I had to figure out a way to not depend on the ASCII 0x04 character being sent by the scanner...since my scanner does not send that character. After that, the barcode scanned event is fired and the popup with the barcode is shown. So thanks Nicholas for your help. </p>
| <p><a href="https://web.archive.org/web/20150108213851/http://nicholas.piasecki.name/blog/2009/02/distinguishing-barcode-scanners-from-the-keyboard-in-winforms">You could use the Raw Input API to distinguish between the keyboard and the scanner like I did recently.</a> It doesn't matter how many keyboard or keyboard-like devices you have hooked up; you will see a <code>WM_INPUT</code> before the keystroke is mapped to a device-independent virtual key that you typically see in a <code>KeyDown</code> event.</p>
<p>Far easier is to do what others have recommended and configure the scanner to send sentinel characters before and after the barcode. (You usually do this by scanning special barcodes in the back of the scanner's user manual.) Then, your main form's <code>KeyPreview</code> event can watch those roll end and swallow the key events for any child control if it's in the middle of a barcode read. Or, if you wanted to be fancier, you could use a low-level keyboard hook with <code>SetWindowsHookEx()</code> to watch for those sentinels and swallow them there (advantage of this is you could still get the event even if your app didn't have focus).</p>
<p>I couldn't change the sentinel values on our barcode scanners among other things so I had to go the complicated route. Was definitely painful. Keep it simple if you can!</p>
<p>--</p>
<p><strong>Your update, seven years later:</strong> If your use case is reading from a USB barcode scanner, Windows 10 has a nice, friendly API for this built-in in <code>Windows.Devices.PointOfService.BarcodeScanner</code>. It's a UWP/WinRT API, but you can use it from a regular desktop app as well; that's what I'm doing now. Here's some example code for it, straight from my app, to give you the gist:</p>
<pre><code>{
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using Windows.Devices.Enumeration;
using Windows.Devices.PointOfService;
using Windows.Storage.Streams;
using PosBarcodeScanner = Windows.Devices.PointOfService.BarcodeScanner;
public class BarcodeScanner : IBarcodeScanner, IDisposable
{
private ClaimedBarcodeScanner scanner;
public event EventHandler<BarcodeScannedEventArgs> BarcodeScanned;
~BarcodeScanner()
{
this.Dispose(false);
}
public bool Exists
{
get
{
return this.scanner != null;
}
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
public async Task StartAsync()
{
if (this.scanner == null)
{
var collection = await DeviceInformation.FindAllAsync(PosBarcodeScanner.GetDeviceSelector());
if (collection != null && collection.Count > 0)
{
var identity = collection.First().Id;
var device = await PosBarcodeScanner.FromIdAsync(identity);
if (device != null)
{
this.scanner = await device.ClaimScannerAsync();
if (this.scanner != null)
{
this.scanner.IsDecodeDataEnabled = true;
this.scanner.ReleaseDeviceRequested += WhenScannerReleaseDeviceRequested;
this.scanner.DataReceived += WhenScannerDataReceived;
await this.scanner.EnableAsync();
}
}
}
}
}
private void WhenScannerDataReceived(object sender, BarcodeScannerDataReceivedEventArgs args)
{
var data = args.Report.ScanDataLabel;
using (var reader = DataReader.FromBuffer(data))
{
var text = reader.ReadString(data.Length);
var bsea = new BarcodeScannedEventArgs(text);
this.BarcodeScanned?.Invoke(this, bsea);
}
}
private void WhenScannerReleaseDeviceRequested(object sender, ClaimedBarcodeScanner args)
{
args.RetainDevice();
}
private void Dispose(bool disposing)
{
if (disposing)
{
this.scanner = null;
}
}
}
}
</code></pre>
<p>Granted, you'll need a barcode scanner that supports the USB HID POS and isn't just a keyboard wedge. If your scanner is just a keyboard wedge, I recommend picking up something like a used Honeywell 4600G off eBay for like $25. Trust me, your sanity will be worth it.</p>
|
Best way to lay out multiple projects in AccuRev <p>I am in the process of switching to AccuRev from another SCM. I have quite a few projects and am struggling how to properly lay them out in AccuRev. </p>
<p>I have quite a few related projects and would like to keep them in a single depot, but I haven't found out how to separate them so you can keep track of individual projects. In other words, I don't want to have to pull <em>every</em> project at once. </p>
<p>My project layout now is</p>
<pre><code>-Project Group
- Sub project 1
- Sub project 2
-Project 2
-Project etc...
</code></pre>
<p>Does anyone have suggestions how to manage these projects in a single depot or should I just go with multiple depots (one for each project)?</p>
| <p>The concept in Accurev is that the root of your depot represents all of your source code. </p>
<p>You then create per-project streams (branches) where work is performed, and which themselves may split into further streams (patches, revisions etc).</p>
<p>Users then attach their individual workspaces to these streams and promote changes with their work. These changes are then propagated up the hierarchy as necessary.</p>
<p>Each stream has the ability to filter our content from its parent. This filtered content will be invisible in all child streams or workspaces.</p>
<p>So in your example the users working on "Project 2" would create a "Project 2" stream from the depot, and this stream would filter out "Project etc" and so on.</p>
<p>The best hierarchy I have found for Accurev is something like;</p>
<ul>
<li>Projects
<ul>
<li>Project A</li>
<li>Project B</li>
</ul></li>
<li>Common</li>
<li>Middleware</li>
</ul>
<p>Each project then has their own stream that filters out other projects but still keeps the common files.</p>
<p>Accurev is very different to many other SCM packages but it really is an excellent excellent product so stick with it.</p>
|
ASP.NET master pages order of adding scripts <p>I have a master page that adds the jquery library via a registerclientscriptinclude:</p>
<pre><code>Page.ClientScript.RegisterClientScriptInclude(this.GetType(),
"JQuery",
Page.ResolveUrl("~/Scripts/jquery-1.2.6.min.js"));
</code></pre>
<p>In a page that uses that master page I want to include a script that depends on jquery:</p>
<pre><code>Page.ClientScript.RegisterClientScriptInclude(this.GetType(),
"jqplugin1",
Page.ResolveUrl("~/Scripts/jquery.plugin1.compressed.js"));
</code></pre>
<p>This causes a problem because the page's client scripts are written first and then the master pages client scripts (causing the plugin to complain that "jquery" is undefined).</p>
<p>Is there anyway to control the ordering of client script includes? Alternatively any recommendation on how best to control this (temporarily the master page is just including everything... but that's not going to work long term).</p>
| <p>You could re-include the jQuery library in the page, if it's already there it will simply override it, if not it will be added.</p>
|
UpdateModel won't properly convert a boolean value <p>I have a custom object called S2kBool that can be converted to and from a regular Boolean object. Basically, it allows my application to treat boolean values in my legacy database the same way it treats C# booleans. Then problem is, when I attempt to use a check box to set the value of an S2kBool property, it fails.</p>
<p>Code like this works:</p>
<pre><code>public class MyClass {
public S2kBool MyProperty { get; set; }
}
MyClassInstance.MyProperty = true;
</code></pre>
<p>But it's almost like UpdateModel is expecting an actual bool type, rather than an object that can be converted to a bool. I can't really tell, however, since the exception thrown is so vague:</p>
<blockquote>
<p>The model was not successfully updated.</p>
</blockquote>
<p>How can I get around this? Do I need a custom ModelBinder?</p>
<p>Thanks!</p>
| <p>You could have an additional bool property of type bool that when set changes the value of your S2kBool property.</p>
<pre><code>public class MyClass {
public S2kBool MyProperty { get; set; }
public bool MyPropertyBool {
get
{
return (bool)MyProperty;
}
set
{
MyProperty = value;
}
}
}
</code></pre>
<p>You then just have the MyPropertyBool in your html form and the modelbinder won't freak out about it's type.</p>
<p>I use this technique for properties like Password & HashedPassword where Password is the property from the html form that the ModelBinder binds to and in the Password's setter it sets HashedPassword to the hash of it which is then persisted to the database or what ever.</p>
|
Link to open jQuery Accordion <p>I'm trying to open an accordion div from an external link. I see the "navigation: true" option but I'm not sure how to implement it. Do you give each div an id and call the link like this? <a href="http://domain.com/link#anchorid">http://domain.com/link#anchorid</a> </p>
<p>I'm new to jQuery so bear with me. Here is the code I'm using if it helps.</p>
<pre><code><script type="text/javascript">
$(function(){
$("#accordion").accordion({ header: "h2", autoHeight: false, animated: false, navigation: true });
});
</script>
<div id="accordion">
<div>
<h2><a href="#">Services</a></h2>
<div class="services">
<p>More information about all of these services</p>
</div>
</div>
</code></pre>
| <p>The navigation option isn't for panel activation. It's for telling the user where they are. </p>
<p>Using simplified html code:</p>
<pre><code><div id="accordion">
<div>
<h2><a href="#services">Services</a></h2>
<p>More information about all of these services</p>
</div>
<div>
<h2><a href="#about">About</a></h2>
<p>About us</p>
</div>
</div>
</code></pre>
<p>You put the unique ID in the Hyperlink in the title</p>
<p>Then the jQuery (simplified):</p>
<pre><code><script type="text/javascript">
$(function(){
$("#accordion").accordion({ header: "h2", navigation: true });
});
</script>
</code></pre>
<p>The "navigation : true" will enable you to go www.site.com/#about which makes the "about" panel selected. For activation, there are a couple of ways. Perhaps one way is to grab a query string and put it into the jQuery.</p>
<p>With C#</p>
<pre><code>$("#accordion").accordion("activate", '<%= Request.QueryString["id"] %>');
</code></pre>
<p>With PHP</p>
<pre><code>$("#accordion").accordion("activate", '<?php echo $_GET['id']; ?>');
</code></pre>
<p>Which will allow you to specify which panel to open by www.site.com?id=2</p>
|
window.onload vs document.onload <p>Which is more widely supported: <code>window.onload</code> or <code>document.onload</code>?</p>
| <h2>window.onload</h2>
<p><strong>When do they fire?</strong></p>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers.onload">window.onload</a></p>
<ul>
<li>By default, it is fired when the entire page loads, including its content (images, css, scripts, etc.)</li>
<li>In some browsers it now takes over the role of document.onload and fires when the DOM is ready as well.</li>
</ul>
<p>document.onload</p>
<ul>
<li>It is called when the DOM is ready which can be prior to images and other external content is loaded.</li>
</ul>
<p><strong>How well are they supported?</strong></p>
<p>window.onload appears to be the most widely supported. In fact, some of the most modern browsers have in a sense replaced document.onload with window.onload. Browser support issues are most likely the reason why many people are starting to use libraries such as <a href="http://jquery.com/">jQuery</a> to handle the checking for the document being ready like so:</p>
<pre><code>$(document).ready(function() { /* code here */ });
$(function() { /* code here */ });
</code></pre>
<hr>
<p>For the purpose of history:</p>
<p><strong>window.onload vs body.onload</strong></p>
<p>As a note, a similar question was asked on <a href="http://www.codingforums.com/archive/index.php/t-106229.html">codingforums</a> a while back regarding the usage of <code>window.onload</code> over <code>body.onload</code>. The result seemed to be that you should use <strong>window.onload</strong> because it is good to separate your structure from the action.</p>
|
Why is it so difficult to do a loop in T-SQL <p>OK, I know it can be done, I do it quite often, but why so difficult to do a loop in T-SQL? I can think of a ton of reasons I'd want to parse thru a query result set and do something that simply can't be done without a loop, yet the code to setup and execute my loop is > 20 lines.</p>
<p>I'm sure others have a similar opinions so why are we still without a simple way to perform a loop?</p>
<p>An aside: we finally got an UPSERT (aka MERGE) in SQL2008 so maybe all hope isn't lost.</p>
| <p>SQL is a set-based, <a href="http://en.wikipedia.org/wiki/Declarative_programming" rel="nofollow">declarative language</a>; not a procedural or <a href="http://en.wikipedia.org/wiki/Imperative_programming" rel="nofollow">imperative language</a>. T-SQL tries to straddle the two, but it's still built on a fundamentally set-based paradigm.</p>
|
Is there a JAWS-friendly date picker for ASP.NET? <p>Does anyone know of an ASP.NET date picker control that works well with <a href="http://www.freedomscientific.com/products/fs/jaws-product-page.asp" rel="nofollow">JAWS</a>? Barring that, do you have any tips for making the existing ASP.NET date picker control easier to use for JAWS users?</p>
| <p>I doubt you'll have much luck getting the ASP.NET control to be accessible. If I were you, I would look into a client-side version of the control. I found this <a href="http://www.websemantics.co.uk/tutorials/accessible%5Fdate%5Fpicker%5Fcalendar/" rel="nofollow">accessible date picker calendar</a> online that is Javascript-based. You will likely have to do a little tweaking to make it work in your app.</p>
<p>Good luck!</p>
|
This BackgroundWorker is currently busy and cannot run multiple tasks concurrently <p>I get this error if I click a button that starts the backgroundworker twice.</p>
<pre><code>This BackgroundWorker is currently busy and cannot run multiple tasks concurrently
</code></pre>
<p>How can I avoid this?</p>
| <p>Simple: Don't start the BackgroundWorker twice.</p>
<p>You can check if it is already running by using the <code>IsBusy</code> property, so just change this code:</p>
<pre><code>worker.RunWorkerAsync();
</code></pre>
<p>to this:</p>
<pre><code>if( !worker.IsBusy )
worker.RunWorkerAsync();
else
MessageBox.Show("Can't run the worker twice!");
</code></pre>
<p>Update:</p>
<p>If you do actually need to launch multiple background tasks at the same time, you can simply create multiple BackgroundWorker objects</p>
|
WPF: Best (reliable) way to translate (move) a Canvas AND monitor Every step <p>I have tried translating (moving) a canvas but I'm having trouble with the timers.</p>
<p>I tried 2 different methods:</p>
<p>First method was with the <code>BeginAnimation</code> function, and the second with <code>DispatcherTimer</code> ticks, but they're both very unreliable.</p>
<p>I need to monitor every step of the translation. With the first method I tried (<code>BeginAnimation</code>), I did the Collision Detection logic in the <code>Changed</code> event, and with the second method (<code>DispatcherTimer</code>) I am doing the Collision Detection logic in the <code>Tick</code> event of the timer.</p>
<p>The problem is that both are very unreliable. In the sense that, in my collision detection logic, the canvas should stop translating when its <code>TranslateTransform</code>'s <code>Y</code> property is <= 0 (technically, if it is monitoring every step, it should stop at 0 every time) , but with both methods I tried, it <strong>varies</strong> when it stops. For example, <strong>sometimes it stops at 0, sometimes at -1, -2, -3 and sometimes even at -4</strong>.</p>
<p>So what's with the discrepancies ? Why doesn't it monitor every step of the way like it's supposed to ?</p>
<p>What can I do to animate this canvas and really monitor every step of the way? An I mean every step...every pixel it moves</p>
| <p>Your problem is that everything is time based, you don't get a callback every time the canvas moves one pixel, you get a callback every time a frame is rendered - and the system doesn't even try to hard to render the frames at a constant rate.</p>
<p>The end result is what you are seeing, sometimes you can get a callback after a 1/2 pixel move because everything went smoothly, the next time it's two pixels move because the GC kicked in mid-frame and the time after that it's a 4 pixels move because Word running in the background stole some CPU cycles to run the spell chekcer.</p>
<p>This is how those things work, you can either deal with it and set a higher tolerance for you collision detection or you can run your simulations off screen on a "virtual timeline" where you can advance objects at whatever pace you want without considering the realities of on-screen animations.</p>
<p>I wrote software that does simulation and collision detection for real aircrafts - and I can tell you it took a lot of hard work, any framework built for animations is optimized for moving things on-screen not for all the work you have to do for high quality simulations and defiantly not for accurate collision detection.</p>
|
limit choices to foreignkey using middleware <p>I'm looking to do something like this:</p>
<p><a href="http://stackoverflow.com/questions/160009/django-model-limitchoicestouser-user">http://stackoverflow.com/questions/160009/django-model-limitchoicestouser-user</a></p>
<p>with some differences.</p>
<p>Some models may explain:</p>
<pre><code>class Job(models.Model):
name = models.CharField(max_length=200)
operators = models.ManyToManyField(User)
class Activity(models.Model):
job = models.ForeignKey(Job)
job_operators = models.ManyToManyField(User, limit_choices_to={user: Job.operators} blank=True, null=True)
</code></pre>
<p>Note: the syntax is not intended to necessarily correct, but illustrative.</p>
<p>Now, I've had some success at getting the current user, using middleware, as some answers on SO depict, however, I was hoping that I might get the current Job, via request.POST, such that, if the Activity were saved, I would be able to discern the current Job, and therefore the subset of Users as operators, that it turn, would be the user set to choose from in the Activity model.</p>
<p>In other words, based on the selections of a ManyToManyField in the parent field, offer that sub-selection to the child field, or, if John, Jim, Jordan and Jesse worked on a Job, choose from only those names to describe work on an Activity, within and attributed to that Job.</p>
<p>BTW, here's my naive attempt in middleware:</p>
<pre><code># threadlocals middleware
try:
from threading import local
except ImportError:
from django.utils._threading_local import local
_thread_locals = local()
def get_current_user():
return getattr(_thread_locals, 'user', None)
def get_current_job():
return getattr(_thread_locals, 'job', None)
class ThreadLocals(object):
"""Middleware that gets various objects from the
request object and saves them in thread local storage."""
def process_request(self, request):
_thread_locals.user = getattr(request, 'user', None)
_thread_locals.job = getattr(request.POST["job"], 'job', None)
</code></pre>
<p>and the Activity model:</p>
<pre><code>operators = modes.ManyToManyField(User, limit_choices_to=dict(Q(User.objects.filter(job==threadlocals.get_current_job)))
</code></pre>
<p>Thank you.</p>
| <p>Ok, I hate to throw a monkey wrench in your works, but you seriously don't need to use threadlocals hacks.</p>
<p>The user is in the request object which means there is no need to extract it using middleware. It's passed as an argument to every view.</p>
<p>The trick to limiting your form choices is therefore to dynamically change the queryset used in the form as opposed to doing a limit choices in the model.</p>
<p>So your form looks like this:</p>
<pre><code># forms.py
from django import forms
from project.app.models import Activity
class ActivityForm(forms.ModelForm):
class Meta:
model Activity
</code></pre>
<p>and your view will look like this:</p>
<pre><code># views.py
...
form = ActivityForm(instance=foo)
form.fields['job_operators'].queryset = \
User.objects.filter(operators__set=bar)
...
</code></pre>
<p>This is just a quick sketch, but should give you the general idea.</p>
<p>If you're wondering how to avoid threadlocals in the admin, please read <a href="http://www.b-list.org/weblog/2008/dec/24/admin/" rel="nofollow">Users and the admin</a> by James Bennett.</p>
<p><strong>Edit:</strong> <a href="http://collingrady.wordpress.com/2008/07/24/useful-form-tricks-in-django/" rel="nofollow">Useful form tricks in Django</a> by Collin Grady also shows an example of dynamically setting the queryset in the form __init__ method, which is cleaner than my example above.</p>
|
Table Prefix Using Castle Active Record <p>Is there anyway to add a prefix to table names at configuration time using Castle Active Record?</p>
<pre><code>[ActiveRecord("Address")]
public class Address : ActiveRecord<Address> {}
</code></pre>
<p>I'd like the actual table created/referenced to be "PRODAddress" or "DEBUGAddress". Is there anything built-in like that I am not seeing?</p>
<p>Thank you,</p>
<p>[EDIT] I've marked the general answer below, but here is the actual code to implement table prefixes for Castle Active Record:</p>
<pre><code>...
ActiveRecordStarter.ModelsCreated += ActiveRecordStarter_ModelsCreated;
ActiveRecordStarter.Initialize(source, typeof(Address));
...
private static void ActiveRecordStarter_ModelsCreated(ActiveRecordModelCollection models, IConfigurationSource source)
{
string tablePrefix = ConfigurationManager.AppSettings["TABLE_PREFIX"];
if (String.IsNullOrEmpty(tablePrefix)) return;
foreach (ActiveRecordModel model in models)
{
model.ActiveRecordAtt.Table = String.Format("{0}{1}", tablePrefix, model.ActiveRecordAtt.Table);
}
}
</code></pre>
| <p>I think you'll have to <a href="http://www.castleproject.org/activerecord/documentation/trunk/manual/xmlconfigref.html" rel="nofollow">configure</a> your own <a href="http://www.hibernate.org/hib%5Fdocs/v3/api/org/hibernate/cfg/NamingStrategy.html" rel="nofollow">INamingStrategy</a></p>
|
C++ Compile problem with WinHttp/Windows SDK <p>Trying to compile a sample http class with the SDK, and getting some strange link errors... I am sure its something to do with a missing option, or directory...</p>
<p>I am no expert in c++ as you can see, but looking for any assistance.</p>
<p>I included my sample class. I also did install the Windows SDK. If you need any other information about my setups or anything, please ask. I'd prefer someone point me to a working WinHttp SDK sample project.</p>
<pre><code>//START OF utils.cpp
#pragma once
#include "stdafx.h"
class http
{
public:
http();
~http();
std::string getText();
};
//END OF utils.cpp
</code></pre>
<p><hr /></p>
<pre><code>//START OF utils.cpp
#include "stdafx.h"
#include "utils.h"
http::http()
{
}
http::~http()
{
}
std::string http::getText()
{
DWORD dwSize = 0;
DWORD dwDownloaded = 0;
LPSTR pszOutBuffer;
BOOL bResults = FALSE;
HINTERNET hSession = NULL,
hConnect = NULL,
hRequest = NULL;
// Use WinHttpOpen to obtain a session handle.
hSession = WinHttpOpen( L"WinHTTP Example/1.0",
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
WINHTTP_NO_PROXY_NAME,
WINHTTP_NO_PROXY_BYPASS, 0 );
// Specify an HTTP server.
if( hSession )
hConnect = WinHttpConnect( hSession, L"www.microsoft.com",
INTERNET_DEFAULT_HTTPS_PORT, 0 );
// Create an HTTP request handle.
if( hConnect )
hRequest = WinHttpOpenRequest( hConnect, L"GET", NULL,
NULL, WINHTTP_NO_REFERER,
WINHTTP_DEFAULT_ACCEPT_TYPES,
WINHTTP_FLAG_SECURE );
// Send a request.
if( hRequest )
bResults = WinHttpSendRequest( hRequest,
WINHTTP_NO_ADDITIONAL_HEADERS, 0,
WINHTTP_NO_REQUEST_DATA, 0,
0, 0 );
// End the request.
if( bResults )
bResults = WinHttpReceiveResponse( hRequest, NULL );
// Keep checking for data until there is nothing left.
if( bResults )
{
do
{
// Check for available data.
dwSize = 0;
if( !WinHttpQueryDataAvailable( hRequest, &dwSize ) )
printf( "Error %u in WinHttpQueryDataAvailable.\n",
GetLastError( ) );
// Allocate space for the buffer.
pszOutBuffer = new char[dwSize+1];
if( !pszOutBuffer )
{
printf( "Out of memory\n" );
dwSize=0;
}
else
{
// Read the data.
ZeroMemory( pszOutBuffer, dwSize+1 );
if( !WinHttpReadData( hRequest, (LPVOID)pszOutBuffer,
dwSize, &dwDownloaded ) )
printf( "Error %u in WinHttpReadData.\n", GetLastError( ) );
else
printf( "%s", pszOutBuffer );
// Free the memory allocated to the buffer.
delete [] pszOutBuffer;
}
} while( dwSize > 0 );
}
// Report any errors.
if( !bResults )
printf( "Error %d has occurred.\n", GetLastError( ) );
// Close any open handles.
if( hRequest ) WinHttpCloseHandle( hRequest );
if( hConnect ) WinHttpCloseHandle( hConnect );
if( hSession ) WinHttpCloseHandle( hSession );
return "";
}
//END OF utils.cpp
</code></pre>
<p><hr /></p>
<pre><code>1>------ Build started: Project: winagent, Configuration: Debug Win32 ------
1>Compiling...
1>utils.cpp
1>Linking...
1> Creating library C:\winagent\Debug\winagent.lib and object C:\winagent\Debug\winagent.exp
1>utils.obj : error LNK2019: unresolved external symbol __imp__WinHttpCloseHandle@4 referenced in function "public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall http::getText(void)" (?getText@http@@QAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ)
1>utils.obj : error LNK2019: unresolved external symbol __imp__WinHttpReadData@16 referenced in function "public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall http::getText(void)" (?getText@http@@QAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ)
1>utils.obj : error LNK2019: unresolved external symbol __imp__WinHttpQueryDataAvailable@8 referenced in function "public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall http::getText(void)" (?getText@http@@QAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ)
1>utils.obj : error LNK2019: unresolved external symbol __imp__WinHttpReceiveResponse@8 referenced in function "public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall http::getText(void)" (?getText@http@@QAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ)
1>utils.obj : error LNK2019: unresolved external symbol __imp__WinHttpSendRequest@28 referenced in function "public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall http::getText(void)" (?getText@http@@QAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ)
1>utils.obj : error LNK2019: unresolved external symbol __imp__WinHttpOpenRequest@28 referenced in function "public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall http::getText(void)" (?getText@http@@QAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ)
1>utils.obj : error LNK2019: unresolved external symbol __imp__WinHttpConnect@16 referenced in function "public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall http::getText(void)" (?getText@http@@QAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ)
1>utils.obj : error LNK2019: unresolved external symbol __imp__WinHttpOpen@20 referenced in function "public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall http::getText(void)" (?getText@http@@QAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ)
1>C:\winagent\Debug\winagent.exe : fatal error LNK1120: 8 unresolved externals
1>Build log was saved at "file://c:\winagent\Debug\BuildLog.htm"
1>winagent - 9 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
</code></pre>
| <p>If you check the MSDN reference for the WinHttp* functions you will see that you need to link with the library Winhttp.lib.</p>
<p>Open the project settings, select the linker options then 'input' and add WinHttp.lib to the 'Additional Dependencies' list.</p>
<p>Or you could put</p>
<pre><code>#pragma comment(lib, "winhttp.lib")
</code></pre>
<p>(as previously mentioned) in your source code.</p>
|
What is the best way to escape non-format characters in Oracle's to_char? <p>I am trying to print a date in a select statement, but I need to add a letter to the output:</p>
<pre><code>to_char(date_updated, 'YYYY-MM-DDTHH:mm:ss')
</code></pre>
<p>Oracle does not like the T. I just want the T to be output like the colons and the dashes. Can I escape it with a backslash or something?</p>
| <p>You just need double-quotes around it:</p>
<pre><code>to_char(date_updated, 'YYYY-MM-DD"T"HH:mm:ss')
</code></pre>
|
Why does GNU make delete a file <p>I've got a slightly hackish makefile for running tests:</p>
<pre><code>### Run the tests
tests := tests/test1 tests/test2 ...
test: $(tests)
$(tests): %: %.c
gcc -o $@ $(testflags) $<
$@
</code></pre>
<p>It works, but it makes Make do something I've never seen it do before. My test is currently broken, and causes a bus error. Make gives the following output:</p>
<pre><code>gcc -o tests/test1 [flags blah blah] tests/test1.c
tests/test1
make: *** [tests/test1] Bus error
make: *** Deleting file `tests/test1'
</code></pre>
<p>I'm curious about the last line. I've never seen Make do that before. Why does Make delete the compiled test?</p>
<p>Note: I edited this example pretty heavily to make it simpler. I might have introduced some mistakes.</p>
| <p>Because the target might not have been built correctly. The next time you <code>make</code> the project, it will attempt to rebuild the target. If the file had not been removed, <code>make</code> would have no way of knowing something went wrong. <code>make</code> can't know that the failure was coming from a test rather than the process that builds the target.</p>
<hr>
<p>Whether or not this behavior is desirable in your case depends on the nature of the tests. If you plan on fixing the test so that it does not cause a <code>Bus error</code>, removing the target isn't a big deal. If you want to use the target for debugging later, you'll need to make a change to your make process.</p>
<p>One way to not delete targets is to use the <code>.PRECIOUS</code> target.</p>
<hr>
<p>Another might be:</p>
<pre><code>$(tests): %: %.c
gcc -o $@ $(testflags) $<
-$@
</code></pre>
<p>Not tested, but the <a href="http://www.gnu.org/software/make/manual/make.html#Errors">documentation</a> indicates the target will not be removed:</p>
<blockquote>
<p>When an error happens that make has not been told to ignore, it implies that the current target cannot be correctly remade, and neither can any other that depends on it either directly or indirectly. No further commands will be executed for these targets, since their preconditions have not been achieved.</p>
</blockquote>
<p>and:</p>
<blockquote>
<p>Usually when a command fails, if it has changed the target file at all, the file is corrupted and cannot be usedâor at least it is not completely updated. Yet the file's time stamp says that it is now up to date, so the next time make runs, it will not try to update that file. The situation is just the same as when the command is killed by a signal; see Interrupts. So generally the right thing to do is to delete the target file if the command fails after beginning to change the file. make will do this if .DELETE_ON_ERROR appears as a target. This is almost always what you want make to do, but it is not historical practice; so for compatibility, you must explicitly request it.</p>
</blockquote>
|
Why can't my software initialize hardware on a different motherboard? <p>I am not a developer, but I think that my question is interesting enough (and I am desperate enough) to post here on stackoverflow</p>
<p>My company uses a program written in C# to drive a kiosk PC that uses .Net 2.0 SP1 and a USB signature pad. The signature pad is a HID that uses the generic Microsoft HID driver.</p>
<p>We tried to install our software on a kiosk PC that uses a different brand of motherboard than we previously used. We moved from a Gigabyte board to an ASUS board. Other than the brand, the specs are identical, same north bridge, same south bridge, same CPU, same host controllers etc. Also, our install procedure is documented and hasn't changed in months.</p>
<p>On the new motherboard, the signature pad is recognized as a HID, installs without an issue, and the manufacturers software can run the device, but our software does not recognize that device is even connected. The only thing that has changed is the motherboard brand. The manufactures software that can initialize the device is not written in C#.</p>
<p>Any thoughts, suggestions, or solutions are welcome!!!!</p>
| <p>It's could possibly related to programing/but i am thinking its the hardware/driver issue. </p>
<p>You could try removing all drivers and reinstall new drivers under computer management. </p>
<p>Most new motherboards of a different model/brand require windows to be reinstalled. </p>
|
.NET Exception Explorer <p>Does anyone know of a program or plug-in or anything that I can find out what are all the exceptions any method may throw?</p>
<p>I think JAVA has this build in if I'm not mistaken. Where the compiler tells you what exceptions this method will throw.</p>
<p>Does the same exist for .NET?</p>
<p>Thanks</p>
<p>Edit: After searching around more, I wish there was tool like Object Explorer, except for Exceptions. You select the class or method and it lists the exceptions, at that level, which are thrown by the class. The tool links provided are a great start. Thanks!</p>
| <p>I don't know if this is exactly what you are looking for, but:</p>
<p><a href="http://www.red-gate.com/Products/Exception_Hunter/index.htm" rel="nofollow">http://www.red-gate.com/Products/Exception_Hunter/index.htm</a></p>
<p>Note: I've never used the product, and I don't work for Red Gate, I just remember seeing it advertised before.</p>
|
What is WPF and how does it compare to WinForms? <p>I've been looking at WPF, but I've never really worked in it (except for 15 minutes, which prompted this question). I looked at this <a href="http://stackoverflow.com/questions/193005/are-wpf-more-flashy-like-than-winforms">post</a> but its really about the "Flash" of a WPF. So what is the difference between a Windows Forms application and a WPF application?</p>
| <p>WPF is a vector graphics based UI presentation layer where WinForms is not. Why is that important/interesting? By being vector based, it allows the presentation layer to smoothly scale UI elements to any size without distortion.</p>
<p>WPF is also a composable presentation system, which means that pretty much any UI element can be made up of any other UI element. This allows you to easily build up complex UI elements from simpler ones.</p>
<p>WPF is also fully databinding aware, which means that you can bind any property of a UI element to a .NET object (or a property/method of an object), a property of another UI element, or data. Yes, WinForms supports databinding but in a much more limited way.</p>
<p>Finally, WPF is "skinable" or "themeable", which means that as a developer you can use a list box because those are the behaviors you need but someone can "skin" it to look like something completely different. </p>
<p>Think of a list box of images. You want the content to actually be the image but you still want list box behaviors. This is completely trivial to do in WPF by simply using a listbox and changing the content presentation to contain an image rather than text.</p>
|
Programmer productivity with STL vs. custom utility classes <p>I work in an environment where, for historical reasons, we are using a hodgepodge of custom utility classes, most of which were written before STL arrived on the scene. There are many reasons why I think it is a good idea to at least write new code using STL, but the main one is that I believe it increases programmer productivity. Unfortunately, that is a point that I don't know how to prove.</p>
<p>Are there any studies out there that attempt to quantify, or even just hint at, a productivity gain from using STL?</p>
<p><strong>Update:</strong> I guess I should have been more specific. I am <em>not</em> advocating rewriting existing code, and I am <em>not</em> worried about the new hires that will get a running start. The former would be foolish, and the latter by itself is not enough to convince people.</p>
| <p>There are no studies that will show STL is more productive just because it is STL. Productivity gains from using it are due to it being a standard programmers are familiar with it, and because the code is already written and tested.</p>
<p>If your company already has utility classes that employees are familiar with, and this utility code is used throughout an existing codebase, then switching to STL could actually be detrimental to productivity.</p>
<p>That said for new code using STL would be a good move. I would not necessarily argue this from a productivity standpoint, but one of maintainability. If you have code that predates STL it sounds like code at your company has quite a long lifetime and is likely to be maintained by a number of new programmers over the years.</p>
<p>You may also want to broach the use of STL as a way for everyone to keep their C++ skillset sharp. While I wouldn't reject a C++ candidate who didn't know STL, I would definitely view it as a black mark.</p>
|
How to get the Freebase Python libraries to work in IronPython <p>How do I get the <a href="http://code.google.com/p/freebase-python/" rel="nofollow">Python libraries for using the Freebase API</a> to work under <a href="http://www.codeplex.com/IronPython" rel="nofollow">IronPython 2.0</a>?</p>
<p>When I "import freebase.api", I get "ImportError: No module named django.utils". What gives?</p>
| <p>You're missing the simplejson module. Since easy_install doesn't yet work with IronPython, your best bet is to grab the latest code using SVN from their <a href="http://code.google.com/p/simplejson/source/checkout" rel="nofollow">Google Code project</a>, or <a href="http://apiguy.com/files/simplejson-2.0.9.zip" rel="nofollow">download a zip file</a>.</p>
<p>Put all of the files that you obtained into the lib/site-packages/simplejson folder under your IronPython installation directory.</p>
<p>Now you'll be able to successfully "import freebase.api".</p>
|
DataMember property [ObjectName] cannot be found on the DataSource <p>I have a business object, which is a composite of child objects.<br />
I am using databinding in Visual Studio 2008 to bind to controls on a Windows form.</p>
<p>But I am getting the above error in the InitializeComponent method of the form.</p>
<p>Lets say I have an object called ParentObject which contains a generic list, ChildListObject. The ParentObject also has Child object, which itself has a Child object. (ie ParentObject.ChildObject.ChildObject) </p>
<p>I set the main binding source:</p>
<pre><code>BindingSource.Datasource = ParentObject
</code></pre>
<p>I add a grid and set it's binding source:</p>
<pre><code>GridBindingSource.Datasource = ParentObject
</code></pre>
<p>and set the DataMember to:</p>
<pre><code>BindingSourceB.DataMember = "ChildListObject"
</code></pre>
<p>Now, the grid's datasource is set to GridBindingSource:</p>
<pre><code>Me.MyDataGridView.DataSource = Me.GridBindingSource
</code></pre>
<p>There are also other controls that are bound to properties of the ParentObject and the ParentObject.ChildObject</p>
<p>I have tested this in an isolated project and it works fine, so I am having trouble finding out what the real bug is? Code that used to work, will all of the sudden stop working.</p>
<p>The error I get is (if I use the names of the objects in the above example):</p>
<blockquote>
<p>"DataMember property ChildObject cannot
be found on the DataSource"</p>
</blockquote>
<p>It fails on:</p>
<pre><code>Me.MyDataGridView.DataSource = Me.GridBindingSource
</code></pre>
<p>Strangely, if I remove <System.Diagnostics.DebuggerStepThrough()> and then when it fails just continue it is fine??? But it still fails in runtime.</p>
<p>Does anyone have any ideas that could point me in the right direction? The closest I have found through googling is it may have something to do with the order of the generated designer code getting messed up. Code that was working, will all of the sudden stop working.</p>
<p><hr /></p>
<p>This issue seems to come and go. If I just continue after the error is raised the program happily continues with no problems. Possibly a bug in VS. But at run-time the error still exists.</p>
<p>What is causing this problem? How do I stop it occurring?</p>
| <p>I tried several experiments about this
The problem only happens in this condition
İf you have a BaseForm and BindingSource on it
if you inherit a new InheritedForm from this BaseForm
if you have additional binding source on InheritedForm related to the BindingSource (which inherited by BaseForm)
you have the designer error.I don't have a designer solution but if you Ignore And Continue
everything is going to be normal while you build project again</p>
<p>or you will have to set datamember by code</p>
|
Documentation driven design. Your experiences <p>I noticed this project (<a href="http://blog.tplus1.com/index.php/2009/02/22/my-new-ticket-tracking-system-is-now-vaporware/" rel="nofollow">pitz</a>) that is being written first with the documentation, then tests, and finally code. Has anyone else tried this "Documentation driven design" and if so, what are your experiences with it?</p>
| <p>Yes, I've done it a couple of times, the most succesful of which was when we were developing a library for use by another part of the organisation, with whom we had erm, "issues". To avoid endless & fruitless arguements, I wrote up the whole library API in the same form that Microsoft use to document the Win32 API before we implemented it.</p>
<p>The presence of the document allowed the discussions between the two groups to become more structured, and though the API spec was significantly changed over time, we did finally get the implementation out the door on schedule.</p>
<p>So if you are going this route, I recommend finding some existing documentation you like and modelling your own on it. </p>
|
WPF - UserControl sizing on Custom Canvas <p>I have a custom canvas that I can drop controls on, move, and resize. I need to be able to at least start with a pre-determined size but then allow re-sizing.</p>
<p>My problem is that I have a user control that doesn't appear to resize. I set Height and Width on the user control (works on drop). But then as the control is resized on the canvas the visual size stays the same (the sizing handles are changing). I can see the Height property changing (usercontrol.height) as the control is resized. But again, the appearance of the control stays the same size. </p>
<p>I had a thought that the inner container on the user control should be bound to the usercontrol.height but that didn't seem to help. (or maybe I didn't have the binding right).</p>
<p>On the same canvas, if the dropped control is for example, an Image control, I can set an explicit height on the drop and everything resizes as it should. So it seems to be UserControl thing.</p>
<p>So is there something special I need to do with UserControls to get the visuals to resize? Should I be using explicit height and width to get it all started?</p>
<p>Thanks for any help.</p>
| <p>The WPF layout system can be confusing, as you've discovered. There is no substitute for a solid understanding of the layout and measurement system. If you plan on doing much WPF development, it's worth taking 20 minutes to read <a href="http://msdn.microsoft.com/en-us/library/ms745058.aspx#LayoutSystem%5FMeasure%5FArrange" rel="nofollow">this article on the layout system</a> and then experimenting for a while in an iterative environment such as <a href="http://www.kaxaml.com" rel="nofollow">Kaxaml</a> until you feel comfortable.</p>
<p>The system is very logical. It won't take long for the penny to drop. Sorry for the indirect answer, but I don't believe there's enough information in your question to really explain what's going on.</p>
<p>You might also look at the <code>HorizontalAlignment</code> and <code>VerticalAlignment</code> properties.</p>
|
How to easily apply a function to a collection in C++ <p>I'm storing images as arrays, templated based on the type of their elements, like <code>Image<unsigned></code> or <code>Image<float></code>, etc. Frequently, I need to perform operations on these images; for example, I might need to add two images, or square an image (elementwise), and so on. All of the operations are elementwise. I'd like get as close as possible to writing things like:</p>
<pre><code>float Add(float a, float b) { return a+b; }
Image<float> result = Add(img1, img2);
</code></pre>
<p>and even better, things like</p>
<pre><code>complex ComplexCombine(float a, float b) { return complex(a, b); }
Image<complex> result = ComplexCombine(img1, img2);
</code></pre>
<p>or</p>
<pre><code>struct FindMax {
unsigned currentMax;
FindMax(): currentMax(0) {}
void operator(unsigned a) { if(a > currentMax) currentMax = a; }
};
FindMax findMax;
findMax(img);
findMax.currentMax; // now contains the maximum value of 'img'
</code></pre>
<p>Now, I obviously can't exactly do that; I've written something so that I can call:</p>
<pre><code>Image<float> result = Apply(img1, img2, Add);
</code></pre>
<p>but I can't seem to figure out a generic way for it to detect the return type of the function/function object passed, so my <code>ComplexCombine</code> example above is out; also, I have to write a new one for each number of arguments I'd like to pass (which seems inevitable).</p>
<p>Any thoughts on how to achieve this (with as little boilerplate code as possible)?</p>
| <p>This is why the unary_function, binary_function, etc. types in he STL have the result_type typedefs. If you use std::ptr_fun, you can take advantage of this with Apply,</p>
<p>e.g.</p>
<pre><code>template<typename Func, typename Arg, typename Result = Func::result_type>
Image<Result> Apply(Arg a1, Arg a2, Func f) {
return Image<Result>(f(a1,a2));
}
</code></pre>
<p>And do,</p>
<pre><code>Apply(img1, img2, std::ptr_fun(&Add));
</code></pre>
<p><hr /></p>
<p>Ok, you caught me, I didn't test it. It is still possible, but more work without being able to directly use some of the STL functionality</p>
<pre><code>#include <iostream>
template<typename T>
struct Image {
T val_;
Image(const T& val) : val_(val) {}
};
template<typename Arg1, typename Arg2, typename Result>
struct image_fun_adapter {
Result (*f)(Arg1, Arg2);
Image<Result> operator()(const Image<Arg1>& a1, const Image<Arg2>& a2) {
return Image<Result>(f(a1.val_, a2.val_));
}
};
template<typename Arg1, typename Arg2, typename Result>
image_fun_adapter<Arg1,Arg2,Result> image_fun_ptr(Result (*f)(Arg1,Arg2)) {
image_fun_adapter<Arg1,Arg2,Result> rv;
rv.f = f;
return rv;
}
float Add(float a, float b) { return a + b; }
int main() {
Image<float> a(1.0);
Image<float> b(12.5);
// this is the cute bit:
Image<float> c = image_fun_ptr(&Add)(a,b);
std::cout << c.val_ << std::endl;
return 0;
}
</code></pre>
|
What is the Best way to do Browser Detection in Javascript? <p>In one of my Web Development classes we where asked to create a script that detects NE4,NE6+,IE4,IE6+ Browsers that display a compatable CSS script for each browser.</p>
<p>he gave us an article to read about these and the article mentioned <a href="https://developer.mozilla.org/En/Browser%5FDetection%5Fand%5FCross%5FBrowser%5FSupport" rel="nofollow">this site</a></p>
<p>one of the students said this </p>
<blockquote>
<p>The best choice for javascript
compatibility is to test for browser
capabilities when you want to do
something. One of the main reasons
for this is that in the future, more
and more browsers will be created.</p>
</blockquote>
<p>Now my questions is this which way is the best way to detect the users browser object detection or using the Navigator Object?</p>
| <p>The standard way to detect what browser is used is to check the user agent supplied.</p>
<pre><code>var BrowserDetect = {
init: function () {
this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
this.version = this.searchVersion(navigator.userAgent)
|| this.searchVersion(navigator.appVersion)
|| "an unknown version";
this.OS = this.searchString(this.dataOS) || "an unknown OS";
},
searchString: function (data) {
for (var i=0;i<data.length;i++) {
var dataString = data[i].string;
var dataProp = data[i].prop;
this.versionSearchString = data[i].versionSearch || data[i].identity;
if (dataString) {
if (dataString.indexOf(data[i].subString) != -1)
return data[i].identity;
}
else if (dataProp)
return data[i].identity;
}
},
searchVersion: function (dataString) {
var index = dataString.indexOf(this.versionSearchString);
if (index == -1) return;
return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
},
dataBrowser: [
{
string: navigator.userAgent,
subString: "Chrome",
identity: "Chrome"
},
{ string: navigator.userAgent,
subString: "OmniWeb",
versionSearch: "OmniWeb/",
identity: "OmniWeb"
},
{
string: navigator.vendor,
subString: "Apple",
identity: "Safari",
versionSearch: "Version"
},
{
prop: window.opera,
identity: "Opera"
},
{
string: navigator.vendor,
subString: "iCab",
identity: "iCab"
},
{
string: navigator.vendor,
subString: "KDE",
identity: "Konqueror"
},
{
string: navigator.userAgent,
subString: "Firefox",
identity: "Firefox"
},
{
string: navigator.vendor,
subString: "Camino",
identity: "Camino"
},
{ // for newer Netscapes (6+)
string: navigator.userAgent,
subString: "Netscape",
identity: "Netscape"
},
{
string: navigator.userAgent,
subString: "MSIE",
identity: "Explorer",
versionSearch: "MSIE"
},
{
string: navigator.userAgent,
subString: "Gecko",
identity: "Mozilla",
versionSearch: "rv"
},
{ // for older Netscapes (4-)
string: navigator.userAgent,
subString: "Mozilla",
identity: "Netscape",
versionSearch: "Mozilla"
}
],
dataOS : [
{
string: navigator.platform,
subString: "Win",
identity: "Windows"
},
{
string: navigator.platform,
subString: "Mac",
identity: "Mac"
},
{
string: navigator.userAgent,
subString: "iPhone",
identity: "iPhone/iPod"
},
{
string: navigator.platform,
subString: "Linux",
identity: "Linux"
}
]
};
BrowserDetect.init();
</code></pre>
<p><a href="http://www.quirksmode.org/js/detect.html">http://www.quirksmode.org/js/detect.html</a></p>
|
How do you detect the main hard drive letter such as C: drive? <p>How do you detect the main hard drive letter such as C: drive?</p>
| <p>Try</p>
<pre><code>Path.GetPathRoot(Environment.GetFolderPath(Environment.SpecialFolder.System));
</code></pre>
<p>That will return (normally) C:\</p>
<p>But it depends on how you define the "main" hard drive. This will give you the drive Windows is installed on.</p>
|
TFrame inheritance refactoring <p>Yet another TFrame IDE-registered-component question from me. Thanks for all the help, fellow programmers. : )</p>
<p>Playing around with Darrian's TFrame inheritance suggestion <a href="http://stackoverflow.com/questions/382562/delphi-visual-component-moving-away-from-tframe-base/382607#382607" rel="nofollow" title="earlier TFrame question / comment">here</a>:</p>
<p><strong>Specifics:</strong></p>
<p>Basically, I have a TFrame-based component that I've registered to the IDE, and it has worked wonderfully. I'm now developing a few "sister" components which will share a great deal of the existing component's non-visual functionality and properties. It makes sense, then, to move a lot of that to a parent/superclass which both the new and the old components can then inherit from.</p>
<p>What is the best way to "refactor" TFrame inheritance in this way? (This may apply to TForm-class descendants too, not sure). What are the caveats and things to watch out for?</p>
<p><strong>Example:</strong></p>
<p>I tried, for example, creating a new TFrame, with nothing on it, and calling that frame TMyBaseFrame. Then modified the class definition of my existing component (Let's call it TMyFrameTreeView) to inherit from that rather than TFrame.</p>
<p>It compiled fine, but when I tried dropping it on a form, I got "ClientHeight not found" (or "ClientHeight property not found"), and it wouldn't drop on the form. Deleting ClientHeight and ClientWidth from the related DFM wreaked havoc, and they ended up replaced upon resizing anyway. I noticed ExplicitHeight and ExplicitWidth in descendent classes, and am thinking that relates to property-value overrides from inherited values, but am not sure. Recreating an entirely new frame via New -> Inherited Items, and then copying everything over, hasn't yielded great results yet either.</p>
<p><strong>Final Note</strong></p>
<p>I realize this could get messy quickly, with streaming DFM files and multiple generations of descendants, etc.... which is part of why I'm asking for the overall "things to look out for" conceptual aspect, but also giving a specific real-world <em>simpler</em> version of the problem as well (which seems to me, ought to be doable).</p>
<p>I've created a little test package to hack around in learning attempts, and am learning a great deal, but it's slow-going, and any guidance/insight from you Delphi "Jedi Masters" out there would be MOST appreciated. : ) </p>
<p><br><br />
<strong>Answer update later:</strong></p>
<p>Both of the answers below were helpful. As well, creating a "Base Frame Class" which has NO changes from the normal TFrame, and THEN inheriting from that before adding any properties, methods, etc. seems to stabilize the inheritance streaming tremendously. Not sure why, but so far it has.</p>
| <p>In addition to changing base class of <code>TMyFrameTreeView</code> to <code>TMyBaseFrame</code> change the first word in the dfm file for <code>TMyFrameTreeView</code> from <code>object</code> to <code>inherited</code>.</p>
|
Are CSS based menus simply toggling display none/block and z-index? <p>Just trying to understand how to get drop down menus to work (the theory behind them).</p>
<p>From what I have seen, it is just playing around with CSS using display:none and block along with the z-index.</p>
<p>Events are attached on mouseover and mouseout to switch the CSS class.</p>
<p>Is that basically it?</p>
| <p>There's an alternative where you can make give menu items visibility dependent on the hover style of the parent element, eg.</p>
<pre><code>li ul {display: none;}
li:hover > ul {display: block;}
</code></pre>
<p>this means you can make menus simply by using </p>
<pre><code><ul id="menu">
<li>
some item
<ul><li>sub item</li></ul>
</li>
<li>
some other item
</li>
<ul>
</code></pre>
<p>Obviously you'll want to throw in more styling, and classes, etc to prevent it applying to all lists, but that's the general concept behind a css menu.</p>
|
jQuery and appending large amounts of HTML <p>I have come to find that using jQuery to create HTML client-side can be a huge performance booster if done properly. I use AJAX returning JSON to retrieve dynamic content and then I build the relevant HTML and insert it using jQuery. The first time I messed with this technique I found that the string concatenator in IE's JavaScript performed really slowly so that building a dynamic table with more than 50 or so rows performed terribly. </p>
<pre><code>var shtml = '<table>';
for(var i=0;i<100;i++) shtml += '<tr><td>A bunch of content</td></tr>';
shtml += '</table>';
$('#myTable').append(shtml);
</code></pre>
<p>Then I found a technique for string concatenation that changed everything. Instead of using the sting += operator use arrays to do concatenation;</p>
<pre><code>var shtml = ['<table>'];
for(var i=0;i<100;i++) shtml.push('<tr><td>A bunch of content</td></tr>');
shtml.push('</table>');
$('#myTable').append(shtml.join(''));
</code></pre>
<p>I found that performance improved significantly. Now, however, there is a ceiling of about 100 rows before I start to see the browser itself struggle with dynamically inserting so much content at once. Does anyone have any pointers or techniques that can be used to help me achieve the next performance boost for large sets of dynamic HTML?</p>
| <p>There's a performance issue with jQuery and inserting a large string of html to the DOM, due to its $.trim function.</p>
<p>I sometimes find plain old dom scripting much faster than using jquery. Try something like</p>
<pre><code>document.getElementById('id').innerHTML = myarray.join('')
</code></pre>
|
How to set the final value of an Animation to the property when the Animation finishes or is canceled? <p>I try to animate a DependencyProperty from a value to a target value (in code) and when the animation finishes (<strong>or is canceled</strong>) set the <em>final</em> value to the property. The final value would be either the To value if the animation finishes or the <em>current</em> computed value (by the animation) when the animation is canceled.</p>
<p>By default the Animation doesn't have this behavior and an Animation doesn't change the actual value even if it has completed.</p>
<h3>A failed attempt</h3>
<p>A while ago I wrote this helper method to achieve the mentioned behavior:</p>
<pre><code>static void AnimateWithAutoRemoveAnimationAndSetFinalValue(IAnimatable element,
DependencyProperty property,
AnimationTimeline animation)
{
var obj = element as DependencyObject;
if (obj == null)
throw new ArgumentException("element must be of type DependencyObject");
EventHandler handler = null;
handler = (sender, e) =>
{
var finalValue = obj.GetValue(property);
//remove the animation
element.BeginAnimation(property, null);
//reset the final value
obj.SetValue(property, finalValue);
animation.Completed -= handler;
};
animation.Completed += handler;
element.BeginAnimation(property, animation);
}
</code></pre>
<p><strong>Unfortunately the Completed event doesn't seem to fire if the Animation is removed by someone calling BeginAnimation(property,null</strong>) and therefore I cannot set the final value correctly when an Animation is canceled. What is worse I cannot remove the event handler either...</p>
<p>Does someone know how to do this in a clean way?</p>
| <p>It looks like you are trying to set value back to the initial value prior to the animation starts just after the animation finishes. This actually happens automatically if you stop the animation (or when the animation timeline finishes). Animations, in WPF, can be though of as an value overlay on top of the current value of the property. Stopping or removing an animation will remove the overlay and the prior value will now start showing through again. The original value is not lost, it is being temporarily obscured.</p>
<p>Setting the property explicitly back to its prior value is, in general, bad practice because it can incur a memory overhead if the value was not originally set locally on the object. Also, this can introduce subtle problems later. For example, if the old value was derived from a style, the property will no longer change if the style changes.</p>
<p>If you still feel you must extract the current value and later restore it, use ReadLocalValue() instead of GetValue(). This will return DepenencyProperty.UnsetValue if the value is not set locally. You can then conditionally call ClearValue() or SetValue() depending on whether the property initially had a local value.</p>
|
Taking a screenshot with tooltip and cursor visible <p>This is the code I am using to take a screenshot:</p>
<pre><code>[DllImport("gdi32.dll",EntryPoint="DeleteDC")]
public static extern IntPtr DeleteDC(IntPtr hDc);
[DllImport("gdi32.dll",EntryPoint="DeleteObject")]
public static extern IntPtr DeleteObject(IntPtr hDc);
[DllImport("gdi32.dll",EntryPoint="BitBlt")]
public static extern bool BitBlt(IntPtr hdcDest,int xDest,
int yDest,int wDest,int hDest,IntPtr hdcSource,
int xSrc,int ySrc,int RasterOp);
[DllImport ("gdi32.dll",EntryPoint="CreateCompatibleBitmap")]
public static extern IntPtr CreateCompatibleBitmap(IntPtr hdc,
int nWidth, int nHeight);
[DllImport ("gdi32.dll",EntryPoint="CreateCompatibleDC")]
public static extern IntPtr CreateCompatibleDC(IntPtr hdc);
[DllImport ("gdi32.dll",EntryPoint="SelectObject")]
public static extern IntPtr SelectObject(IntPtr hdc,IntPtr bmp);
[DllImport("user32.dll", EntryPoint="GetDesktopWindow")]
public static extern IntPtr GetDesktopWindow();
[DllImport("user32.dll",EntryPoint="GetDC")]
public static extern IntPtr GetDC(IntPtr ptr);
[DllImport("user32.dll",EntryPoint="GetSystemMetrics")]
public static extern int GetSystemMetrics(int abc);
[DllImport("user32.dll",EntryPoint="GetWindowDC")]
public static extern IntPtr GetWindowDC(Int32 ptr);
[DllImport("user32.dll",EntryPoint="ReleaseDC")]
public static extern IntPtr ReleaseDC(IntPtr hWnd,IntPtr hDc);
public static Bitmap GetDesktopImage()
{
//In size variable we shall keep the size of the screen.
SIZE size;
//Variable to keep the handle to bitmap.
IntPtr hBitmap;
//Here we get the handle to the desktop device context.
IntPtr hDC = GetDC(GetDesktopWindow());
//Here we make a compatible device context in memory for screen
//device context.
IntPtr hMemDC = CreateCompatibleDC(hDC);
//We pass SM_CXSCREEN constant to GetSystemMetrics to get the
//X coordinates of the screen.
size.cx = GetSystemMetrics(SM_CXSCREEN);
//We pass SM_CYSCREEN constant to GetSystemMetrics to get the
//Y coordinates of the screen.
size.cy = GetSystemMetrics(SM_CYSCREEN);
//We create a compatible bitmap of the screen size and using
//the screen device context.
hBitmap = CreateCompatibleBitmap
(hDC, size.cx, size.cy);
//As hBitmap is IntPtr, we cannot check it against null.
//For this purpose, IntPtr.Zero is used.
if (hBitmap!=IntPtr.Zero)
{
//Here we select the compatible bitmap in the memeory device
//context and keep the refrence to the old bitmap.
IntPtr hOld = (IntPtr)SelectObject
(hMemDC, hBitmap);
//We copy the Bitmap to the memory device context.
BitBlt(hMemDC, 0, 0,size.cx,size.cy, hDC,0, 0,SRCCOPY);
//We select the old bitmap back to the memory device context.
SelectObject(hMemDC, hOld);
//We delete the memory device context.
DeleteDC(hMemDC);
//We release the screen device context.
ReleaseDC(GetDesktopWindow(), hDC);
//Image is created by Image bitmap handle and stored in
//local variable.
Bitmap bmp = System.Drawing.Image.FromHbitmap(hBitmap);
//Release the memory to avoid memory leaks.
DeleteObject(hBitmap);
//This statement runs the garbage collector manually.
GC.Collect();
//Return the bitmap
return bmp;
}
//If hBitmap is null, retun null.
return null;
}
</code></pre>
<p>It does capture a screenshot, but I want to take the screenshot with the tooltip visible. What do I have to add to take screenshot with the tooltip and cursor visible?</p>
| <p>Vista has a snipping Tool to easily do so as given in <a href="http://blog.falafel.com/2008/08/12/CaptureScreenShotsWithToolTipsAndPopupsUsingVistaSnippingTool.aspx" rel="nofollow">http://blog.falafel.com/2008/08/12/CaptureScreenShotsWithToolTipsAndPopupsUsingVistaSnippingTool.aspx</a>.</p>
<p>There is also an application via Silverlight: <a href="http://blogs.msdn.com/swick/archive/2007/12/18/snipping-pictures-with-silverlight.aspx" rel="nofollow">http://blogs.msdn.com/swick/archive/2007/12/18/snipping-pictures-with-silverlight.aspx</a></p>
<p>I don't know if source code is available for the snipping tool. You can try taking a video, then taking a snapshot of a part of the video <a href="http://www.codeproject.com/KB/audio-video/CaptureScreenAsVideo.aspx" rel="nofollow">as shown here</a>.</p>
|
How to alloc a dynamic typed object <p>I have seen a lot of talk about dynamic typing in objective-c. But i haven't seen any examples of what i think it is supposed to be.</p>
<p>lets say I have a generic function that is supposed to juggle two objects (one gets allocated and the other gets freed) and the calling object attaches it self to the newly alloced object. Both are inherited from class0</p>
<p>Please feel free to interpret this however you want if you think it will explain something!!</p>
<p>If the class is picked at runtime, how do i deal with the arguments list (? is a placeholder for now)
How do i alloc a object who's class is not defined until runtime?</p>
<pre><code>-(void) juggle:(?*)objclass1:(?*)objclass2{
? temp = [? alloc] init];
objclass1 = temp;
[temp release];
[objclass2.view removefromsuperview];
[self.handle insertsubview:objclass1.view];
}
</code></pre>
| <p>I have no idea what the code you have there is trying to do, it is not syntactically valid, and manipulating views has nothing to do with your questions. Anyway, if you really don't know the type you generally use "id" which is type cast to a "void *" for codegen. It has the special property that it is assumed to receive any message, so it does not trigger compiler warnings for unknown messages.</p>
<p>In order to instantiate a class you just need to be holding the "Class" object for it. In Objective C all instances of a class refer to a Class object (the isa pointer in the legacy runtime), which also responds to methods. So in other words, in the following code:</p>
<pre><code>NSArray *myObject = [[NSArray alloc] init];
</code></pre>
<p>NSArray is actually an object. So this will generate equivalent code results:</p>
<pre><code>Class myClass = [NSArray class];
NSArray *myObject = [[myClass alloc] init];
</code></pre>
<p>or even</p>
<pre><code>Class myClass = NSClassFromString(@"NSArray");
NSArray *myObject = [[myClass alloc] init];
</code></pre>
<p>Which uses the function NSClassFromString which walks into the runtime and finds a class with the name you pass in.</p>
<p>All objects return their class if use the class getter, so to instantiate an object that is the same class as an existing object like this:</p>
<pre><code>- (void) leakObjectWithSameClassAs:(id)object {
[[[object class] alloc] init];
}
</code></pre>
|
How do you fix this mysql query without the use of a subquery? <p>I have 3 tables. For the purposes of this example I will simplify it as much as I can.</p>
<p>First table contains movie ids and names, second table contains genre ids and genre names (action, drama, etc). 3rd table stores the genre id associated with each movie, since some movies have more than one. It has 2 columns, genre_id and movie_id. Fairy simple stuff. Im trying to output the list of movies, along with a list of genres associated with each movie.</p>
<pre><code> SELECT *
FROM movies
LEFT JOIN gen_pairs
ON movies.mov_id = gen_pairs.gen_movieid
LEFT JOIN categories
ON gen_pairs.gen_catid = categories.cat_id
GROUP BY mov_id
</code></pre>
<p>This will obviously output a single genre of each film, even if it has multiple ones in the gen_pairs table. How would I get it to display a comma separated list of genres for each movie, without running a sub-query for each item?</p>
| <p>Your select should build the Cartesian product, so you'll get output like</p>
<pre><code>MovieA GenreA
MovieA GenreB
MovieB GenreA
...
</code></pre>
<p>But it sounds like you want this instead:</p>
<pre><code>MovieA GenreA, GenreB
MovieB GenreA
...
</code></pre>
<p>MySQL has a GROUP_CONCAT function to do what you want:</p>
<pre><code>SELECT m.mov_id, GROUP_CONCAT(c.name)
FROM movies m
LEFT JOIN gen_pairs gp ON (m.mov_id = gp.gen_movieid)
LEFT JOIN categories c ON (gp.gen_catid = c.cat_id)
GROUP BY m.mov_id
</code></pre>
<p>Note the GROUP_CONCAT and GROUP BY.</p>
|
Passing data from a jquery ajax request to a wcf service fails deserialization? <p>I use the following code to call a wcf service. If i call a (test) method that takes no parameters, but returns a string it works fine. If i add a parameter to my method i get a wierd error:</p>
<blockquote>
<p>{"ExceptionDetail":{"HelpLink":null,"InnerException":null,"Message":"The token '\"' was expected but found '''.","StackTrace":" at System.Xml.XmlExceptionHelper.ThrowXmlException(XmlDictionaryReader reader, String res, String arg1, String arg2, String arg3)\u000d\u000a at System.Xml.XmlExceptionHelper.ThrowTokenExpected(XmlDictionaryReader reader, String expected, Char found)\u000d\u000a at System.Runtime.Serialization.Json.XmlJsonReader.ParseStartElement()\u000d\u000a at System.Runtime.Serialization.Json.XmlJsonReader.Read()\u000d\u000a at System.ServiceModel.Dispatcher.DataContractJsonSerializerOperationFormatter.DeserializeBodyCore(XmlDictionaryReader reader, Object[] parameters, Boolean isRequest)\u000d\u000a at System.ServiceModel.Dispatcher.DataContractJsonSerializerOperationFormatter.DeserializeBody(XmlDictionaryReader reader, MessageVersion version, String action, MessageDescription messageDescription, Object[] parameters, Boolean isRequest)\u000d\u000a at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeBodyContents(Message message, Object[] parameters, Boolean isRequest)\u000d\u000a at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeRequest(Message message, Object[] parameters)\u000d\u000a at System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(Message message, Object[] parameters)\u000d\u000a at System.ServiceModel.Dispatcher.UriTemplateDispatchFormatter.DeserializeRequest(Message message, Object[] parameters)\u000d\u000a at System.ServiceModel.Dispatcher.CompositeDispatchFormatter.DeserializeRequest(Message message, Object[] parameters)\u000d\u000a at System.ServiceModel.Dispatcher.DispatchOperationRuntime.DeserializeInputs(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)","Type":"System.Xml.XmlException"},"ExceptionType":"System.Xml.XmlException","Message":"The token '\"' was expected but found '''.","StackTrace":" at System.Xml.XmlExceptionHelper.ThrowXmlException(XmlDictionaryReader reader, String res, String arg1, String arg2, String arg3)\u000d\u000a at System.Xml.XmlExceptionHelper.ThrowTokenExpected(XmlDictionaryReader reader, String expected, Char found)\u000d\u000a at System.Runtime.Serialization.Json.XmlJsonReader.ParseStartElement()\u000d\u000a at System.Runtime.Serialization.Json.XmlJsonReader.Read()\u000d\u000a at System.ServiceModel.Dispatcher.DataContractJsonSerializerOperationFormatter.DeserializeBodyCore(XmlDictionaryReader reader, Object[] parameters, Boolean isRequest)\u000d\u000a at System.ServiceModel.Dispatcher.DataContractJsonSerializerOperationFormatter.DeserializeBody(XmlDictionaryReader reader, MessageVersion version, String action, MessageDescription messageDescription, Object[] parameters, Boolean isRequest)\u000d\u000a at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeBodyContents(Message message, Object[] parameters, Boolean isRequest)\u000d\u000a at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeRequest(Message message, Object[] parameters)\u000d\u000a at System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(Message message, Object[] parameters)\u000d\u000a at System.ServiceModel.Dispatcher.UriTemplateDispatchFormatter.DeserializeRequest(Message message, Object[] parameters)\u000d\u000a at System.ServiceModel.Dispatcher.CompositeDispatchFormatter.DeserializeRequest(Message message, Object[] parameters)\u000d\u000a at System.ServiceModel.Dispatcher.DispatchOperationRuntime.DeserializeInputs(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)"}</p>
</blockquote>
<p>My jquery looks like this, but i tried changing the actual data which i send as a string serialized json (as you can see) to a pure json object with the same sad result.</p>
<pre><code>$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/Statistics.svc/Get7DaysStatistics",
dataType: "json",
data: "{'customerId': '2'}",
timeout: 10000,
success: function(obj) { updateStatistics(obj.d); },
error: function(xhr) {
if (xhr.responseText)
$("body").html(xhr.responseText);
else
alert('unknown error');
return;
}
});
</code></pre>
<p>The wcf service looks like this:</p>
<pre><code> [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic"), OperationContract]
public string Get7DaysStatistics(string customerId)
{
Debug.WriteLine(customerId);
return "Test done";
}
</code></pre>
<p>It's placed in a a class with the following attributes:</p>
<pre><code>[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
</code></pre>
<p>I won't list the configuration in the web.config to keep this long message "short" but i can post it if anybody thinks they can use it - i just want to stress that i CAN call a method and get a result - string or even a json object i can read from as long as i DON'T pass any data to the wcf service.</p>
| <p>Use double quotes instead of single quotes in the JSON you are sending to the service. That is, change:</p>
<pre><code>data: "{'customerId': '2'}",
</code></pre>
<p>to </p>
<pre><code>data: '{"customerId": "2"}',
</code></pre>
<p>I've tested this locally and this fixes the problem. </p>
<p>Incidentally, I debugged this using a method I've often used when calling ASMX and WCF services using libraries other than the built-in ASP.NET tools. I called the service using the client proxy created by an <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.scriptreference.aspx">asp:ScriptReference</a> and then inspected the request being sent to the server using an HTTP sniffer (such as <a href="http://code.google.com/p/httpfox/">HttpFox</a> for FireFox) and compared the request to the one being sent by <a href="http://jquery.com/">jQuery</a>. Then you can usually quickly see what is different (and so probably wrong) with the request. In this case, it was clear that there was a difference in the POST data being sent.</p>
|
Using the All operator <p>I would like to see an example that makes the best use of the ALL operator when using a parent child reltaionship in LINQ. Can you show me one please?</p>
| <p>The All() extension method checks a predicate against all the items; for example, at execution:</p>
<pre><code>if(order.Lines.All(l=>l.IsClosed)) order.Close();
</code></pre>
<p>(checks all lines are closed, and if so, closes the order)</p>
<p>of in a query:</p>
<pre><code>var qry = from order in ctx.Orders
where order.CustomerId = id
select new {
order.OrderId,
IsShipped = order.Lines.All(l => l.IsShipped)
};
</code></pre>
|
How to convert Byte array into string? <p>I have structure as follows:</p>
<p>struct data
{int no; string name; int id};</p>
<p>I am converting this structure into bytearray. I need to convert this back into structure format. For that I need to convert first members into integer and string. How to convert bytearray into structure ?</p>
| <p>Well the answer really depends on how are you converting the structure into byte array. In theory, you will need to perform the same steps in reverse sequence!</p>
<p>For example if you serialize the structure such that:</p>
<ul>
<li>first 4 bytes = no</li>
<li>second 4 bytes = id</li>
<li>rest bytes = byte stream of
characters in name</li>
</ul>
<p>then to convert the byte array back to structure, you just need to define a variable of that structure type and assign the members with values converted from byte array!</p>
|
In what languages/platforms is Invoke for GUI operations required? <p>I understand that in .NET, one needs to use Control.Invoke(delegate) to perform operations on a control. This lead me to wondering in which environments Invoke is actually required. As far as i know, it was not required in older versions of, say, Visual Basic and Pascal. In particular, what is the status of Java (possibly version-dependent?) and "old style" windows GUI programming (manually reading the message queue)?</p>
| <p>You are mistaken. Control.Invoke is not required to perform operations on a control.</p>
<p>Control.Invoke is a useful tool to help marshall code across thread boundaries, but it is not the only way to do it. You will see this used most often when you do some work in a background thread.</p>
<p>When you call code from a background thread that must update a Windowed control (that is, a control that has a Windows window handle and processes messages via message pump), change it's properties, or some other manipulation of the control then you must pass control to the MessagePump thread, and Control.Invoke is a useful way to acocmplish that.</p>
<p>In <em>ALL</em> programs that run under Windows, you cannot call functions that update controls on a background thread. Some languages may handle this detail in the background, but I don't know of any that do. </p>
|
Flex/AS3 Drag Drop - Custom Drop Feedback <p>I am using a <code>HorizontalList</code> component to display a list of images, you can drag images from another component to join the list, this all works fine.</p>
<p>If I do <code>list.showDropFeedback(event)</code> I get an unsightly black bar at the top of images in the <code>HorizontalList</code> - what I really want is a line to the left/right of the image, where the new one will actually sit.</p>
<p>I guess I need to define a custom DropFeedback to override the default. Does anyone know if there there is a way to achieve this?</p>
<p>Thanks!</p>
| <p>Yuo can sove it by overriding showDropFeedback() method. My code below:</p>
<pre><code> import mx.controls.HorizontalList;
import mx.controls.listClasses.IListItemRenderer;
import mx.core.mx_internal;
import mx.events.DragEvent;
use namespace mx_internal;
public class HList extends HorizontalList
{
public function HList()
{
super();
}
override public function showDropFeedback(event:DragEvent):void
{
super.showDropFeedback(event);
dropIndicator.setActualSize(rowHeight - 4, 4);
DisplayObject(dropIndicator).rotation = 90;
}
}
</code></pre>
|
Should I use Java date and time classes or go with a 3rd party library like Joda Time? <p>I'm creating a web based system which will be used in countries from all over the world. One type of data which must be stored is dates and times.</p>
<p>What are the pros and cons of using the Java date and time classes compared to 3rd party libraries such as <a href="http://www.joda.org/joda-time/">Joda time</a>? I guess these third party libraries exist for a good reason, but I've never really compared them myself.</p>
| <p>EDIT: Now that Java 8 has been released, if you can use that, do so! <code>java.time</code> is even cleaner than Joda Time, in my view. However, if you're stuck pre-Java-8, read on...</p>
<p>Max asked for the pros and cons of using Joda...</p>
<p>Pros:</p>
<ul>
<li>It works, very well. I strongly suspect there are far fewer bugs in Joda than the standard Java libraries. Some of the bugs in the Java libraries are really hard (if not impossible) to fix due to the design.</li>
<li>It's designed to encourage you to think about date/time handling in the right way - separating the concept of a "local time" (e.g "wake me at 7am wherever I am") and an instant in time ("I'm calling James at 3pm PST; it may not be 3pm where he is, but it's the same instant")</li>
<li>I believe it makes it easier to update the timezone database, which <em>does</em> change relatively frequently</li>
<li>It has a good immutability story, which makes life a <em>lot</em> easier IME.</li>
<li>Leading on from immutability, all the formatters are thread-safe, which is great because you almost <em>always</em> want to reuse a single formatter through the application</li>
<li>You'll have a head-start on learning <code>java.time</code> in Java 8, as they're at least somewhat similar</li>
</ul>
<p>Cons:</p>
<ul>
<li>It's another API to learn (although the docs are pretty good)</li>
<li>It's another library to build against and deploy</li>
<li>When you use Java 8, there's still some work to migrate your skills</li>
<li>I've failed to use the <code>DateTimeZoneBuilder</code> effectively in the past. This is a <em>very</em> rare use case though.</li>
</ul>
<p>To respond to the oxbow_lakes' idea of effectively building your own small API, here are my views of why this is a bad idea:</p>
<ul>
<li>It's work. Why do work when it's already been done for you?</li>
<li>A newcomer to your team is much more likely to be familiar with Joda than with your homegrown API</li>
<li>You're likely to get it wrong for anything beyond the simplest uses... and even if you initially <em>think</em> you only need simple functionality, these things have a habit of growing more complicated, one tiny bit at a time. Date and time manipulation is <em>hard</em> to do properly. Furthermore, the built-in Java APIs are hard to <em>use</em> properly - just look at the rules for how the calendar API's date/time arithmetic works. Building anything on top of these is a bad idea rather than using a well-designed library to start with.</li>
</ul>
|
What options are available for the layout of directed or undirected graphs in .NET? <p>By <em>graph</em> here I mean something resembling these images:</p>
<p><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/e/e4/Directed_graph_with_back_edge.svg/298px-Directed_graph_with_back_edge.svg.png" width="202">
<img src="http://upload.wikimedia.org/wikipedia/commons/thumb/d/dc/Directed_cycle.svg/200px-Directed_cycle.svg.png">
<img src="http://upload.wikimedia.org/wikipedia/commons/thumb/b/bc/UnitedStatesGraphViz.svg/250px-UnitedStatesGraphViz.svg.png"></p>
<p>The ideal solution would:</p>
<ul>
<li>use only managed code</li>
<li>allow output to a bitmap image</li>
<li>allow output to WPF elements</li>
<li>include some kind of interactive surface for displaying the graph that supports zooming, panning and reorganisation of nodes</li>
</ul>
<p>I'm also interested in hearing about projects that could potentially be used as the starting point for this kind of work. If it requires some development to achieve what I want, then I'm prepared to tackle it. The most complex portion of this goal seems to be obtaining the graph layout in a reasonable time frame.</p>
| <p><a href="http://graphsharp.codeplex.com/">Graph#</a> is also another option. I haven't used it personally, but I've been meaning to get around to looking over it.</p>
|
default value of a variable at the time of declaration in C# and VB? <p>Can anybody tell me what is the default value of a variable at the time of declaration in C# and vb??</p>
| <p>In c# you can use the default keyword to determine default values.</p>
<p>For example:</p>
<pre>
default(bool)
default(int)
default(int?)
</pre>
|
How popular are security code reviews? <p>Real world, how many here undergo in-depth security code reviews? Those that do, how often - once a quarter, once a version, once a blue moon? Those that don't - why not? (Not referring to small or hobby programmers - not that I'm trivializing them, its just I don't expect them to ;-) ).</p>
<p>As a security consultant, I'm usually the one called in to do the security reviews, however this is usually only either for very security-sensitive organizations (e.g. large banks, software vendors, military, etc), or as a result of regulatory requirements (e.g. PCI-DSS).<br />
Now, few groups (except those in the biggest companies such as Microsoft, Intel, RSA, etc) really enjoy the review, even though it really should be a positive experience. It seems to me that this is mostly because of the perceived high investment - of resources, time, and of course cash to bring in the consultants. </p>
<p>Okay, so it's not just perceived, it's real enough: it's commonly accepted that a single reviewer can cover between 50-100 LoC per hour. Though we've managed to multiply that - since we're only looking for specific security issues (and the clients are pressing hard for lower costs) and we can minimize the scope according to the risk - we can max out at around 1000 LoC per hour. For any medium-to-large system, this is still hundreds of costly consultant hours, not trivial at all.</p>
<p>The common suggested alternative is automatic source code scanners, ala Fortify, ounce labs, etc. However, besides the licensing costs, this is far from efficient - typically we find these tools to produce results in the 100 thousands, with a very high (70-90%) rate of false positives (and duplicates). So you're still spending large chunks of time going over the results, AND these tools do not cover a substantial set of potential vulnerabilities (e.g. logic flaws, business logic, etc)</p>
<p>That said, (and a big DISCLAIMER should go here:) I've been working the past few months with one of the tool vendors to develop a service that would do this very efficiently - e.g. be able to cover 500K LoC in just around a single week of work, and yet provide actual, real accurate and complete results - virtually ZERO false positives and nearly no missed false negatives.</p>
<p>Those of you who should be doing SCR, but aren't - would this be enough to convince you otherwise? or is there something else holding you back? Or is it just not an issue for you?</p>
<p><hr /></p>
<p>To clarify, I'm not trying to promote myself or my service, just trying to get some real-world perspective beyond my own security-evangelistic agenda. I'd like to see the issues as other programmers see them... </p>
<p>Further clarification, I am NOT asking HOW to perform code reviews, what options there are, etc. I have much expertise in this field, and it is this expertise that I sell to my clients. My question is IF code reviews are as unpopular as they seem, WHY this specific activity is not as popular as it should be, and HOW we can go about changing this. (Irrelevant of choice of methodology, tool, etc.) </p>
<p><hr /></p>
<p>Furthermore, as Corneliu and others pointed out, security code reviews should NOT be taken alone as the sole protection and verification of a system's security, rather should be one element of a complete, holistic SDLC (secure development lifecycle) framework. However, neither should it be forgotten. So my question is really focusing on that one element, whether in the context of the full SDLC or alone as a step forward from penetrate-and-patch.</p>
| <p>I'm from Australia and I have to say that security reviews are (maybe) more popular here.<br />
In the last two projects I've worked we had formal security reviews. I have one more review aligned in the close future but from my perspective a "security review" is wrong by design. </p>
<p>People who do security reviews just look for a cheap silver-bullet to tell them the code is not completely busted and that the chance for an application attack is slightly lower than "it will happen in the first 10 hours of production".</p>
<p>I think a security review starts with:</p>
<ul>
<li>an Architectural Review from a Security Perspective when the architecture is put in place. </li>
<li>Then you work with the architect + business on Threat Modelling and understanding the potential issues to be faced and mitigations that can be put in place.</li>
<li>Then you build an approach for putting these mitigations in place preferably at an architecture level and try to isolate business-level developers from as much of the security code as possible.</li>
<li>Next I would do the full Security Development Life-cycle with the team and teach them proper secure-coding guidelines. Show them all the types of attacks that can happen on their application based on the Threat Model that you built before. Show them how to code and protect.</li>
<li>Teach the team about defence in depth and how to secure each piece of their puzzle</li>
<li>Teach them how to deploy securely, how to design isolated pieces with a minimum required security on them and so on.</li>
<li>Teach them how to do security code reviews of their own code and provoke them to provoke each-other in writing better code.</li>
</ul>
<p>This would take you a good two weeks I'd say. Maybe three.</p>
<p>Then, you come back regularly and do partial reviews, update the threat-model, and provide more guidance on potential issues that they might introduce.</p>
<p>With this you have a better chance at the end of the project to do a final code review and have a good trust that what you have is good and secure.</p>
<p>Oh, and you can sell this to a business much better than "I need a month to look at your code base and I'll let you know how busted your app is". You can go in holidays for a month and come back and tell them all is good mate and they have no idea what you did.</p>
<p>My 2 cents,</p>
<p>Corneliu.</p>
|
Setting the HTTP_REFERER in a global before(:all) in Rspec <p>In order to avoid adding</p>
<pre><code>request.env["HTTP_REFERER"] = '/'
</code></pre>
<p>to a before block on every controller_spec file I create, I have tried to add this to the global config (in spec_helper.rb)</p>
<pre><code>config.before(:each) {request.env["HTTP_REFERER"] = '/'}
</code></pre>
<p>The problem is, I get the following error:</p>
<pre><code>You have a nil object when you didn't expect it!
The error occurred while evaluating nil.env
</code></pre>
<p>Has anyone any pointers on how to implement this correctly?</p>
<p>Cheers!</p>
| <p>Have you tried</p>
<pre><code> config.before(:type => :controller) do
request.env["HTTP_REFERER"] = "/"
end
</code></pre>
|
How to Log Stack Frames with Windows x64 <p>I am using Stackdumps with Win32, to write all return adresses into my logfile. I match these with a mapfile later on (see my article [Post Mortem Debugging][1]). </p>
<p><strong>EDIT:: Problem solved - see my own answer below.</strong></p>
<p>With Windows x64 i do not find a reliable way to write only the return adresses into the logfile. I tried several ways:</p>
<p><strong>Trial 1: Pointer Arithmetic:</strong></p>
<pre><code> CONTEXT Context;
RtlCaptureContext(&Context);
char *eNextBP = (char *)Context.Rdi;
for(ULONG Frame = 0; eNextBP ; Frame++)
{
char *pBP = eNextBP;
eNextBP = *(char **)pBP; // Next BP in Stack
fprintf(LogFile, "*** %2d called from %016LX (pBP at %016LX)\n", Frame,
(ULONG64)*(char **)(pBP + 8), (ULONG64)pBP);
}
</code></pre>
<p>This works fine in the debug version - but it crashes in the release version. The value of Context.Rdi has no usable value there. I did check for differences in the compiler settings (visual Studio 2005). I have not found anything suspicious.</p>
<p><strong>Trial 2: Using StackWalk64</strong></p>
<pre><code>RtlCaptureContext(&Context);
STACKFRAME64 stk;
memset(&stk, 0, sizeof(stk));
stk.AddrPC.Offset = Context.Rip;
stk.AddrPC.Mode = AddrModeFlat;
stk.AddrStack.Offset = Context.Rsp;
stk.AddrStack.Mode = AddrModeFlat;
stk.AddrFrame.Offset = Context.Rbp;
stk.AddrFrame.Mode = AddrModeFlat;
for(ULONG Frame = 0; ; Frame++)
{
BOOL result = StackWalk64(
IMAGE_FILE_MACHINE_AMD64, // __in DWORD MachineType,
GetCurrentProcess(), // __in HANDLE hProcess,
GetCurrentThread(), // __in HANDLE hThread,
&stk, // __inout LP STACKFRAME64 StackFrame,
&Context, // __inout PVOID ContextRecord,
NULL, // __in_opt PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine,
SymFunctionTableAccess64, // __in_opt PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine,
SymGetModuleBase64, // __in_opt PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine,
NULL // __in_opt PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress
);
fprintf(gApplSetup.TraceFile, "*** %2d called from %016LX STACK %016LX FRAME %016LX\n", Frame, (ULONG64)stk.AddrPC.Offset, (ULONG64)stk.AddrStack.Offset, (ULONG64)stk.AddrFrame.Offset);
if(! result)
break;
}
</code></pre>
<p>This does not only dump the return addresses, but the WHOLE STACK. I receive about 1000 lines in my log file using this approach. I can use this, but i have to search trough the lines and some data of the stacks happens to be a valid code address.</p>
<p><strong>Trial 3: Using Backtrace</strong></p>
<pre><code>static USHORT (WINAPI
*s_pfnCaptureStackBackTrace)(ULONG, ULONG, PVOID*, PULONG) = 0;
if (s_pfnCaptureStackBackTrace == 0)
{
const HMODULE hNtDll = ::GetModuleHandle("ntdll.dll");
reinterpret_cast<void*&>(s_pfnCaptureStackBackTrace)
= ::GetProcAddress(hNtDll, "RtlCaptureStackBackTrace");
}
PVOID myFrames[128];
s_pfnCaptureStackBackTrace(0, 128, myFrames, NULL);
for(int ndx = 0; ndx < 128; ndx++)
fprintf(gApplSetup.TraceFile, "*** BackTrace %3d %016LX\n", ndx, (ULONG64)myFrames[ndx]);
</code></pre>
<p>Results in no usable information.</p>
<p>Has anyone implemented such a stack walk in x64 that does only write out the return adresses in the stack? Ive seen the approaches [StackTrace64][2], [StackWalker][3] and other ones. They either do not compile or they are much too much comlicated. It basically is a simple task!</p>
<p><strong>Sample StackDump64.cpp</strong></p>
<pre><code>#include <Windows.h>
#include <DbgHelp.h>
#include <Winbase.h>
#include <stdio.h>
void WriteStackDump()
{
FILE *myFile = fopen("StackDump64.log", "w+t");
CONTEXT Context;
memset(&Context, 0, sizeof(Context));
RtlCaptureContext(&Context);
RtlCaptureContext(&Context);
STACKFRAME64 stk;
memset(&stk, 0, sizeof(stk));
stk.AddrPC.Offset = Context.Rip;
stk.AddrPC.Mode = AddrModeFlat;
stk.AddrStack.Offset = Context.Rsp;
stk.AddrStack.Mode = AddrModeFlat;
stk.AddrFrame.Offset = Context.Rbp;
stk.AddrFrame.Mode = AddrModeFlat;
for(ULONG Frame = 0; ; Frame++)
{
BOOL result = StackWalk64(
IMAGE_FILE_MACHINE_AMD64, // __in DWORD MachineType,
GetCurrentProcess(), // __in HANDLE hProcess,
GetCurrentThread(), // __in HANDLE hThread,
&stk, // __inout LP STACKFRAME64 StackFrame,
&Context, // __inout PVOID ContextRecord,
NULL, // __in_opt PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine,
SymFunctionTableAccess64, // __in_opt PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine,
SymGetModuleBase64, // __in_opt PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine,
NULL // __in_opt PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress
);
fprintf(myFile, "*** %2d called from %016I64LX STACK %016I64LX AddrReturn %016I64LX\n", Frame, stk.AddrPC.Offset, stk.AddrStack.Offset, stk.AddrReturn.Offset);
if(! result)
break;
}
fclose(myFile);
}
void funcC()
{
WriteStackDump();
}
void funcB()
{
funcC();
}
void funcA()
{
funcB();
}
int main(int argc, char *argv[])
{
funcA();
}
</code></pre>
<p>Running this sample results in the follwing log file content:</p>
<pre><code>*** 0 called from 000000014000109E STACK 000000000012F780 AddrReturn 0000000140005798
*** 1 called from 000000001033D160 STACK 000000000012F788 AddrReturn 00000001400057B0
*** 2 called from 00000001400057B0 STACK 000000000012F790 AddrReturn 0000000000000001
*** 3 called from 0000000000000002 STACK 000000000012F798 AddrReturn 00000001400057B0
*** 4 called from 0000000000000002 STACK 000000000012F7A0 AddrReturn 000000000012F7F0
*** 5 called from 000000000012F7F0 STACK 000000000012F7A8 AddrReturn 0000000000000000
*** 6 called from 0000000000000000 STACK 000000000012F7B0 AddrReturn 000007FF7250CF40
*** 7 called from 000007FF7250CF40 STACK 000000000012F7B8 AddrReturn 000007FF7250D390
*** 8 called from 000007FF7250D390 STACK 000000000012F7C0 AddrReturn 000007FF725B6950
*** 9 called from 000007FF725B6950 STACK 000000000012F7C8 AddrReturn CCCCCCCCCCCCCCCC
*** 10 called from CCCCCCCCCCCCCCCC STACK 000000000012F7D0 AddrReturn 000000001033D160
*** 11 called from 000000001033D160 STACK 000000000012F7D8 AddrReturn CCCCCCCCCCCCCCCC
*** 12 called from CCCCCCCCCCCCCCCC STACK 000000000012F7E0 AddrReturn CCCCCCCCCCCCCCCC
*** 13 called from CCCCCCCCCCCCCCCC STACK 000000000012F7E8 AddrReturn CCCCCCCCCCCCCCCC
*** 14 called from CCCCCCCCCCCCCCCC STACK 000000000012F7F0 AddrReturn 0000000000000000
*** 15 called from 0000000000000000 STACK 000000000012F7F8 AddrReturn 0000000000000000
*** 16 called from 0000000000000000 STACK 000000000012F800 AddrReturn 0000000000000000
*** 17 called from 0000000000000000 STACK 000000000012F808 AddrReturn 0000000000000000
*** 18 called from 0000000000000000 STACK 000000000012F810 AddrReturn 0000000000000000
*** 19 called from 0000000000000000 STACK 000000000012F818 AddrReturn 0000000000000000
*** 20 called from 0000000000000000 STACK 000000000012F820 AddrReturn 00001F800010000F
*** 21 called from 00001F800010000F STACK 000000000012F828 AddrReturn 0053002B002B0033
*** 22 called from 0053002B002B0033 STACK 000000000012F830 AddrReturn 00000206002B002B
*** 23 called from 00000206002B002B STACK 000000000012F838 AddrReturn 0000000000000000
*** 24 called from 0000000000000000 STACK 000000000012F840 AddrReturn 0000000000000000
*** 25 called from 0000000000000000 STACK 000000000012F848 AddrReturn 0000000000000000
*** 26 called from 0000000000000000 STACK 000000000012F850 AddrReturn 0000000000000000
*** 27 called from 0000000000000000 STACK 000000000012F858 AddrReturn 0000000000000000
*** 28 called from 0000000000000000 STACK 000000000012F860 AddrReturn 0000000000000000
*** 29 called from 0000000000000000 STACK 000000000012F868 AddrReturn 0000000000000246
*** 30 called from 0000000000000246 STACK 000000000012F870 AddrReturn 000000000012F7F0
*** 31 called from 000000000012F7F0 STACK 000000000012F878 AddrReturn 0000000000000000
*** 32 called from 0000000000000000 STACK 000000000012F880 AddrReturn 0000000000000000
*** 33 called from 0000000000000000 STACK 000000000012F888 AddrReturn 000000000012F888
*** 34 called from 000000000012F888 STACK 000000000012F890 AddrReturn 0000000000000000
*** 35 called from 0000000000000000 STACK 000000000012F898 AddrReturn 0000000000000000
*** 36 called from 0000000000000000 STACK 000000000012F8A0 AddrReturn 000000000012FE10
*** 37 called from 000000000012FE10 STACK 000000000012F8A8 AddrReturn 0000000000000000
*** 38 called from 0000000000000000 STACK 000000000012F8B0 AddrReturn 0000000000000000
*** 39 called from 0000000000000000 STACK 000000000012F8B8 AddrReturn 0000000000000000
*** 40 called from 0000000000000000 STACK 000000000012F8C0 AddrReturn 0000000000000246
*** 41 called from 0000000000000246 STACK 000000000012F8C8 AddrReturn 0000000000000000
*** 42 called from 0000000000000000 STACK 000000000012F8D0 AddrReturn 0000000000000000
*** 43 called from 0000000000000000 STACK 000000000012F8D8 AddrReturn 0000000000000000
*** 44 called from 0000000000000000 STACK 000000000012F8E0 AddrReturn 0000000000000000
*** 45 called from 0000000000000000 STACK 000000000012F8E8 AddrReturn 0000000000000000
*** 46 called from 0000000000000000 STACK 000000000012F8F0 AddrReturn 000000000000027F
*** 47 called from 000000000000027F STACK 000000000012F8F8 AddrReturn 0000000000000000
*** 48 called from 0000000000000000 STACK 000000000012F900 AddrReturn 0000000000000000
*** 49 called from 0000000000000000 STACK 000000000012F908 AddrReturn 0000FFFF00001F80
*** 50 called from 0000FFFF00001F80 STACK 000000000012F910 AddrReturn 0000000000000000
*** 51 called from 0000000000000000 STACK 000000000012F918 AddrReturn 0000000000000000
*** 52 called from 0000000000000000 STACK 000000000012F920 AddrReturn 0000000000000000
*** 53 called from 0000000000000000 STACK 000000000012F928 AddrReturn 0000000000000000
*** 54 called from 0000000000000000 STACK 000000000012F930 AddrReturn 0000000000000000
*** 55 called from 0000000000000000 STACK 000000000012F938 AddrReturn 0000000000000000
*** 56 called from 0000000000000000 STACK 000000000012F940 AddrReturn 0000000000000000
*** 57 called from 0000000000000000 STACK 000000000012F948 AddrReturn 0000000000000000
*** 58 called from 0000000000000000 STACK 000000000012F950 AddrReturn 0000000000000000
*** 59 called from 0000000000000000 STACK 000000000012F958 AddrReturn 0000000000000000
*** 60 called from 0000000000000000 STACK 000000000012F960 AddrReturn 0000000000000000
*** 61 called from 0000000000000000 STACK 000000000012F968 AddrReturn 0000000000000000
*** 62 called from 0000000000000000 STACK 000000000012F970 AddrReturn 0000000000000000
*** 63 called from 0000000000000000 STACK 000000000012F978 AddrReturn 0000000000000000
*** 64 called from 0000000000000000 STACK 000000000012F980 AddrReturn 0000000000000000
*** 65 called from 0000000000000000 STACK 000000000012F988 AddrReturn 0000000000000000
*** 66 called from 0000000000000000 STACK 000000000012F990 AddrReturn 0000000000000000
*** 67 called from 0000000000000000 STACK 000000000012F998 AddrReturn 0000000000000000
*** 68 called from 0000000000000000 STACK 000000000012F9A0 AddrReturn 0000000000000000
*** 69 called from 0000000000000000 STACK 000000000012F9A8 AddrReturn 0000000000000000
*** 70 called from 0000000000000000 STACK 000000000012F9B0 AddrReturn 0000000000000000
*** 71 called from 0000000000000000 STACK 000000000012F9B8 AddrReturn 0000000000000000
*** 72 called from 0000000000000000 STACK 000000000012F9C0 AddrReturn 0000000000000000
*** 73 called from 0000000000000000 STACK 000000000012F9C8 AddrReturn 0000000000000000
*** 74 called from 0000000000000000 STACK 000000000012F9D0 AddrReturn 0000000000000000
*** 75 called from 0000000000000000 STACK 000000000012F9D8 AddrReturn 0000000000000000
*** 76 called from 0000000000000000 STACK 000000000012F9E0 AddrReturn 0000000000000000
*** 77 called from 0000000000000000 STACK 000000000012F9E8 AddrReturn 0000000000000000
*** 78 called from 0000000000000000 STACK 000000000012F9F0 AddrReturn 0000000000000000
*** 79 called from 0000000000000000 STACK 000000000012F9F8 AddrReturn 0000000000000000
*** 80 called from 0000000000000000 STACK 000000000012FA00 AddrReturn 0000000000000000
*** 81 called from 0000000000000000 STACK 000000000012FA08 AddrReturn 0000000000000000
*** 82 called from 0000000000000000 STACK 000000000012FA10 AddrReturn 0000000000000000
*** 83 called from 0000000000000000 STACK 000000000012FA18 AddrReturn 0000000000000000
*** 84 called from 0000000000000000 STACK 000000000012FA20 AddrReturn 0000000000000000
*** 85 called from 0000000000000000 STACK 000000000012FA28 AddrReturn 0000000000000000
*** 86 called from 0000000000000000 STACK 000000000012FA30 AddrReturn 0000000000000000
*** 87 called from 0000000000000000 STACK 000000000012FA38 AddrReturn 0000000000000000
*** 88 called from 0000000000000000 STACK 000000000012FA40 AddrReturn 0000000000000000
*** 89 called from 0000000000000000 STACK 000000000012FA48 AddrReturn 0000000000000000
*** 90 called from 0000000000000000 STACK 000000000012FA50 AddrReturn 0000000000000000
*** 91 called from 0000000000000000 STACK 000000000012FA58 AddrReturn 0000000000000000
*** 92 called from 0000000000000000 STACK 000000000012FA60 AddrReturn 0000000000000000
*** 93 called from 0000000000000000 STACK 000000000012FA68 AddrReturn 0000000000000000
*** 94 called from 0000000000000000 STACK 000000000012FA70 AddrReturn 0000000000000000
*** 95 called from 0000000000000000 STACK 000000000012FA78 AddrReturn 0000000000000000
*** 96 called from 0000000000000000 STACK 000000000012FA80 AddrReturn 0000000000000000
*** 97 called from 0000000000000000 STACK 000000000012FA88 AddrReturn 0000000000000000
*** 98 called from 0000000000000000 STACK 000000000012FA90 AddrReturn 0000000000000000
*** 99 called from 0000000000000000 STACK 000000000012FA98 AddrReturn 0000000000000000
*** 100 called from 0000000000000000 STACK 000000000012FAA0 AddrReturn 0000000000000000
*** 101 called from 0000000000000000 STACK 000000000012FAA8 AddrReturn 0000000000000000
*** 102 called from 0000000000000000 STACK 000000000012FAB0 AddrReturn 0000000000000000
*** 103 called from 0000000000000000 STACK 000000000012FAB8 AddrReturn 0000000000000000
*** 104 called from 0000000000000000 STACK 000000000012FAC0 AddrReturn 0000000000000000
*** 105 called from 0000000000000000 STACK 000000000012FAC8 AddrReturn 0000000000000000
*** 106 called from 0000000000000000 STACK 000000000012FAD0 AddrReturn 0000000000000000
*** 107 called from 0000000000000000 STACK 000000000012FAD8 AddrReturn 0000000000000000
*** 108 called from 0000000000000000 STACK 000000000012FAE0 AddrReturn 0000000000000000
*** 109 called from 0000000000000000 STACK 000000000012FAE8 AddrReturn 0000000000000000
*** 110 called from 0000000000000000 STACK 000000000012FAF0 AddrReturn 0000000000000000
*** 111 called from 0000000000000000 STACK 000000000012FAF8 AddrReturn 0000000000000000
*** 112 called from 0000000000000000 STACK 000000000012FB00 AddrReturn 0000000000000000
*** 113 called from 0000000000000000 STACK 000000000012FB08 AddrReturn 0000000000000000
*** 114 called from 0000000000000000 STACK 000000000012FB10 AddrReturn 0000000000000000
*** 115 called from 0000000000000000 STACK 000000000012FB18 AddrReturn 0000000000000000
*** 116 called from 0000000000000000 STACK 000000000012FB20 AddrReturn 0000000000000000
*** 117 called from 0000000000000000 STACK 000000000012FB28 AddrReturn 0000000000000000
*** 118 called from 0000000000000000 STACK 000000000012FB30 AddrReturn 0000000000000000
*** 119 called from 0000000000000000 STACK 000000000012FB38 AddrReturn 0000000000000000
*** 120 called from 0000000000000000 STACK 000000000012FB40 AddrReturn 0000000000000000
*** 121 called from 0000000000000000 STACK 000000000012FB48 AddrReturn 0000000000000000
*** 122 called from 0000000000000000 STACK 000000000012FB50 AddrReturn 0000000000000000
*** 123 called from 0000000000000000 STACK 000000000012FB58 AddrReturn 0000000000000000
*** 124 called from 0000000000000000 STACK 000000000012FB60 AddrReturn 0000000000000000
*** 125 called from 0000000000000000 STACK 000000000012FB68 AddrReturn 0000000000000000
*** 126 called from 0000000000000000 STACK 000000000012FB70 AddrReturn 0000000000000000
*** 127 called from 0000000000000000 STACK 000000000012FB78 AddrReturn 0000000000000000
*** 128 called from 0000000000000000 STACK 000000000012FB80 AddrReturn 0000000000000000
*** 129 called from 0000000000000000 STACK 000000000012FB88 AddrReturn 0000000000000000
*** 130 called from 0000000000000000 STACK 000000000012FB90 AddrReturn 0000000000000000
*** 131 called from 0000000000000000 STACK 000000000012FB98 AddrReturn 0000000000000000
*** 132 called from 0000000000000000 STACK 000000000012FBA0 AddrReturn 0000000000000000
*** 133 called from 0000000000000000 STACK 000000000012FBA8 AddrReturn 0000000000000000
*** 134 called from 0000000000000000 STACK 000000000012FBB0 AddrReturn 0000000000000000
*** 135 called from 0000000000000000 STACK 000000000012FBB8 AddrReturn 0000000000000000
*** 136 called from 0000000000000000 STACK 000000000012FBC0 AddrReturn 0000000000000000
*** 137 called from 0000000000000000 STACK 000000000012FBC8 AddrReturn 0000000000000000
*** 138 called from 0000000000000000 STACK 000000000012FBD0 AddrReturn 0000000000000000
*** 139 called from 0000000000000000 STACK 000000000012FBD8 AddrReturn 0000000000000000
*** 140 called from 0000000000000000 STACK 000000000012FBE0 AddrReturn 0000000000000000
*** 141 called from 0000000000000000 STACK 000000000012FBE8 AddrReturn 0000000000000000
*** 142 called from 0000000000000000 STACK 000000000012FBF0 AddrReturn 0000000000000000
*** 143 called from 0000000000000000 STACK 000000000012FBF8 AddrReturn 0000000000000000
*** 144 called from 0000000000000000 STACK 000000000012FC00 AddrReturn 0000000000000000
*** 145 called from 0000000000000000 STACK 000000000012FC08 AddrReturn 0000000000000000
*** 146 called from 0000000000000000 STACK 000000000012FC10 AddrReturn 0000000000000000
*** 147 called from 0000000000000000 STACK 000000000012FC18 AddrReturn 0000000000000000
*** 148 called from 0000000000000000 STACK 000000000012FC20 AddrReturn 0000000000000000
*** 149 called from 0000000000000000 STACK 000000000012FC28 AddrReturn 0000000000000000
*** 150 called from 0000000000000000 STACK 000000000012FC30 AddrReturn 0000000000000000
*** 151 called from 0000000000000000 STACK 000000000012FC38 AddrReturn 0000000000000000
*** 152 called from 0000000000000000 STACK 000000000012FC40 AddrReturn 0000000000000000
*** 153 called from 0000000000000000 STACK 000000000012FC48 AddrReturn 0000000000000000
*** 154 called from 0000000000000000 STACK 000000000012FC50 AddrReturn 0000000000000000
*** 155 called from 0000000000000000 STACK 000000000012FC58 AddrReturn 0000000000000000
*** 156 called from 0000000000000000 STACK 000000000012FC60 AddrReturn 0000000000000000
*** 157 called from 0000000000000000 STACK 000000000012FC68 AddrReturn 0000000000000000
*** 158 called from 0000000000000000 STACK 000000000012FC70 AddrReturn 0000000000000000
*** 159 called from 0000000000000000 STACK 000000000012FC78 AddrReturn 0000000000000000
*** 160 called from 0000000000000000 STACK 000000000012FC80 AddrReturn 0000000000000000
*** 161 called from 0000000000000000 STACK 000000000012FC88 AddrReturn 0000000000000000
*** 162 called from 0000000000000000 STACK 000000000012FC90 AddrReturn 0000000000000000
*** 163 called from 0000000000000000 STACK 000000000012FC98 AddrReturn 0000000000000000
*** 164 called from 0000000000000000 STACK 000000000012FCA0 AddrReturn 0000000000000000
*** 165 called from 0000000000000000 STACK 000000000012FCA8 AddrReturn 0000000000000000
*** 166 called from 0000000000000000 STACK 000000000012FCB0 AddrReturn 0000000000000000
*** 167 called from 0000000000000000 STACK 000000000012FCB8 AddrReturn 0000000000000000
*** 168 called from 0000000000000000 STACK 000000000012FCC0 AddrReturn CCCCCCCCCCCCCCCC
*** 169 called from CCCCCCCCCCCCCCCC STACK 000000000012FCC8 AddrReturn CCCCCCCCCCCCCCCC
*** 170 called from CCCCCCCCCCCCCCCC STACK 000000000012FCD0 AddrReturn CCCCCCCCCCCCCCCC
*** 171 called from CCCCCCCCCCCCCCCC STACK 000000000012FCD8 AddrReturn CCCCCCCCCCCCCCCC
*** 172 called from CCCCCCCCCCCCCCCC STACK 000000000012FCE0 AddrReturn CCCCCCCCCCCCCCCC
*** 173 called from CCCCCCCCCCCCCCCC STACK 000000000012FCE8 AddrReturn 0000000300000000
*** 174 called from 0000000300000000 STACK 000000000012FCF0 AddrReturn 0000000300000000
*** 175 called from 0000000300000000 STACK 000000000012FCF8 AddrReturn 0000000300000000
*** 176 called from 0000000300000000 STACK 000000000012FD00 AddrReturn 000000000012FCF0
*** 177 called from 000000000012FCF8 STACK 000000000012FD08 AddrReturn 0000000300000000
*** 178 called from 0000000300000000 STACK 000000000012FD10 AddrReturn 000000000012FD10
*** 179 called from 000000000012FD18 STACK 000000000012FD18 AddrReturn 0000000300000000
*** 180 called from 0000000300000000 STACK 000000000012FD20 AddrReturn 0000000000000000
*** 181 called from 0000000000000000 STACK 000000000012FD28 AddrReturn 0000000000000000
*** 182 called from 0000000000000000 STACK 000000000012FD30 AddrReturn 0000000000000000
*** 183 called from 0000000000000000 STACK 000000000012FD38 AddrReturn 0000000000000000
*** 184 called from 0000000000000000 STACK 000000000012FD40 AddrReturn 0000000000000000
*** 185 called from 0000000100000000 STACK 000000000012FD48 AddrReturn 0000000100000000
*** 186 called from 0000000000000000 STACK 000000000012FD50 AddrReturn 0000000000000000
*** 187 called from 0000000000000000 STACK 000000000012FD58 AddrReturn 0000000100000000
*** 188 called from 0000000100000000 STACK 000000000012FD60 AddrReturn 0000000000000000
*** 189 called from 0000000000000000 STACK 000000000012FD68 AddrReturn 0000000000000000
*** 190 called from 0000000000000000 STACK 000000000012FD70 AddrReturn 0000000000000000
*** 191 called from 0000000000000000 STACK 000000000012FD78 AddrReturn 0000000000000000
*** 192 called from 0000000000000000 STACK 000000000012FD80 AddrReturn 0000000000000000
*** 193 called from 0000000000000000 STACK 000000000012FD88 AddrReturn 0000000000000000
*** 194 called from 0000000000000000 STACK 000000000012FD90 AddrReturn 0000000000000000
*** 195 called from 0000000000000000 STACK 000000000012FD98 AddrReturn 0000000000000000
*** 196 called from 0000000000000000 STACK 000000000012FDA0 AddrReturn 0000000000000000
*** 197 called from 0000000000000000 STACK 000000000012FDA8 AddrReturn 0000000000000000
*** 198 called from 0000000000000000 STACK 000000000012FDB0 AddrReturn 0000000000000000
*** 199 called from 0000000000000000 STACK 000000000012FDB8 AddrReturn 0000000000000000
*** 200 called from 0000000000000000 STACK 000000000012FDC0 AddrReturn 0000000000000000
*** 201 called from 0000000000000000 STACK 000000000012FDC8 AddrReturn 0000000000000000
*** 202 called from 0000000000000000 STACK 000000000012FDD0 AddrReturn 0000000000000000
*** 203 called from 0000000000000000 STACK 000000000012FDD8 AddrReturn 0000000000000000
*** 204 called from 0000000000000000 STACK 000000000012FDE0 AddrReturn 0000000000000000
*** 205 called from 0000000000000000 STACK 000000000012FDE8 AddrReturn CCCCCCCCCCCCCCCC
*** 206 called from CCCCCCCCCCCCCCCC STACK 000000000012FDF0 AddrReturn 000000CECCCCCCCC
*** 207 called from 000000CFCCCCCCCC STACK 000000000012FDF8 AddrReturn CCCCCCCC00000001
*** 208 called from CCCCCCCC00000001 STACK 000000000012FE00 AddrReturn FFFFFFFFFFFFFFFE
*** 209 called from FFFFFFFFFFFFFFFE STACK 000000000012FE08 AddrReturn CCCCCCCCCCCCCCCC
*** 210 called from CCCCCCCCCCCCCCCC STACK 000000000012FE10 AddrReturn 000000000012FE40
*** 211 called from 000000000012FE40 STACK 000000000012FE18 AddrReturn 000000014000122F
*** 212 called from 000000014000122F STACK 000000000012FE20 AddrReturn CCCCCCCCCCCCCCCC
*** 213 called from CCCCCCCCCCCCCCCC STACK 000000000012FE28 AddrReturn CCCCCCCCCCCCCCCC
*** 214 called from CCCCCCCCCCCCCCCC STACK 000000000012FE30 AddrReturn CCCCCCCCCCCCCCCC
*** 215 called from CCCCCCCCCCCCCCCC STACK 000000000012FE38 AddrReturn CCCCCCCCCCCCCCCC
*** 216 called from CCCCCCCCCCCCCCCC STACK 000000000012FE40 AddrReturn 000000000012FE70
*** 217 called from 000000000012FE70 STACK 000000000012FE48 AddrReturn 000000014000125F
*** 218 called from 000000014000125F STACK 000000000012FE50 AddrReturn CCCCCCCCCCCCCCCC
*** 219 called from CCCCCCCCCCCCCCCC STACK 000000000012FE58 AddrReturn CCCCCCCCCCCCCCCC
*** 220 called from CCCCCCCCCCCCCCCC STACK 000000000012FE60 AddrReturn CCCCCCCCCCCCCCCC
*** 221 called from CCCCCCCCCCCCCCCC STACK 000000000012FE68 AddrReturn CCCCCCCCCCCCCCCC
*** 222 called from CCCCCCCCCCCCCCCC STACK 000000000012FE70 AddrReturn 000000000012FEA0
*** 223 called from 000000000012FEA0 STACK 000000000012FE78 AddrReturn 000000014000128F
*** 224 called from 000000014000128F STACK 000000000012FE80 AddrReturn CCCCCCCCCCCCCCCC
*** 225 called from CCCCCCCCCCCCCCCC STACK 000000000012FE88 AddrReturn CCCCCCCCCCCCCCCC
*** 226 called from CCCCCCCCCCCCCCCC STACK 000000000012FE90 AddrReturn CCCCCCCCCCCCCCCC
*** 227 called from CCCCCCCCCCCCCCCC STACK 000000000012FE98 AddrReturn CCCCCCCCCCCCCCCC
*** 228 called from CCCCCCCCCCCCCCCC STACK 000000000012FEA0 AddrReturn 000000000012FED0
*** 229 called from 000000000012FED0 STACK 000000000012FEA8 AddrReturn 00000001400012CB
*** 230 called from 00000001400012CB STACK 000000000012FEB0 AddrReturn CCCCCCCCCCCCCCCC
*** 231 called from CCCCCCCCCCCCCCCC STACK 000000000012FEB8 AddrReturn CCCCCCCCCCCCCCCC
*** 232 called from CCCCCCCCCCCCCCCC STACK 000000000012FEC0 AddrReturn CCCCCCCCCCCCCCCC
*** 233 called from CCCCCCCCCCCCCCCC STACK 000000000012FEC8 AddrReturn CCCCCCCCCCCCCCCC
*** 234 called from CCCCCCCCCCCCCCCC STACK 000000000012FED0 AddrReturn 0000000000000000
*** 235 called from 0000000000000000 STACK 000000000012FED8 AddrReturn 000000014000190C
*** 236 called from 000000014000190C STACK 000000000012FEE0 AddrReturn 0000000100000001
*** 237 called from 0000000100000001 STACK 000000000012FEE8 AddrReturn 0000000000454B50
*** 238 called from 0000000000454B50 STACK 000000000012FEF0 AddrReturn 0000000000000000
*** 23
</code></pre>
| <p>I finally found a reliable way to log the stack frames in x64, using the Windows function CaptureStackBackTrace(). As i did not want to update my SDK, i call it via GetProcAddress(LoadLibrary());</p>
<pre><code> typedef USHORT (WINAPI *CaptureStackBackTraceType)(__in ULONG, __in ULONG, __out PVOID*, __out_opt PULONG);
CaptureStackBackTraceType func = (CaptureStackBackTraceType)(GetProcAddress(LoadLibrary("kernel32.dll"), "RtlCaptureStackBackTrace"));
if(func == NULL)
return; // WOE 29.SEP.2010
// Quote from Microsoft Documentation:
// ## Windows Server 2003 and Windows XP:
// ## The sum of the FramesToSkip and FramesToCapture parameters must be less than 63.
const int kMaxCallers = 62;
void* callers[kMaxCallers];
int count = (func)(0, kMaxCallers, callers, NULL);
for(i = 0; i < count; i++)
printf(TraceFile, "*** %d called from %016I64LX\n", i, callers[i]);
</code></pre>
<p>This works without problems.</p>
|
Html Bugs in Opera <p>In versions of opera greater than 9.0, I have found a bug that fails to render a large portion of my text. This happens with links, span and strong tags. As well as this, it throws a strange error with sup tags.</p>
<p>Here is the link to the live site: <a href="http://clients.bionic-comms.co.uk/licensingawards/microsite/enter.html" rel="nofollow">http://clients.bionic-comms.co.uk/licensingawards/microsite/enter.html</a>
Below is the code (the first div doesn't give me any problems at all):</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Licensing Awards '09 - Enter Your Products</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<!--[if IE 6]>
<link rel="stylesheet" type="text/css" href="css/ie.css">
<![endif]-->
<noscript><link rel="stylesheet" type="text/css" href="css/noscript.css"></noscript>
<script src="js/shadedborder/shadedborder.js" type="text/javascript"></script>
</head>
<body>
<div id="page">
<div id="otherbits">
<a href="about.html" id="licensing" name="About"><i>About</i></a>
<a href="http://www.bionic-comms.co.uk" id="bionic" name="Bionic"><i>Bionic</i></a>
</div>
<div id="header">
<div id="nav">
<div id="menu">
<a href="enter.html" id="home" name="Home"><i>Home</i></a>
<a href="nominate.html" id="nominate" name="nominate"><i>nominate</i></a>
<a href="tickets.html" id="tickets" name="tickets"><i>tickets</i></a>
<a href="about.html" id="about" name="about"><i>about</i></a>
<a href="photos.html" id="photos" name="photos"><i>photos</i></a>
</div>
</div>
</div>
<div id="lildetails">
<p>Thursday September 10th 2009, Royal Lancaster Hotel, London &bull; Black Tie / Posh Frocks</p>
</div>
<div id="enter">
<div class="head">
<h2 class="enter">Here you can download the entry form for the product categories in The Licensing Awards 2009. These annual product awards are open to all UK and Ireland-based companies and are for officially licensed ranges.</h2>
</div>
<div class="circle1">1</div>
<div class="text1">
<div id="my-border">
<h5 class="enter">Fill in the form:</h5><br /><span class="enter">Fill in the entry form (one form per entry). <strong>You can download the form <a href="files/entryform.pdf" class="enter">here</a>.</strong></span>
</div>
</div>
<div class="circle2">2</div>
<div class="text2">
<div id="my-border1">
<h5 class="enter">Select your product entries:</h5><br /><span class="enter">Check that the products being entered comply with the entry requirements (i.e. were launched between June 1st 2008 and May 31st 2009). You should submit up to five actual items for each licensed range. Remember &ndash; entries should be license&ndash;specific.</span>
</div>
</div>
<div class="circle3">3</div>
<div class="text3">
<div id="my-border2">
<h5 class="enter">Send your entries:</h5><br /><span class="enter">All entry forms, samples and supporting materials should be sent (arriving no later than June 1st) to:<br /><br /> <span class="enter">The Licensing Awards, Max Publishing, United House, North Road, London, N7 9DP</span>.<br /><br />For further clarification on entering contact Ian Hyder or Jakki Brown at The Licensing Source Book on 202 7700 6740 or by email: <a href="mailto:ianh@max-publishing.co.uk" class="enter">ianh@max-publishing.co.uk</a></span>
</div>
</div>
</div>
</div>
<script language="javascript" type="text/javascript">
var browser=navigator.appName;
var b_version=navigator.appVersion;
var version=parseFloat(b_version);
if ((browser=="Microsoft Internet Explorer") && (version=4)) { }
else {
var myBorder = RUZEE.ShadedBorder.create({ corner:8, shadow:16 });
myBorder.render('my-border');
myBorder.render('my-border1');
myBorder.render('my-border2');
}
</script>
</body>
</html>
</code></pre>
<p>If someone could shed some light on this or tell me what i'm doing wrong, it would be much appreciated. </p>
| <p>I don't know why, as I know sod all about Javascript, but its your shadedbo.js that's causing the error. Removal of that (and only that) makes the site render correctly on Opera 9.26</p>
|
create .project file for flex application <p>I want to add my flex project to a SCM like Clearcase and then allow other developers download it and use in FlexBuilder. </p>
<p>What foramt do i need to place it in my clearcase so users can simply download and import into Flex Builder? Is there some way to create a .project file or similiar to allow Flex Recognise the project in clearcase?</p>
| <p>I do not know Flex Builder project config files (I do know very well ClearCase though), but this question looks like "<a href="http://stackoverflow.com/questions/116121/do-you-keep-your-project-files-under-version-control/119377#119377">Do you keep your project files under version control ?</a>" or "<a href="http://stackoverflow.com/questions/337304/which-eclipse-files-belong-under-version-control/337317">Which eclipse files belong under Version Control</a>"</p>
<p>In essence, you should put any config file in ClearCase as long as you have relative path and/or variable for the other users to interpret.</p>
<p>A snapshot or dynamic ClearCase view will simply present those files for them to use, whatever they are. For instance, some eclipse .project or .classpath can be stored that way, while using <a href="http://stackoverflow.com/questions/300328#300346">linked directories</a>.</p>
<p>So for Flex Builder project, one way to determine what file to store is to copy a minimal subset of those files in a new directory and check if you can re-open your project successfully.<br />
Once the minimal set of file is determined, you can "add to source control" them.</p>
|
Tips for manual merge of diverged code <p>I am fairly used to using svn for branching and merging, normally this works fine. However one component was worked on in two branches and basically took the component in different directions, so automatic merge won't work and using beyond compare shows the files as mostly different.</p>
<p>I have tried to stitch together some of the files, but the results, even if they work, are fairly horrific.</p>
<p>I am tempted to say to the business that this just can't be done. I can see this frustrating them as they have module + feature A working and module + feature B working but module + feature A + feature B just doesnât make sense as it stands. For example feature A may remove something that was a key component in feature B.</p>
<p>Is there a way to try to merge such code? Or is module + A + B really module + C?</p>
<p>We did see this coming, but feature A was needed on a shorter time scale than feature B which was part of a long running project. Are there ways to work to avoid this happening? Or are their ways to structure the code so that both features will fit together nicely?</p>
| <p>What you're talking about is essentially trying to rebase one of the branches. There is support for this in <a href="http://git-scm.com/docs/git-rebase" rel="nofollow">some DVCSs</a> but I'm not aware of any support for this kind of thing in SVN.</p>
<p>Your best bet is to pick one of the branches (the one that is most important to have now) and merge it in to the main line which should be fairly straight forward. In the other branch you will need to pull the changes from trunk and reconcile the differences, given the situation you described, this will almost certainly not be automatic and you might have to spend some serious time thinking about how to implement this branches features on top of the one merged into the main line, but that's the cost of parallel development: things change.</p>
<p>How do you avoid this in the future? <a href="http://martinfowler.com/articles/continuousIntegration.html" rel="nofollow">Frequent integration</a>.</p>
<p>If you have two teams that are each given codebase A and they go and work on different features for 6 months, the integration is going to very painful as each will have made assumptions about A that the other team has changed. On the other hand, with weekly or monthly integration builds, each team should be substantially more aware about which changes the other is making and final integration should be much easier.</p>
<p>This is why open source projects often oppose huge patches, they get out of date startlingly fast and nobody really has the time to review them properly. On the other hand, if you take the same contribution and break it up into a number of small digestible parts that stand alone, your contribution is much more likely to be A) accepted and B) reviewed properly so that it doesn't result in an endless stream of defects.</p>
|
How to change a Python module name? <p>Is it only possible if I rename the file? Or is there a <code>__module__</code> variable to the file to define what's its name?</p>
| <p>If you really want to import the file 'oldname.py' with the statement 'import newname', there is a trick that makes it possible: Import the module <em>somewhere</em> with the old name, then inject it into <code>sys.modules</code> with the new name. Subsequent import statements will also find it under the new name. Code sample:</p>
<pre><code># this is in file 'oldname.py'
...module code...
</code></pre>
<p>Usage:</p>
<pre><code># inject the 'oldname' module with a new name
import oldname
import sys
sys.modules['newname'] = oldname
</code></pre>
<p>Now you can everywhere your module with <code>import newname</code>.</p>
|
Java TCP Socket Sniffing <p>I am using TCP sockets to communicate data between a server and client program using a specific port number on the same computer (localhost).</p>
<p>I need a software that can capture the data being sent/received through that socket?</p>
<p>(or)</p>
<p>What's the simplest way of sniffing packets from a specified port in Java?</p>
| <p>I suggest using Wireshark. It's easy to use and runs on many platforms.</p>
<p><a href="http://www.wireshark.org/" rel="nofollow">http://www.wireshark.org/</a></p>
|
C#: Declaring and using a list of generic classes with different types, how? <p>Having the following generic class that would contain either <strong><code>string, int, float, long</code></strong> as the type:</p>
<pre><code>public class MyData<T>
{
private T _data;
public MyData (T value)
{
_data = value;
}
public T Data { get { return _data; } }
}
</code></pre>
<p>I am trying to get a list of <strong><code>MyData<T></code></strong> where each item would be of different <strong><code>T</code></strong>.</p>
<p>I want to be able to access an item from the list and get its value as in the following code:</p>
<pre><code>MyData<> myData = _myList[0]; // Could be <string>, <int>, ...
SomeMethod (myData.Data);
</code></pre>
<p>where <strong><code>SomeMethod()</code></strong> is declared as follows:</p>
<pre><code>public void SomeMethod (string value);
public void SomeMethod (int value);
public void SomeMethod (float value);
</code></pre>
<p><hr /></p>
<p><strong>UPDATE:</strong></p>
<p><strong><code>SomeMethod()</code></strong> is from another tier class I do not have control of and <strong><code>SomeMethod(object)</code></strong> does not exist.</p>
<p><hr /></p>
<p>However, I can't seem to find a way to make the compiler happy.</p>
<p>Any suggestions?</p>
<p>Thank you.</p>
| <p>I think the issue that you're having is because you're trying to create a generic type, and then create a list of that generic type. You could accomplish what you're trying to do by contracting out the data types you're trying to support, say as an IData element, and then create your MyData generic with a constraint of IData. The downside to this would be that you would have to create your own data types to represent all the primitive data types you're using (string, int, float, long). It might look something like this:</p>
<pre><code>public class MyData<T, C>
where T : IData<C>
{
public T Data { get; private set; }
public MyData (T value)
{
Data = value;
}
}
public interface IData<T>
{
T Data { get; set; }
void SomeMethod();
}
//you'll need one of these for each data type you wish to support
public class MyString: IData<string>
{
public MyString(String value)
{
Data = value;
}
public void SomeMethod()
{
//code here that uses _data...
Console.WriteLine(Data);
}
public string Data { get; set; }
}
</code></pre>
<p>and then you're implementation would be something like:</p>
<pre><code>var myData = new MyData<MyString, string>(new MyString("new string"));
// Could be MyString, MyInt, ...
myData.Data.SomeMethod();
</code></pre>
<p>it's a little more work but you get the functionality you were going for.</p>
<p><strong>UPDATE:</strong>
remove SomeMethod from your interface and just do this</p>
<pre><code>SomeMethod(myData.Data.Data);
</code></pre>
|
GWT: Capturing URL parameters in GET request <p>I need to build a GWT application that will be called by an external application with specific URL parameters. </p>
<p>For example: </p>
<p><a href="http://www.somehost.com/com.app.client.Order.html?orderId=99999">http://www.somehost.com/com.app.client.Order.html?orderId=99999</a>.</p>
<p>How do I capture the orderId parameter inside the GWT application? </p>
| <p>Try,</p>
<pre><code>string value = com.google.gwt.user.client.Window.Location.getParameter("orderId");
// parse the value to int
</code></pre>
<p>P.S. GWT can invoke native javascript which means if the stuff javascript can do, GWT can do it too.
e.g. in GWT, you can write</p>
<pre><code>public static native void alert(String msg)
/*-{
$wnd.alert("Hey I am javascript");
}-*/;
</code></pre>
<p>In this case, you can even use existing javascript lib to extract param's value in the querystring.</p>
|
Making sure OnPropertyChanged() is called on UI thread in MVVM WPF app <p>In a WPF app that I'm writing using the MVVM pattern, I have a background process that doing it's thing, but need to get status updates from it out to the UI.</p>
<p>I'm using the MVVM pattern, so my ViewModel knows virtually nothing of the view (UI) that is presenting the model to the user.</p>
<p>Say I have the following method in my ViewModel:</p>
<pre><code>public void backgroundWorker_ReportProgress(object sender, ReportProgressArgs e)
{
this.Messages.Add(e.Message);
OnPropertyChanged("Messages");
}
</code></pre>
<p>In my view, I have a ListBox bound to the Messages property (a <code>List<string></code>) of the ViewModel. <code>OnPropertyChanged</code> fulfills the role of the <code>INotifyPropertyChanged</code> interface by calling a <code>PropertyChangedEventHandler</code>.</p>
<p>I need to ensure that <code>OnPropertyChanged</code> is called on the UI thread - how do I do this? I've tried the following:</p>
<pre><code>public Dispatcher Dispatcher { get; set; }
public MyViewModel()
{
this.Dispatcher = Dispatcher.CurrentDispatcher;
}
</code></pre>
<p>Then adding the following to the <code>OnPropertyChanged</code> method:</p>
<pre><code>if (this.Dispatcher != Dispatcher.CurrentDispatcher)
{
this.Dispatcher.Invoke(DispatcherPriority.Normal, new ThreadStart(delegate
{
OnPropertyChanged(propertyName);
}));
return;
}
</code></pre>
<p>but this did not work. Any ideas?</p>
| <p>WPF automatically marshals property changes to the UI thread. However, it does not marshal collection changes, so I suspect your adding a message is causing the failure.</p>
<p>You can marshal the add manually yourself (see example below), or use something like <a href="http://kentb.blogspot.com/2008/01/cross-thread-collection-binding-in-wpf.html">this technique</a> I blogged about a while back.</p>
<p>Manually marshalling:</p>
<pre><code>public void backgroundWorker_ReportProgress(object sender, ReportProgressArgs e)
{
Dispatcher.Invoke(new Action<string>(AddMessage), e.Message);
OnPropertyChanged("Messages");
}
private void AddMessage(string message)
{
Dispatcher.VerifyAccess();
Messages.Add(message);
}
</code></pre>
|
Network performance measurement in asp.net 2.0 via HttpHandlers and HttpModules strangeness <p>We have a performance measurement module that relies on HttpModule and HttpHandlers and works like this:</p>
<ol>
<li>Request comes in to server for a page.</li>
<li>HttpModule_Begin writes start time in the cookie.</li>
<li>HttpModule_End writes end time in the cookie.</li>
<li>On client, when page load is finished, fire off a special request via AJAX
that is handled by HttpHandler_ProcessRequest</li>
<li>In HttpHandler_ProcessRequest subtract DateTime.Now from end time written by the previous HttpModule_End (which is stored in the cookie) and store it in the database.
One thing I forgot to mention: all data is shared via a cookie, so the HttpHandler, just pulls the data from the cookie without any session id's, etc...
All participants are in the same time zone.</li>
</ol>
<p>This process works fine for most cases, but there are some instances that report network time in excess of an hour!
This indicates a very large passage of time between the the writing of end time and firing off the AJAX request or a large passage of time between firing off AJAX request and the time it gets to the app server.
I am trying to figure what could be causing this issues in the wild. Why does the operation not simply time out?</p>
| <p>Extend your troubleshooting: append values to the IIS log (<a href="http://msdn.microsoft.com/en-us/library/system.web.httpresponse.appendtolog.aspx" rel="nofollow">HttpContext.Current.Response.AppendToLog(string)</a>).</p>
<p>The IIS log will show your entries and you can determine when those requests were actually recorded. You can append whatever you want and it shows up in the query field of the log (assuming you're using W3C format.)</p>
<p>If you're experiencing delays in requests, as the evidence suggests, you can verify it.
This will give you the IIS log as a comparative source against the recorded values in cookies. </p>
|
Powerful audio lib <p>Can you recommend a powerful audio lib?</p>
<p>I need it to timestrech & pitchshift independently, as well as give me full access to the raw audio data and let me stream bytes into its pipeline.</p>
<p>Other effects like eq, filtering, distortion are a plus.</p>
<p>Needs to be accessible from C++ / Linux.</p>
<p>Maybe gstreamer, xine or mplayer would work? Or what would you suggest.</p>
| <p>I think <a href="http://www.fmod.org/" rel="nofollow"><strong>FMod</strong></a> is widely recognized as one of the most powerful audio engine available for free until you do something commercial with it, and cross-platform, like in console-mac-pc cross-platform.</p>
<p>Now, <a href="http://connect.creativelabs.com/openal/default.aspx" rel="nofollow"><strong>OpenAL</strong></a> is worth giving a try.</p>
|
NInject: Where do you keep your reference to the Kernel? <p>I'm using NInject on a new web application and there are two things that are unclear to me:</p>
<ol>
<li><p>Don't I need to keep a reference to the Kernel around (Session/App variable) to insure that GC doesn't collect all my instances? For example, if I specify .Using() and then the Kernel object gets collected, aren't all my "singletons" collected as well?</p></li>
<li><p>If I do need keep a reference to a Kernel object around, how do I allow the arguments passed in to WithArguments() to change or is that not possible.</p></li>
</ol>
| <p>It's true that you don't want to pass around the kernel. Typically, in a web app, I store the kernel in a static property in the HttpApplication. If you need a reference to the kernel, you can just expose a dependency (via constructor argument or property) that is of the type IKernel, and Ninject will give you a reference to the kernel that activated the type.</p>
<p>If you use WithArguments() on a binding, they will be used for all activations. If you use IParameters, they will only be used for that activation. (However, if the service you're activating has a re-usable behavior like Singleton, it won't be re-activated even if you pass different IParameters.)</p>
|
Making a .NET Windows application show-up on keystroke <p>My application resides mostly on the system tray on minimize. I'd like the user to be able to hit a keystroke (like ALT+SHIFT etc.) and it shows up on the screen (sort of like Launchy, if you've used it; or the Google search bar).</p>
<p>Anyone knows how to do it?</p>
| <p>You want the SetWindowsHookEx Windows API call. There is some details on using it in this CodeProject article:</p>
<p><a href="http://www.codeproject.com/KB/system/CSLLKeyboard.aspx" rel="nofollow">http://www.codeproject.com/KB/system/CSLLKeyboard.aspx</a></p>
<p>There is also some useful advice about what will and won't work and what tricky issues lurk around SetWindowsHookEx and .NET here:</p>
<p><a href="http://www.pinvoke.net/default.aspx/user32.SetWindowsHookEx" rel="nofollow">http://www.pinvoke.net/default.aspx/user32.SetWindowsHookEx</a></p>
|
as3 Access to undefined property? <p>Can someone help me to find out why I'm getting the error message "Access to undefined property: removeChild(goBack)" on the following snipped?</p>
<p>BTW, this is for flash CS4</p>
<pre><code>function nameOfFunction() {
var goBack:backButton_mc = new backButton_mc();
goBack.x = 10;
goBack.y = 700;
goBack.back_text.text = myXML.*[buildingName].NAME;
goBack.name = "backBtn";
goBack.buttonMode = true;
addChild(goBack);
goBack.addEventListener(MouseEvent.CLICK, anotherFunction);
}
function anotherFunction(e:MouseEvent):void {
removeChild(goBack);
}
</code></pre>
| <p>You are wrong with the scope. (surprise :-D)</p>
<p>The variable goBack is just defined inside of "nameOfFunction", when you try to access this from a another function like "anotherFunction" it will not exists anymore (even if it is on the display list)</p>
<p>There are different possibilities to solve this problem:</p>
<pre><code>function anotherFunction(e:MouseEvent):void {
removeChild(e.currentTarget);
}
</code></pre>
<p>Or the best way would be: promote goBack as a class member of the class holding both functions. (Or if you don't use classes make goBack "global".)</p>
|
What's the best WYSIWYG editor when using the ASP.NET MVC Framework? <p>Was wondering what the best WYSIWYG editor that I can embed in a web-site based on the ASP.NET MVC Framework? Ideally it should be Xhtml compliant and allow users to embed images etc.</p>
<p>The only one I've used before is the <a href="http://www.fckeditor.net/">FCKEditor</a>, how well does this work with the MVC - has anyone tried...?</p>
<p>My main requirements are:</p>
<ul>
<li>Xhtml compliance</li>
<li>Deprecate (as best it can) when Javascript is disabled</li>
<li>Modify the toolbar options</li>
<li>Skinable (at least easily change the look and feel)</li>
<li>Easy to use client side api</li>
<li>Plays nicely with the ASP.NET MVC framework</li>
</ul>
<p><strong>Edit:</strong></p>
<p>As <a href="http://stackoverflow.com/questions/590960/whats-the-best-wysiwyg-editor-when-using-the-asp-net-mvc-framework/591025#591025">Nick</a> said, the <a href="http://www.xstandard.com/">XStandard</a> editor is good, but requires a plug-in...what are your thoughts on requiring a plug-in for web-site functionality?</p>
<p>Thanks,<br />
Kieron</p>
<p><strong>Additional info:</strong></p>
<p>As <a href="http://stackoverflow.com/questions/590960/whats-the-best-wysiwyg-editor-when-using-the-asp-net-mvc-framework/591037#591037">Hippo</a> answered, the TinyMCE edit is ideal - for completness here's there download page:</p>
<p><a href="http://tinymce.moxiecode.com/download.php">http://tinymce.moxiecode.com/download.php</a></p>
<p>There's a download for .NET, JSP, ColdFusion, PHP and a jQuery plug-in too.
Also, there are language packs available.</p>
<p>Been using it for a while now, best editor I've used. Thanks all!</p>
| <p>I really like <a href="http://tinymce.moxiecode.com/">TinyMCE</a> which also should fit your requirements. It is well documented and offers a lot of possibilities to configure.</p>
|
Identify IDisposable objects <p>i have to review a code made by some other person that has some memory leaks. Right now i'm searching the disposable objects to enclause them with the using statement and i would like to know if there is a quick way that tells you all the disposable objects declared in. I mean something like resharper or another visual studio plugin.</p>
<p>thanks.</p>
| <p>I know what you mean. I don't know, but look at FxCop. It might have a rule in there somewhere that checks whether objects implementing IDisposable are not disposed. Just a hunch, mind.</p>
<p><strong>UPDATE</strong>: <a href="http://stackoverflow.com/users/16076/mitch-wheat">Mitch Wheat</a> writes:</p>
<blockquote>
<p>FxCop includes the rule, thats says all types that derive from types that implement IDisposable should implement the Dispose() pattern</p>
</blockquote>
<p>Thanks, Mitch.</p>
|
How do I search XML files on a .NET Windows Mobile Handheld? <p>I have a .NET Windows Mobile 5.0 application that is used for data collection. For purposes of this question let's say it's a survey application with two screens - a survey list screen and a survey detail screen. You click on a survey in the survey list screen to display a survey detail screen with the detail information for the survey you clicked.</p>
<p>When the data for a new survey is saved it is serialized to a XML file in a directory on the handheld. Here's an example of the XML file format:</p>
<pre><code><GDO key=âOrderâ>
<PROP key=âOrderIDâ dataType=âSystem.Stringâ value=ââ/>
<PROP key=âTrackingIDâ dataType=âSystem.Stringâ value=ââ/>
<PROP key=âOrderTypeâ dataType=âSystem.Stringâ value=ââ/>
<GDO key=âCustomerâ>
<PROP key=âCustomerIDâ dataType=âSystem.Stringâ value=ââ/>
<PROP key="CustomerName" dataType="System.String" value=""/>
<PROP key=âAddressâ dataType=âSystem.Stringâ value=ââ/>
<PROP key=âCityâ dataType=âSystem.Stringâ value=ââ/>
<PROP key=âStateâ dataType=âSystem.Stringâ value=ââ/>
<PROP key=âZipâ dataType=âSystem.Int16â value=ââ/>
</GDO>
</GDO>
</code></pre>
<p>I need to be able to search through the all XML files in this directory to build a list of context tags for the survey list screen (using the above example let's say the context tags are OrderID and CustomerName).</p>
<p>I don't have any particular filename naming conventions at this time thought I've decided the filename extension will be .GDO.</p>
<p>I know I could use a database for this type of work but this implementation has to be file-based. Any suggestions? </p>
| <p>There is no difference to how you would do this on the desktop, imho.</p>
<ul>
<li>Iterate through all the files in the directory</li>
<li>read the XML into an XMLDocument</li>
<li>use XMLDocument.SelectNodes and an XPath query to do the search</li>
</ul>
|
Can I add a <br/> and links to a javascript alert? <p>I have the following statement:</p>
<pre><code>btnApply.Attributes.Add("onclick", "alert('Must be a member to Use this Tool')");
</code></pre>
<p>Is there a way to add a new line. I tried, but it showed the in the text. In addition, can I add a link that would close the alert and take the user to another page?</p>
<p>How can I do this with my example?</p>
<p>When I added the \n, the alert doesn't show up.</p>
| <p>You can't use HTML, but you can add line breaks:</p>
<pre><code>alert('line1\nline2');
</code></pre>
<p>If a rich modal popup is really what you want though, you can use <a href="http://docs.jquery.com/UI/Dialog">jQuery's dialog</a> feature and put whatever you want in there.</p>
|
Can I use a decorator to mutate the local scope of a function in Python? <p>Is there any way of writing a decorator such that the following would work?</p>
<pre><code>assert 'z' not in globals()
@my_decorator
def func(x, y):
print z
</code></pre>
<p><hr /></p>
<p>EDIT: moved from anwser</p>
<p>In answer to hop's "why?": syntax sugar / DRY.</p>
<p>It's not about caching, it's about calculating z (and z1, z2, z3, ...) based upon the values of x & y.</p>
<p>I have lots of functions which do related things, and I don't want to do have to write</p>
<pre><code>z1, z2, z3=calculate_from(x, y)
</code></pre>
<p>at the beginning of every single function - I'll get it wrong somewhere. If this were c I'd do this with cpp (if this were lisp, I'd do this with macros ...), but I wanted to see if decorators could do the same thing.</p>
<p>If it helps, I'd almost certainly call the decorator "precalculate_z", and it certainly wouldn't be part of any public API.</p>
<p>I could probably get a similar effect from using the class infrastructure as well, but I wanted to see if it was doable with raw functions.</p>
| <p>Echoing Hop's answer</p>
<ol>
<li>Don't do it.</li>
<li>Seriously, don't do this. Lisp and Ruby are more appropriate languages for writing your own custom syntax. Use one of those. Or find a cleaner way to do this</li>
<li>If you must, you want dynamic scoped variables, not lexically scoped.</li>
</ol>
<p>Python doesn't have dynamically scoped variables, but you can simulate it. Here's an example that simulates it by creating a global binding, but restores the previous value on exit:</p>
<p><a href="http://codepad.org/6vAY8Leh">http://codepad.org/6vAY8Leh</a></p>
<pre><code>def adds_dynamic_z_decorator(f):
def replacement(*arg,**karg):
# create a new 'z' binding in globals, saving previous
if 'z' in globals():
oldZ = (globals()['z'],)
else:
oldZ = None
try:
globals()['z'] = None
#invoke the original function
res = f(*arg, **karg)
finally:
#restore any old bindings
if oldZ:
globals()['z'] = oldZ[0]
else:
del(globals()['z'])
return res
return replacement
@adds_dynamic_z_decorator
def func(x,y):
print z
def other_recurse(x):
global z
print 'x=%s, z=%s' %(x,z)
recurse(x+1)
print 'x=%s, z=%s' %(x,z)
@adds_dynamic_z_decorator
def recurse(x=0):
global z
z = x
if x < 3:
other_recurse(x)
print 'calling func(1,2)'
func(1,2)
print 'calling recurse()'
recurse()
</code></pre>
<p>I make no warranties on the utility or sanity of the above code. Actually, I warrant that it <em>is</em> insane, and you should avoid using it unless you want a flogging from your Python peers.</p>
<p>This code is similar to both eduffy's and John Montgomery's code, but ensures that 'z' is created and properly restored "like" a local variable would be -- for instance, note how 'other_recurse' is able to see the binding for 'z' specified in the body of 'recurse'. </p>
|
mysql explain different results on different servers, same query, same db <p>After much work I finally got a rather complicated query to work very smootly and return results very quickly. </p>
<p>It was running well on both dev and testing, but now testing has slowed considerably.
The explain query which takes 0.06 second on dev and was about the same in testing is now 7 seconds in testing.</p>
<p>The explains are slightly different, and I'm not sure why this would be
The explain from dev</p>
<pre>
-+---------+------------------------------+------+------------------------------
---+
| id | select_type | table | type | possible_keys | key
| key_len | ref | rows | Extra
|
+----+-------------+------------+--------+-------------------------+------------
-+---------+------------------------------+------+------------------------------
---+
| 1 | PRIMARY | | ALL | NULL | NULL
| NULL | NULL | 5 |
|
| 1 | PRIMARY | tickets | ref | biddate_idx | biddate_idx
| 7 | showsdate.bid,showsdate.date | 78 |
|
| 2 | DERIVED | shows | ALL | biddate_idx,latlong_idx | NULL
| NULL | NULL | 3089 | Using temporary; Using fileso
rt |
| 2 | DERIVED | genres | ref | bandid_idx | bandid_idx
| 4 | activehw.shows.bid | 2 | Using index
|
| 2 | DERIVED | artists | eq_ref | bid_idx | bid_idx
| 4 | activehw.genres.bid | 1 | Using where
|
+----+-------------+------------+--------+-------------------------+------------
</pre>
<p>and in the testing</p>
<pre>
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+------------+--------+-------------------------+-------------+---------+------------------------------+--------+----------------------------------------------+
| 1 | PRIMARY | | ALL | NULL | NULL | NULL | NULL | 5 | |
| 1 | PRIMARY | tickets | ref | biddate_idx | biddate_idx | 7 | showsdate.bid,showsdate.date | 78 | |
| 2 | DERIVED | genres | index | bandid_idx | bandid_idx | 139 | NULL | 531281 | Using index; Using temporary; Using filesort |
| 2 | DERIVED | artists | eq_ref | bid_idx | bid_idx | 4 | activeHW.genres.bid | 1 | |
| 2 | DERIVED | shows | eq_ref | biddate_idx,latlong_idx | biddate_idx | 7 | activeHW.artists.bid | 1 | Using where |
+----+-------------+------------+--------+-------------------------+-------------+---------+------------------------------+--------+----------------------------------------------+
5 rows in set (6.99 sec)
</pre>
<p>The order of the tables is different, even though the queries are exactly the same.
Is this what would cause the slowdown? if so, how would I fix it?
The dev is windows, testing is centOs.
both running same version of mysql 5.0, and like I said, testing was running perfectly and I haven't made any structural changes to the database. </p>
<p>I ran mysqlcheck and all tables came back ok. </p>
| <p>I would try regenerating statistics and rebuilding the indexes for all the tables and see if that fixes your problem - it's likely that is why the plans would be different.</p>
<p>There are lots of other things it could be (memory, disk, os differences, other loads, etc) but I'm assuming those probably aren't the issue since you mentioned that it ran fine before.</p>
|
How can I automate Winforms in .NET? <p>I want to get the ControlName of .NET properties in VB6 code, just like described in <a href="http://msdn.microsoft.com/en-us/library/ms996405.aspx" rel="nofollow">this article</a>. But unfortunately, it doesn't work for me. I always got 0 for bufferMem.</p>
<pre><code> bufferMem = VirtualAllocEx(processHandle, 0, size,
MEM_RESERVE Or MEM_COMMIT, PAGE_READWRITE)
If bufferMem = 0 Then
Error Err, "VirtualAllocEx API Failed"
End If
</code></pre>
<p>What am I doing wrong?</p>
| <p>Do you set the size beforehand? </p>
<pre><code>size = 65536
</code></pre>
|
How can I modify password expiration in Windows using Python? <p>How can I modify the password expiration to "never" on Windows XP for a local user with Python? I have the PyWIN and WMI modules on board but have no solution. I managed to query the current settings via WMI(based on Win32_UserAccount class), but how can modify it?</p>
| <p>If you are running your python script with ActvePython against Active Directory, then you can use something like this:</p>
<pre><code>import win32com.client
ads = win32com.client.Dispatch('ADsNameSpaces')
user = ads.getObject("", "WinNT://DOMAIN/username,user")
user.Getinfo()
user.Put('userAccountControl', 65536 | user.Get('userAccountControl'))
user.Setinfo()
</code></pre>
<p>But if your python is running under unix, you need two things to talk to Active Directory: Kerberos and LDAP. Once you have a SASL(GSSAPI(KRB5)) authenticated LDAP connection to your Active Directory server, then you access the target user's "userAccountControl" attribute. </p>
<p>userAccountControl is an integer attribute, treated as a bit field, on which you must set the DONT EXPIRE PASSWORD bit. See <a href="http://support.microsoft.com/kb/305144" rel="nofollow">this KB article</a> for bit values.</p>
|
Convert SELECT to an update statement <pre><code>SELECT t1.status, t3.guid, t3.objectID
FROM Table1 t1, Table2 t2, Table3 t3
WHERE t2.ID = t3.ID
AND t1.ID = t2.ID
AND t3.Guid IN ('', '', '')
</code></pre>
<p>How can I convert this to an update statement where I set the <code>t1.status = 1</code>?</p>
| <p>I would start by converting it to using joins instead of "classical joining":</p>
<pre><code>select t1.status, t3.guid, t3.objectID
from Table1 t1
inner join Table2 t2 on t2.ID = t1.ID
inner join Table3 t3 on t3.ID = t2.ID
where t3.Guid in ('', '', '')
</code></pre>
<p>Then you can just rip of the select statement and slap an update and set statement on it:</p>
<pre><code>update t1
set status = 1
from Table1 t1
inner join Table2 t2 on t2.ID = t1.ID
inner join Table3 t3 on t3.ID = t2.ID
where t3.Guid in ('', '', '')
</code></pre>
|
Getting the local iPhone number through SDK <p>I am looking for a SDK API to retrieve the device's local phone number<br>
from the SIM card. Is there a way to do it?</p>
| <p>There's no reliable way. You'll find code online that tells you to look up SBFormattedPhoneNumber, and sometimes that works, but not consistently. Mostly it's people who brought their phone number over from another cell carrier. In those cases, you get a phone number, but not one for the current phone, and not one that's guaranteed to be valid for anything at all (it may not even be unique).</p>
<p>I have no basis for saying whether this is a few people or a lot, but it's an undocumented key that's inherently unreliable.</p>
|
How can you programmatically tell the CPython interpreter to enter interactive mode when done? <p>If you invoke the cpython interpreter with the -i option, it will enter the interactive mode upon completing any commands or scripts it has been given to run. Is there a way, within a program to get the interpreter to do this even when it has not been given -i? The obvious use case is in debugging by interactively inspecting the state when an exceptional condition has occurred.</p>
| <p>You want the <a href="http://docs.python.org/library/code.html">code module</a>.</p>
<pre><code>#!/usr/bin/env python
import code
code.interact("Enter Here")
</code></pre>
|
CSS: Cascade just one level <p>Say i have a <table> with a css class defined (<table class="x">) and i want to change the 'color' property of just the first level of <td>, is this possible using css without setting classes on the relevant <td>?</p>
<p>I.e.</p>
<pre><code><table class="x">
<tr>
<td>
xxxx
<table><tr><td>yyy</td><tr></table>
</td>
</tr>
<table>
</code></pre>
<p>I only want the xxxx to change color - so <code>.x td{color:red;}</code> will currently apply to xxxx and yyyy when i only want xxxx targeted, but would rather not give the xxxx td a class name</p>
| <p>Try this:</p>
<pre><code>table.x > tr > td { ... }
</code></pre>
<p>The <code>></code> is the immediate child selector.</p>
|
JTable sorting rows in Java 1.5 <p>Is there a simple way to sort rows in a JTable with Java 1.5 (<code>setAutoCreateRowSorter</code> and <code>TableRowSorter</code> appear to be Java 1.6 features)?</p>
| <p>Sorting in Java 1.5 is only possible via libraries.</p>
<p>E.g. use the JXTable mentioned from Kaarel or VLTable from <a href="http://www.vlsolutions.com/en/documentation/articles/jtable/index.php" rel="nofollow">here</a>.</p>
<p>Another good library is <a href="http://publicobject.com/glazedlists/" rel="nofollow">glazedlists</a></p>
<p>which is also used in the Spring Rich Client project.</p>
<p>There are even ways to use <a href="http://sites.google.com/site/glazedlists/documentation/swingx" rel="nofollow">Glazed Lists with JXTable</a></p>
|
Footertemplate in gridview <p>I am using datatable to fill gridview.</p>
<p>How can i add blank row in datatable to view footertemplate even if i don't have any data ?</p>
<p>I am using asp.net 2005. I am using gridview control to add,edit and modify the data. i put add control at footertemplate. it's working fine but i face one problem that when ever there is no data in the grid then footertemplate is not visible. I want footertemplate will be visible all the time so that user can add data even though there is no data available.</p>
<p>Can any body help me out...</p>
<p>Thanks</p>
| <p>I ran into this as well. If I remember correctly, there is no way to actually fix it. I worked around the issue by creating an empty data template that had the controls I needed to be able to add the data.</p>
|
How to disable file input text box in IE? <p>Is it possible to prevent a user from typing in a file input text box in IE? The reason I ask is that if a user enters text that does not look like a file system path (eg. doesn't start with something like c:...) then when the user clicks the submit button nothing will happen.</p>
<p>I would either like to not allow the user to type in the box or have the form submit as normal.</p>
<p>I have found that the same question was asked here with no answer:
<a href="http://www.webmasterworld.com/html/3290988.htm">http://www.webmasterworld.com/html/3290988.htm</a></p>
<p>And this person came up with a hack which I can use if there is no other suitable answer:
<a href="http://www.shauninman.com/archive/2007/09/10/styling_file_inputs_with_css_and_the_dom">http://www.shauninman.com/archive/2007/09/10/styling_file_inputs_with_css_and_the_dom</a></p>
<p>EDIT: To clarify - if the user types "not a file path" in the text box next to the "Browse" button and clicks submit, in IE nothing will happen. The form will not submit - IE does not allow a form to be submitted when a <input type="file"> box does not have a real file path.</p>
| <p>How about this one? You can't type, or right click and paste.</p>
<pre><code><input type="file" name="file" onKeyDown="this.blur()" onContextMenu="return false;">
</code></pre>
|
How do I unit test my asp.net-mvc controller's OnActionExecuting method? <p>I've overridden my controller's OnActionExecuting method to set some internal state based on the executing filterContext. How do I test this? The method itself is protected so I assume I'll have to go higher up in the call stack. </p>
<p>What code do I need to test this? </p>
<p>I'm using mvc RC 1.</p>
<p>Edit: I'm also using nunit.</p>
<p>Thanks</p>
| <p>You need to add and use a Private Accessor. Right click in your controller class and choose <code>Create Private Accessors</code> from the menu and add them to your test project. Once in your test project, create your controller, then create an accessor for it. The method should be available on the accessor. Here's a sample test from my own code:</p>
<pre><code>/// <summary>
///A test for OnActionExecuting
///</summary>
[TestMethod()]
[ExpectedException( typeof( InvalidOperationException ) )]
public void OnActionExecutingWindowsIdentityTest()
{
var identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal( identity );
var httpContext = MockRepository.GenerateStub<HttpContextBase>();
httpContext.User = principal;
var actionDescriptor = MockRepository.GenerateStub<ActionDescriptor>();
RouteData routeData = new RouteData();
BaseController controller = new BaseController();
BaseController_Accessor accessor = new BaseController_Accessor( new PrivateObject( controller ) );
ControllerContext controllerContext = MockRepository.GenerateStub<ControllerContext>( httpContext, routeData, controller );
ActionExecutingContext filterContext = new ActionExecutingContext( controllerContext, actionDescriptor, new Dictionary<string, object>() );
accessor.OnActionExecuting( filterContext );
}
</code></pre>
<p><strong>EDIT</strong>: If you aren't using MSTest for your unit tests, you may have to generate the accessors by hand. Essentially, you make a wrapper class that exposes the private/protected methods of the class under test via equivalent public methods, pass an instance of the class under test to the wrapper, and then use reflection from the wrapper class to invoke the private/protected method on the class under test.</p>
<pre><code> public class MyClass
{
protected void DoSomething( int num )
{
}
}
public class MyClass_accessor
{
private MyClass privateObj;
public MyClass_accessor( MyClass obj )
{
this.privateObj = obj;
}
public void DoSomething( int num )
{
MethodInfo info = privateObj.GetType()
.GetMethod("DoSomething",
BindingFlags.NonPublic
| BindingFlags.Instance );
info.Invoke(obj,new object[] { num });
}
}
</code></pre>
|
Stream (.NET) handling best-practices <p>The question is entitled with the word "Stream" because the question below is a concrete example of a more generic doubt I have about Streams:</p>
<p>I have a problem that accepts two solutions and I want to know the best one:</p>
<ol>
<li>I download a file, save it to disk (2 min), read it and write the contents to the DB (+ 2 min).</li>
<li>I download a file and write the contents directly to the DB (3 min).</li>
</ol>
<p>If the write to DB fails I'll have to download again in the second case, but not in the first case.</p>
<p>Which is best? Which would you use?</p>
| <p>Unless the increased latency is really killing you, I'd usually go for Option 1 unless there's a good reason you don't want the data on the file system (e.g. concerns about security, capacity, ...).</p>
<p>Or maybe <a href="http://stackoverflow.com/questions/591760/stream-net-handling-best-practices/591814#591814">Option 3 as suggested by Max Schmeling</a>, save to the filesystem at the same time as writing to the database. </p>
<p>Disk space is cheap, and it's often useful to have a backup of downloaded data (e.g. to test changes to your database writing code, as evidence of the contents of data downloaded, ...).</p>
|
.NET Membership <p>Hi I am trying out the membership features for .NET and I am using the ASP.NET Web application Administration Tool. My question is where is the user data being stored? I checked my databases and I cannot find it anywhere. I also tried to look for any information within Providers in the admin tool but I still could not locate a path. Can someone help me out? Thanks.</p>
<p>[EDIT]
Nothing is in the App_Data folder.</p>
<p>Also I was wondering when I right click App_Data and try to add a database, there is no option to do so. (Add New Item).</p>
| <p>I think, it would create a database by name aspnet by default.</p>
<p>Check it :)</p>
|
Triggering haslayout in IE 6, what's the side effect of using * html div { height: 1%; } <p>For a while, I've been putting * html div { zoom: 1; } in my base stylesheet, and it has worked great. However, I now run into situations where there're elements that are absolute positioned that are losing their heights and widths in IE 6 cuz of this. So I'm thinking of putting * html div { height: 1%; } instead, but what are the side effects?</p>
<p><strong>Update:</strong></p>
<p>Thanks for all your responses. The answer is most probably no side effects as all of you said.</p>
<p>I will however have to disagree with all your recommendations (at this given moment) about how/when to trigger haslayout. I see haslayout a desirable behaviour and should therefore be a default behaviour in IE6 (& 7).</p>
<p>It's been mentioned that it's unlikely there would be any side effects, for the exact reason, why not make it a default behaviour and only turn it off when an undesirable behaviour (if ever) occurs.</p>
<p>One can do this by specifying {zoom: auto;} or {height:auto;} on that specific element depending on how it was defined in the base stylesheet.</p>
<p>I will have to give the answer to the first person that said "no side effects" since everyone's answer is the same, while some went out of scope. Thanks again!</p>
| <p>This is known as <a href="http://www.communitymx.com/content/article.cfm?page=2&cid=c37E0" rel="nofollow">The Holly Hack</a>. As far as I know, there isn't a side effect, especially if you <code>* html</code> it for IE6 directly. I agree with the other posters that placing it on the <code><div></code> tag may not be the wisest choice - I'd target the individual elements that are causing grief.</p>
|
resume/suspend enery star linux from command line <p>I have an ssh connection to a linux machine which is hibernated after some non-activity time.</p>
<p>I want to make it resume, how do I do that?
(writing to /dev/mouse to simulate mouse movement didn't do the trick)</p>
| <p>A machine that is hibernating cannot come out of sleep without pressing the power button, or sending a magic packet if the ethernet adaptor has Wake On Lan (WOL) capability and the motherboard supports that. WOL packets can only be generated on the local network, not remotely from other networks.</p>
|
Huge main.cs file <p>I am new to C# (coming from Delphi) and find my main.cs file becoming quite large. In Delphi I can create classes in a .pas file and use it from my main application file. I simply add the uses (filename) keyword.</p>
<p>My question is how do I do something similar in C#? Example:</p>
<p>Delphi:</p>
<pre><code>Button1.Visible = False;
</code></pre>
<p>I can refer to the buttons properties in another unit by adding a reference to the main unit:</p>
<pre><code>frmMain.Button.Visible = True;
</code></pre>
<p>In C# I would like to move this code to another .cs file and call it from my main form. It does not work.</p>
<pre><code>private void manageMainMenuButtons()
{
if (rtbSharedSARP.Text == "")
{
utmToolBar.Tools["First"].SharedProps.Enabled = false;
utmToolBar.Tools["Previous"].SharedProps.Enabled = false;
utmToolBar.Tools["Next"].SharedProps.Enabled = false;
utmToolBar.Tools["Last"].SharedProps.Enabled = false;
}
else
{
utmToolBar.Tools["First"].SharedProps.Enabled = true;
utmToolBar.Tools["Previous"].SharedProps.Enabled = true;
utmToolBar.Tools["Next"].SharedProps.Enabled = true;
utmToolBar.Tools["Last"].SharedProps.Enabled = true;
}
}
</code></pre>
<p>Not the best example, but I hope someone can help me.</p>
| <p>First, you need to make sure you're in the same namespace:</p>
<pre><code>namespace mynamesspace {
</code></pre>
<p>Next, if your class members are declared privately, you need to indicate you're working on that class:</p>
<pre><code>public partial class frmMyForm : Form {
</code></pre>
<p>Note though, that this is extending the original class. You may just need to specify the namespace, if you're accessing public members (which is a good way to go about things).</p>
|
SQL Express remote access <p>Is there any way to install SQL Express 2005 silently while configuring to allow remote access, or must the configuration be done with the SQL Server Management Studio UI?</p>
| <p>After the SQL Service is installed log into the database and run the following and then restart the SQL Service.</p>
<pre><code>exec sp_configure 'remote access', 1
reconfigure
</code></pre>
<p>This will allow remote access to the service. If you are installing a named instance you'll need to ensure that the SQL Browser service is running and set to automatic.</p>
|
static vs extern "C"/"C++" <p>What is the difference between a static member function and an extern "C" linkage function ? For instance, when using "makecontext" in C++, I need to pass a pointer to function. Google recommends using extern "C" linkage for it, because "makecontext" is C. But I found out that using static works as well. Am I just lucky or...</p>
<pre><code>class X {
public:
static void proxy(int i) {}
}
makecontext(..., (void (*)(void)) X::proxy, ...);
</code></pre>
<p>vs</p>
<pre><code>extern "C" void proxy(int i) {}
makecontext(..., (void (*)(void)) proxy, ...);
</code></pre>
<p>EDIT: I am sorry, but I'm still not convinced... Can you show a compiler or architecture where the static member version does not work (and it's not a bug in the compiler) ?</p>
| <p>Yes, you are just lucky :) The extern "C" is one language linkage for the C language that every C++ compiler has to support, beside extern "C++" which is the default. Compilers may supports other language linkages. GCC for example supports extern "Java" which allows interfacing with java code (though that's quite cumbersome). </p>
<p>extern "C" tells the compiler that your function is callable by C code. That can, but not must, include the appropriate calling convention and the appropriate C language name mangling (sometimes called "decoration") among other things depending on the implementation. If you have a static member function, the calling convention for it is the one of your C++ compiler. Often they are the same as for the C compiler of that platform - so i said you are just lucky. If you have a C API and you pass a function pointer, better always put one to a function declared with extern "C" like</p>
<pre><code>extern "C" void foo() { ... }
</code></pre>
<p>Even though the function pointer type does not contain the linkage specification but rather looks like</p>
<pre><code>void(*)(void)
</code></pre>
<p>The linkage is an integral part of the type - you just can't express it directly without a typedef:</p>
<pre><code>extern "C" typedef void(*extern_c_funptr_t)();
</code></pre>
<p>The Comeau C++ compiler, in strict mode, will emit an error for example if you try to assign the address of the extern "C" function of above to a <code>(void(*)())</code>, beause this is a pointer to a function with C++ linkage.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.