question_id
int64
4
6.31M
answer_id
int64
7
6.31M
title
stringlengths
9
150
question_body
stringlengths
0
28.8k
answer_body
stringlengths
60
27.2k
question_text
stringlengths
40
28.9k
combined_text
stringlengths
124
39.6k
tags
listlengths
1
6
question_score
int64
0
26.3k
answer_score
int64
0
28.8k
view_count
int64
15
14M
answer_count
int64
0
182
favorite_count
int64
0
32
question_creation_date
stringdate
2008-07-31 21:42:52
2011-06-10 18:12:18
answer_creation_date
stringdate
2008-07-31 22:17:57
2011-06-10 18:14:17
46,585
46,614
When do you use POST and when do you use GET?
From what I can gather, there are three categories: Never use GET and use POST Never use POST and use GET It doesn't matter which one you use. Am I correct in assuming those three cases? If so, what are some examples from each case?
Use POST for destructive actions such as creation (I'm aware of the irony), editing, and deletion, because you can't hit a POST action in the address bar of your browser. Use GET when it's safe to allow a person to call an action. So a URL like: http://myblog.org/admin/posts/delete/357 Should bring you to a confirmation page, rather than simply deleting the item. It's far easier to avoid accidents this way. POST is also more secure than GET, because you aren't sticking information into a URL. And so using GET as the method for an HTML form that collects a password or other sensitive information is not the best idea. One final note: POST can transmit a larger amount of information than GET. 'POST' has no size restrictions for transmitted data, whilst 'GET' is limited to 2048 characters.
When do you use POST and when do you use GET? From what I can gather, there are three categories: Never use GET and use POST Never use POST and use GET It doesn't matter which one you use. Am I correct in assuming those three cases? If so, what are some examples from each case?
TITLE: When do you use POST and when do you use GET? QUESTION: From what I can gather, there are three categories: Never use GET and use POST Never use POST and use GET It doesn't matter which one you use. Am I correct in assuming those three cases? If so, what are some examples from each case? ANSWER: Use POST for destructive actions such as creation (I'm aware of the irony), editing, and deletion, because you can't hit a POST action in the address bar of your browser. Use GET when it's safe to allow a person to call an action. So a URL like: http://myblog.org/admin/posts/delete/357 Should bring you to a confirmation page, rather than simply deleting the item. It's far easier to avoid accidents this way. POST is also more secure than GET, because you aren't sticking information into a URL. And so using GET as the method for an HTML form that collects a password or other sensitive information is not the best idea. One final note: POST can transmit a larger amount of information than GET. 'POST' has no size restrictions for transmitted data, whilst 'GET' is limited to 2048 characters.
[ "http-post", "http-get" ]
410
450
252,918
27
0
2008-09-05T19:05:12.060000
2008-09-05T19:12:17.473000
46,586
52,307
GOTO still considered harmful?
Everyone is aware of Dijkstra's Letters to the editor: go to statement considered harmful (also here.html transcript and here.pdf) and there has been a formidable push since that time to eschew the goto statement whenever possible. While it's possible to use goto to produce unmaintainable, sprawling code, it nevertheless remains in modern programming languages. Even the advanced continuation control structure in Scheme can be described as a sophisticated goto. What circumstances warrant the use of goto? When is it best to avoid? As a follow-up question: C provides a pair of functions, setjmp() and longjmp(), that provide the ability to goto not just within the current stack frame but within any of the calling frames. Should these be considered as dangerous as goto? More dangerous? Dijkstra himself regretted that title, for which he was not responsible. At the end of EWD1308 (also here.pdf) he wrote: Finally a short story for the record. In 1968, the Communications of the ACM published a text of mine under the title " The goto statement considered harmful ", which in later years would be most frequently referenced, regrettably, however, often by authors who had seen no more of it than its title, which became a cornerstone of my fame by becoming a template: we would see all sorts of articles under the title "X considered harmful" for almost any X, including one titled "Dijkstra considered harmful". But what had happened? I had submitted a paper under the title " A case against the goto statement ", which, in order to speed up its publication, the editor had changed into a "letter to the Editor", and in the process he had given it a new title of his own invention! The editor was Niklaus Wirth. A well thought out classic paper about this topic, to be matched to that of Dijkstra, is Structured Programming with go to Statements, by Donald E. Knuth. Reading both helps to reestablish context and a non-dogmatic understanding of the subject. In this paper, Dijkstra's opinion on this case is reported and is even more strong: Donald E. Knuth: I believe that by presenting such a view I am not in fact disagreeing sharply with Dijkstra's ideas, since he recently wrote the following: "Please don't fall into the trap of believing that I am terribly dogmatical about [the go to statement]. I have the uncomfortable feeling that others are making a religion out of it, as if the conceptual problems of programming could be solved by a single trick, by a simple form of coding discipline! "
The following statements are generalizations; while it is always possible to plead exception, it usually (in my experience and humble opinion) isn't worth the risks. Unconstrained use of memory addresses (either GOTO or raw pointers) provides too many opportunities to make easily avoidable mistakes. The more ways there are to arrive at a particular "location" in the code, the less confident one can be about what the state of the system is at that point. (See below.) Structured programming IMHO is less about "avoiding GOTOs" and more about making the structure of the code match the structure of the data. For example, a repeating data structure (e.g. array, sequential file, etc.) is naturally processed by a repeated unit of code. Having built-in structures (e.g. while, for, until, for-each, etc.) allows the programmer to avoid the tedium of repeating the same cliched code patterns. Even if GOTO is low-level implementation detail (not always the case!) it's below the level that the programmer should be thinking. How many programmers balance their personal checkbooks in raw binary? How many programmers worry about which sector on the disk contains a particular record, instead of just providing a key to a database engine (and how many ways could things go wrong if we really wrote all of our programs in terms of physical disk sectors)? Footnotes to the above: Regarding point 2, consider the following code: a = b + 1 /* do something with a */ At the "do something" point in the code, we can state with high confidence that a is greater than b. (Yes, I'm ignoring the possibility of untrapped integer overflow. Let's not bog down a simple example.) On the other hand, if the code had read this way:... goto 10... a = b + 1 10: /* do something with a */... goto 10... The multiplicity of ways to get to label 10 means that we have to work much harder to be confident about the relationships between a and b at that point. (In fact, in the general case it's undecideable!) Regarding point 4, the whole notion of "going someplace" in the code is just a metaphor. Nothing is really "going" anywhere inside the CPU except electrons and photons (for the waste heat). Sometimes we give up a metaphor for another, more useful, one. I recall encountering (a few decades ago!) a language where if (some condition) { action-1 } else { action-2 } was implemented on a virtual machine by compiling action-1 and action-2 as out-of-line parameterless routines, then using a single two-argument VM opcode which used the boolean value of the condition to invoke one or the other. The concept was simply "choose what to invoke now" rather than "go here or go there". Again, just a change of metaphor.
GOTO still considered harmful? Everyone is aware of Dijkstra's Letters to the editor: go to statement considered harmful (also here.html transcript and here.pdf) and there has been a formidable push since that time to eschew the goto statement whenever possible. While it's possible to use goto to produce unmaintainable, sprawling code, it nevertheless remains in modern programming languages. Even the advanced continuation control structure in Scheme can be described as a sophisticated goto. What circumstances warrant the use of goto? When is it best to avoid? As a follow-up question: C provides a pair of functions, setjmp() and longjmp(), that provide the ability to goto not just within the current stack frame but within any of the calling frames. Should these be considered as dangerous as goto? More dangerous? Dijkstra himself regretted that title, for which he was not responsible. At the end of EWD1308 (also here.pdf) he wrote: Finally a short story for the record. In 1968, the Communications of the ACM published a text of mine under the title " The goto statement considered harmful ", which in later years would be most frequently referenced, regrettably, however, often by authors who had seen no more of it than its title, which became a cornerstone of my fame by becoming a template: we would see all sorts of articles under the title "X considered harmful" for almost any X, including one titled "Dijkstra considered harmful". But what had happened? I had submitted a paper under the title " A case against the goto statement ", which, in order to speed up its publication, the editor had changed into a "letter to the Editor", and in the process he had given it a new title of his own invention! The editor was Niklaus Wirth. A well thought out classic paper about this topic, to be matched to that of Dijkstra, is Structured Programming with go to Statements, by Donald E. Knuth. Reading both helps to reestablish context and a non-dogmatic understanding of the subject. In this paper, Dijkstra's opinion on this case is reported and is even more strong: Donald E. Knuth: I believe that by presenting such a view I am not in fact disagreeing sharply with Dijkstra's ideas, since he recently wrote the following: "Please don't fall into the trap of believing that I am terribly dogmatical about [the go to statement]. I have the uncomfortable feeling that others are making a religion out of it, as if the conceptual problems of programming could be solved by a single trick, by a simple form of coding discipline! "
TITLE: GOTO still considered harmful? QUESTION: Everyone is aware of Dijkstra's Letters to the editor: go to statement considered harmful (also here.html transcript and here.pdf) and there has been a formidable push since that time to eschew the goto statement whenever possible. While it's possible to use goto to produce unmaintainable, sprawling code, it nevertheless remains in modern programming languages. Even the advanced continuation control structure in Scheme can be described as a sophisticated goto. What circumstances warrant the use of goto? When is it best to avoid? As a follow-up question: C provides a pair of functions, setjmp() and longjmp(), that provide the ability to goto not just within the current stack frame but within any of the calling frames. Should these be considered as dangerous as goto? More dangerous? Dijkstra himself regretted that title, for which he was not responsible. At the end of EWD1308 (also here.pdf) he wrote: Finally a short story for the record. In 1968, the Communications of the ACM published a text of mine under the title " The goto statement considered harmful ", which in later years would be most frequently referenced, regrettably, however, often by authors who had seen no more of it than its title, which became a cornerstone of my fame by becoming a template: we would see all sorts of articles under the title "X considered harmful" for almost any X, including one titled "Dijkstra considered harmful". But what had happened? I had submitted a paper under the title " A case against the goto statement ", which, in order to speed up its publication, the editor had changed into a "letter to the Editor", and in the process he had given it a new title of his own invention! The editor was Niklaus Wirth. A well thought out classic paper about this topic, to be matched to that of Dijkstra, is Structured Programming with go to Statements, by Donald E. Knuth. Reading both helps to reestablish context and a non-dogmatic understanding of the subject. In this paper, Dijkstra's opinion on this case is reported and is even more strong: Donald E. Knuth: I believe that by presenting such a view I am not in fact disagreeing sharply with Dijkstra's ideas, since he recently wrote the following: "Please don't fall into the trap of believing that I am terribly dogmatical about [the go to statement]. I have the uncomfortable feeling that others are making a religion out of it, as if the conceptual problems of programming could be solved by a single trick, by a simple form of coding discipline! " ANSWER: The following statements are generalizations; while it is always possible to plead exception, it usually (in my experience and humble opinion) isn't worth the risks. Unconstrained use of memory addresses (either GOTO or raw pointers) provides too many opportunities to make easily avoidable mistakes. The more ways there are to arrive at a particular "location" in the code, the less confident one can be about what the state of the system is at that point. (See below.) Structured programming IMHO is less about "avoiding GOTOs" and more about making the structure of the code match the structure of the data. For example, a repeating data structure (e.g. array, sequential file, etc.) is naturally processed by a repeated unit of code. Having built-in structures (e.g. while, for, until, for-each, etc.) allows the programmer to avoid the tedium of repeating the same cliched code patterns. Even if GOTO is low-level implementation detail (not always the case!) it's below the level that the programmer should be thinking. How many programmers balance their personal checkbooks in raw binary? How many programmers worry about which sector on the disk contains a particular record, instead of just providing a key to a database engine (and how many ways could things go wrong if we really wrote all of our programs in terms of physical disk sectors)? Footnotes to the above: Regarding point 2, consider the following code: a = b + 1 /* do something with a */ At the "do something" point in the code, we can state with high confidence that a is greater than b. (Yes, I'm ignoring the possibility of untrapped integer overflow. Let's not bog down a simple example.) On the other hand, if the code had read this way:... goto 10... a = b + 1 10: /* do something with a */... goto 10... The multiplicity of ways to get to label 10 means that we have to work much harder to be confident about the relationships between a and b at that point. (In fact, in the general case it's undecideable!) Regarding point 4, the whole notion of "going someplace" in the code is just a metaphor. Nothing is really "going" anywhere inside the CPU except electrons and photons (for the waste heat). Sometimes we give up a metaphor for another, more useful, one. I recall encountering (a few decades ago!) a language where if (some condition) { action-1 } else { action-2 } was implemented on a virtual machine by compiling action-1 and action-2 as out-of-line parameterless routines, then using a single two-argument VM opcode which used the boolean value of the condition to invoke one or the other. The concept was simply "choose what to invoke now" rather than "go here or go there". Again, just a change of metaphor.
[ "language-agnostic", "goto" ]
316
202
102,703
49
0
2008-09-05T19:05:18.877000
2008-09-09T16:34:07.100000
46,621
46,627
DotNetNuke using PNG images with Transparency
I have a DotNetNuke site where my main logo is a PNG file using transparency. I tried GIF but the quality wasn't good enough. Anyways it worked great on IE7 but I just saw my site in IE6 and noticed that the transparency isn't working with my logo. Does anyone know of a quick way to fix this in a DotNetNuke portal?
I don't know that it's a DotNetNuke issue as much as it is IE6. Anyways, here's a site that shows you how to work around IE6's png issues. Hope it helps. http://24ways.org/2007/supersleight-transparent-png-in-ie6
DotNetNuke using PNG images with Transparency I have a DotNetNuke site where my main logo is a PNG file using transparency. I tried GIF but the quality wasn't good enough. Anyways it worked great on IE7 but I just saw my site in IE6 and noticed that the transparency isn't working with my logo. Does anyone know of a quick way to fix this in a DotNetNuke portal?
TITLE: DotNetNuke using PNG images with Transparency QUESTION: I have a DotNetNuke site where my main logo is a PNG file using transparency. I tried GIF but the quality wasn't good enough. Anyways it worked great on IE7 but I just saw my site in IE6 and noticed that the transparency isn't working with my logo. Does anyone know of a quick way to fix this in a DotNetNuke portal? ANSWER: I don't know that it's a DotNetNuke issue as much as it is IE6. Anyways, here's a site that shows you how to work around IE6's png issues. Hope it helps. http://24ways.org/2007/supersleight-transparent-png-in-ie6
[ "internet-explorer-6", "png", "transparency", "dotnetnuke" ]
2
6
1,443
7
0
2008-09-05T19:13:22.370000
2008-09-05T19:14:54.127000
46,636
46,640
Copying from network share using BAT
What's the best way to copy a file from a network share to the local file system using a Windows batch file? Normally, I would use "net use *" but using this approach how can I get the drive letter?
Can you just use the full UNC path to the file? copy \\myserver\myshare\myfolder\myfile.txt c:\myfiles
Copying from network share using BAT What's the best way to copy a file from a network share to the local file system using a Windows batch file? Normally, I would use "net use *" but using this approach how can I get the drive letter?
TITLE: Copying from network share using BAT QUESTION: What's the best way to copy a file from a network share to the local file system using a Windows batch file? Normally, I would use "net use *" but using this approach how can I get the drive letter? ANSWER: Can you just use the full UNC path to the file? copy \\myserver\myshare\myfolder\myfile.txt c:\myfiles
[ "windows", "batch-file" ]
9
15
20,904
3
0
2008-09-05T19:17:15.153000
2008-09-05T19:18:23.637000
46,642
46,659
Does anyone here have a favorite memory profiling/memory leak tool they like to use for their java webapps?
I'm looking for a good tool to profile a java webapp. I'd like to get performance information and memory usage if possible. Any suggestions?
JProfiler is a really good one. It integrates with all the major IDEs and application servers.
Does anyone here have a favorite memory profiling/memory leak tool they like to use for their java webapps? I'm looking for a good tool to profile a java webapp. I'd like to get performance information and memory usage if possible. Any suggestions?
TITLE: Does anyone here have a favorite memory profiling/memory leak tool they like to use for their java webapps? QUESTION: I'm looking for a good tool to profile a java webapp. I'd like to get performance information and memory usage if possible. Any suggestions? ANSWER: JProfiler is a really good one. It integrates with all the major IDEs and application servers.
[ "java", "profiling", "web-applications" ]
6
7
826
7
0
2008-09-05T19:18:30.297000
2008-09-05T19:20:48.513000
46,644
47,382
Any way to handle Put and Delete verbs in ASP.Net MVC?
just wondering if anyone knows of a truly restful Put/delete implementation asp.net mvc preview 5 preferably.
Check out the mvccontrib project at http://www.mvccontrib.org. In the source code a restful implementation has been added and it is current up to Preview 5. Check out the source code here - http://mvccontrib.googlecode.com/svn/trunk/src/MVCContrib/SimplyRestful
Any way to handle Put and Delete verbs in ASP.Net MVC? just wondering if anyone knows of a truly restful Put/delete implementation asp.net mvc preview 5 preferably.
TITLE: Any way to handle Put and Delete verbs in ASP.Net MVC? QUESTION: just wondering if anyone knows of a truly restful Put/delete implementation asp.net mvc preview 5 preferably. ANSWER: Check out the mvccontrib project at http://www.mvccontrib.org. In the source code a restful implementation has been added and it is current up to Preview 5. Check out the source code here - http://mvccontrib.googlecode.com/svn/trunk/src/MVCContrib/SimplyRestful
[ "asp.net-mvc", "rest", "https" ]
3
2
2,361
6
0
2008-09-05T19:18:34.087000
2008-09-06T10:58:37.323000
46,663
47,452
How can I send an email by Java application using GMail, Yahoo, or Hotmail?
Is it possible to send an email from my Java application using a GMail account? I have configured my company mail server with Java app to send email, but that's not going to cut it when I distribute the application. Answers with any of using Hotmail, Yahoo or GMail are acceptable.
First download the JavaMail API and make sure the relevant jar files are in your classpath. Here's a full working example using GMail. import java.util.*; import javax.mail.*; import javax.mail.internet.*; public class Main { private static String USER_NAME = "*****"; // GMail user name (just the part before "@gmail.com") private static String PASSWORD = "********"; // GMail password private static String RECIPIENT = "lizard.bill@myschool.edu"; public static void main(String[] args) { String from = USER_NAME; String pass = PASSWORD; String[] to = { RECIPIENT }; // list of recipient email addresses String subject = "Java send mail example"; String body = "Welcome to JavaMail!"; sendFromGMail(from, pass, to, subject, body); } private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) { Properties props = System.getProperties(); String host = "smtp.gmail.com"; props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.user", from); props.put("mail.smtp.password", pass); props.put("mail.smtp.port", "587"); props.put("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(props); MimeMessage message = new MimeMessage(session); try { message.setFrom(new InternetAddress(from)); InternetAddress[] toAddress = new InternetAddress[to.length]; // To get the array of addresses for( int i = 0; i < to.length; i++ ) { toAddress[i] = new InternetAddress(to[i]); } for( int i = 0; i < toAddress.length; i++) { message.addRecipient(Message.RecipientType.TO, toAddress[i]); } message.setSubject(subject); message.setText(body); Transport transport = session.getTransport("smtp"); transport.connect(host, from, pass); transport.sendMessage(message, message.getAllRecipients()); transport.close(); } catch (AddressException ae) { ae.printStackTrace(); } catch (MessagingException me) { me.printStackTrace(); } } } Naturally, you'll want to do more in the catch blocks than print the stack trace as I did in the example code above. (Remove the catch blocks to see which method calls from the JavaMail API throw exceptions so you can better see how to properly handle them.) Thanks to @jodonnel and everyone else who answered. I'm giving him a bounty because his answer led me about 95% of the way to a complete answer.
How can I send an email by Java application using GMail, Yahoo, or Hotmail? Is it possible to send an email from my Java application using a GMail account? I have configured my company mail server with Java app to send email, but that's not going to cut it when I distribute the application. Answers with any of using Hotmail, Yahoo or GMail are acceptable.
TITLE: How can I send an email by Java application using GMail, Yahoo, or Hotmail? QUESTION: Is it possible to send an email from my Java application using a GMail account? I have configured my company mail server with Java app to send email, but that's not going to cut it when I distribute the application. Answers with any of using Hotmail, Yahoo or GMail are acceptable. ANSWER: First download the JavaMail API and make sure the relevant jar files are in your classpath. Here's a full working example using GMail. import java.util.*; import javax.mail.*; import javax.mail.internet.*; public class Main { private static String USER_NAME = "*****"; // GMail user name (just the part before "@gmail.com") private static String PASSWORD = "********"; // GMail password private static String RECIPIENT = "lizard.bill@myschool.edu"; public static void main(String[] args) { String from = USER_NAME; String pass = PASSWORD; String[] to = { RECIPIENT }; // list of recipient email addresses String subject = "Java send mail example"; String body = "Welcome to JavaMail!"; sendFromGMail(from, pass, to, subject, body); } private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) { Properties props = System.getProperties(); String host = "smtp.gmail.com"; props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.user", from); props.put("mail.smtp.password", pass); props.put("mail.smtp.port", "587"); props.put("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(props); MimeMessage message = new MimeMessage(session); try { message.setFrom(new InternetAddress(from)); InternetAddress[] toAddress = new InternetAddress[to.length]; // To get the array of addresses for( int i = 0; i < to.length; i++ ) { toAddress[i] = new InternetAddress(to[i]); } for( int i = 0; i < toAddress.length; i++) { message.addRecipient(Message.RecipientType.TO, toAddress[i]); } message.setSubject(subject); message.setText(body); Transport transport = session.getTransport("smtp"); transport.connect(host, from, pass); transport.sendMessage(message, message.getAllRecipients()); transport.close(); } catch (AddressException ae) { ae.printStackTrace(); } catch (MessagingException me) { me.printStackTrace(); } } } Naturally, you'll want to do more in the catch blocks than print the stack trace as I did in the example code above. (Remove the catch blocks to see which method calls from the JavaMail API throw exceptions so you can better see how to properly handle them.) Thanks to @jodonnel and everyone else who answered. I'm giving him a bounty because his answer led me about 95% of the way to a complete answer.
[ "java", "email", "gmail", "jakarta-mail", "mail-server" ]
219
200
267,601
14
0
2008-09-05T19:23:00.303000
2008-09-06T13:19:58.280000
46,677
46,976
Employee Web Usage From Proxy Logs
I need to find/create an application that will create employee web usage reports from HTTP proxy logs. Does anyone know of a good product that will do this? @Joe Liversedge - Good point. I don't have to worry about this, however, as I am the only person in my company with the know-how to pull off an SSH tunnel.
Here's a scenario: What's to stop two employees, let's call them 'Eric' and 'Tim', from running their own little SSH tunnel back home to prevent 'the Man', in this case you, from narc'ing out their use of the Internet. Now you have a useless report. If you're serious about getting real data, you'll want something close to the pipes. But agreed, Splunk would work pretty well, as would an over-long and unmaintainable Perl script or a series of awk s, sort s, uniq -c 's, etc.
Employee Web Usage From Proxy Logs I need to find/create an application that will create employee web usage reports from HTTP proxy logs. Does anyone know of a good product that will do this? @Joe Liversedge - Good point. I don't have to worry about this, however, as I am the only person in my company with the know-how to pull off an SSH tunnel.
TITLE: Employee Web Usage From Proxy Logs QUESTION: I need to find/create an application that will create employee web usage reports from HTTP proxy logs. Does anyone know of a good product that will do this? @Joe Liversedge - Good point. I don't have to worry about this, however, as I am the only person in my company with the know-how to pull off an SSH tunnel. ANSWER: Here's a scenario: What's to stop two employees, let's call them 'Eric' and 'Tim', from running their own little SSH tunnel back home to prevent 'the Man', in this case you, from narc'ing out their use of the Internet. Now you have a useless report. If you're serious about getting real data, you'll want something close to the pipes. But agreed, Splunk would work pretty well, as would an over-long and unmaintainable Perl script or a series of awk s, sort s, uniq -c 's, etc.
[ "reporting" ]
0
4
295
3
0
2008-09-05T19:26:18.483000
2008-09-05T22:00:18.037000
46,692
46,797
Information Management Policy in SharePoint
An obscure puzzle, but it's driving me absolutely nuts: I'm creating a custom Information Management Policy in MOSS. I've implemented IPolicyFeature, and my policy feature happily registers itself by configuring a new SPItemEventReceiver. All new items in my library fire the events as they should, and it all works fine. IPolicyFeature also has a method ProcessListItem, which is supposed to retroactively apply the policy to items that were already in the library (at least, it's supposed to do that for as long as it keeps returning true ). Except it doesn't. It only applies the policy to the first item in the library, and I have absolutely no idea why. It doesn't seem to be throwing an exception, and it really does return true from processing that first item, and I can't think what else to look at. Anyone? Edit: Cory's answer, below, set me on the right track. Something else was indeed failing -- I didn't find out what, since my windbg-fu isn't what it should be, but I suspect it was something like "modifying a collection while it's being iterated over". My code was modifying the SPListItem that's passed into ProcessListItem, and then calling SystemUpdate on it; as soon as I changed the code so that it created its own variable (pointing at the exact same SPListItem) and used that, the problem went away...
There's only a couple of things I can think of to try. First, are you developing on the box where you might be able to use Visual Studio to debug? So just stepping through it. Assuming that's not the case - what I'd do is fire up WinDBG and attach it to the process just before I registered the policy. Turn on first chance exceptions so that it breaks whenever they occur. you can do that by issuing the command "sxe clr" once it is broken in. Here's a little more info about WinDBG: http://blogs.msdn.com/tess/archive/2008/06/05/setting-net-breakpoints-in-windbg-for-applications-that-crash-on-startup.aspx What I'd do is then watch for First Chance exceptions to be thrown, and do a!PrintException to see what is going on. My guess is that there is an exception being thrown somewhere that is causing the app to stop processing the other items. What does the logic look like for your ProcessListItem? Have you tried just doing a return true to make sure it works?
Information Management Policy in SharePoint An obscure puzzle, but it's driving me absolutely nuts: I'm creating a custom Information Management Policy in MOSS. I've implemented IPolicyFeature, and my policy feature happily registers itself by configuring a new SPItemEventReceiver. All new items in my library fire the events as they should, and it all works fine. IPolicyFeature also has a method ProcessListItem, which is supposed to retroactively apply the policy to items that were already in the library (at least, it's supposed to do that for as long as it keeps returning true ). Except it doesn't. It only applies the policy to the first item in the library, and I have absolutely no idea why. It doesn't seem to be throwing an exception, and it really does return true from processing that first item, and I can't think what else to look at. Anyone? Edit: Cory's answer, below, set me on the right track. Something else was indeed failing -- I didn't find out what, since my windbg-fu isn't what it should be, but I suspect it was something like "modifying a collection while it's being iterated over". My code was modifying the SPListItem that's passed into ProcessListItem, and then calling SystemUpdate on it; as soon as I changed the code so that it created its own variable (pointing at the exact same SPListItem) and used that, the problem went away...
TITLE: Information Management Policy in SharePoint QUESTION: An obscure puzzle, but it's driving me absolutely nuts: I'm creating a custom Information Management Policy in MOSS. I've implemented IPolicyFeature, and my policy feature happily registers itself by configuring a new SPItemEventReceiver. All new items in my library fire the events as they should, and it all works fine. IPolicyFeature also has a method ProcessListItem, which is supposed to retroactively apply the policy to items that were already in the library (at least, it's supposed to do that for as long as it keeps returning true ). Except it doesn't. It only applies the policy to the first item in the library, and I have absolutely no idea why. It doesn't seem to be throwing an exception, and it really does return true from processing that first item, and I can't think what else to look at. Anyone? Edit: Cory's answer, below, set me on the right track. Something else was indeed failing -- I didn't find out what, since my windbg-fu isn't what it should be, but I suspect it was something like "modifying a collection while it's being iterated over". My code was modifying the SPListItem that's passed into ProcessListItem, and then calling SystemUpdate on it; as soon as I changed the code so that it created its own variable (pointing at the exact same SPListItem) and used that, the problem went away... ANSWER: There's only a couple of things I can think of to try. First, are you developing on the box where you might be able to use Visual Studio to debug? So just stepping through it. Assuming that's not the case - what I'd do is fire up WinDBG and attach it to the process just before I registered the policy. Turn on first chance exceptions so that it breaks whenever they occur. you can do that by issuing the command "sxe clr" once it is broken in. Here's a little more info about WinDBG: http://blogs.msdn.com/tess/archive/2008/06/05/setting-net-breakpoints-in-windbg-for-applications-that-crash-on-startup.aspx What I'd do is then watch for First Chance exceptions to be thrown, and do a!PrintException to see what is going on. My guess is that there is an exception being thrown somewhere that is causing the app to stop processing the other items. What does the logic look like for your ProcessListItem? Have you tried just doing a return true to make sure it works?
[ "sharepoint", "moss", "information-management" ]
1
1
841
2
0
2008-09-05T19:30:37.367000
2008-09-05T20:11:12.057000
46,693
47,320
.Net 3.5, most secure way to pass string between processes
I'd like to be able to pass a SecureString (a cached passphrase) to a child process in C# (.Net 3.5), but I don't know what the most secure way is to do it. If I were to convert the SecureString back to a regular string and pass it as a command-line argument, for example, then I think the value may be prone to disk paging--which would make the plaintext touch the filesystem and ruin the point of using SecureString. Can the IntPtr for the SecureString be passed instead? Could I use a named pipe without increasing the risk?
In general you should define your threat model before worrying about more exotic attacks. In this case: are you worried that somebody shuts down the computer and does a forensic analysis of the harddrive? Application memory can also be swapped out, so the simple fact that one process has it in memory, makes it potentially possible for it to end in the swap file. What about hibernation? During hibernation the entire content of the memory is written to the harddisk (including the SecureString - and presumably the encryption key!). What if the attacker has access to the system while it's running and can search through the memory of applications? In general client side security is very tricky and unless you have dedicated hardware (like a TPM chip) it is almost impossible to get right. Two solutions would be: If you only need to test for equality between two strings (ie: is this string the same as the one I had earlier), store only a (salted) hash value of it. Make the user re-enter the information when it is needed a second time (not very convenient, but security and convenience are opposed to each other)
.Net 3.5, most secure way to pass string between processes I'd like to be able to pass a SecureString (a cached passphrase) to a child process in C# (.Net 3.5), but I don't know what the most secure way is to do it. If I were to convert the SecureString back to a regular string and pass it as a command-line argument, for example, then I think the value may be prone to disk paging--which would make the plaintext touch the filesystem and ruin the point of using SecureString. Can the IntPtr for the SecureString be passed instead? Could I use a named pipe without increasing the risk?
TITLE: .Net 3.5, most secure way to pass string between processes QUESTION: I'd like to be able to pass a SecureString (a cached passphrase) to a child process in C# (.Net 3.5), but I don't know what the most secure way is to do it. If I were to convert the SecureString back to a regular string and pass it as a command-line argument, for example, then I think the value may be prone to disk paging--which would make the plaintext touch the filesystem and ruin the point of using SecureString. Can the IntPtr for the SecureString be passed instead? Could I use a named pipe without increasing the risk? ANSWER: In general you should define your threat model before worrying about more exotic attacks. In this case: are you worried that somebody shuts down the computer and does a forensic analysis of the harddrive? Application memory can also be swapped out, so the simple fact that one process has it in memory, makes it potentially possible for it to end in the swap file. What about hibernation? During hibernation the entire content of the memory is written to the harddisk (including the SecureString - and presumably the encryption key!). What if the attacker has access to the system while it's running and can search through the memory of applications? In general client side security is very tricky and unless you have dedicated hardware (like a TPM chip) it is almost impossible to get right. Two solutions would be: If you only need to test for equality between two strings (ie: is this string the same as the one I had earlier), store only a (salted) hash value of it. Make the user re-enter the information when it is needed a second time (not very convenient, but security and convenience are opposed to each other)
[ ".net", "security", ".net-3.5", "ipc" ]
4
3
1,648
2
0
2008-09-05T19:30:43.137000
2008-09-06T08:17:42.093000
46,697
46,751
Monitoring GDI calls
Is there a tool that allows one to monitor GDI calls?
Tools like AutomatedQA AQTime can help you diagnose GDI usage. A much simpler, but free tool one can be found here.
Monitoring GDI calls Is there a tool that allows one to monitor GDI calls?
TITLE: Monitoring GDI calls QUESTION: Is there a tool that allows one to monitor GDI calls? ANSWER: Tools like AutomatedQA AQTime can help you diagnose GDI usage. A much simpler, but free tool one can be found here.
[ "windows", "monitoring", "gdi" ]
5
3
1,269
2
0
2008-09-05T19:31:59.983000
2008-09-05T19:52:54.223000
46,704
46,800
Using jQuery, what is the best way to set onClick event listeners for radio buttons?
For the following HTML: One Two Three Four Changing from the following JavaScript code: $(function() { var myForm = document.myForm; var radios = myForm.area; // Loop through radio buttons for (var i=0; i Thanks EDIT: The response I selected answers the question I asked, however I like the answer that uses bind() because it also shows how to distinguish the group of radio buttons
$( function() { $("input:radio").click(radioClicks).filter("[value='S']").attr("checked", "checked"); });
Using jQuery, what is the best way to set onClick event listeners for radio buttons? For the following HTML: One Two Three Four Changing from the following JavaScript code: $(function() { var myForm = document.myForm; var radios = myForm.area; // Loop through radio buttons for (var i=0; i Thanks EDIT: The response I selected answers the question I asked, however I like the answer that uses bind() because it also shows how to distinguish the group of radio buttons
TITLE: Using jQuery, what is the best way to set onClick event listeners for radio buttons? QUESTION: For the following HTML: One Two Three Four Changing from the following JavaScript code: $(function() { var myForm = document.myForm; var radios = myForm.area; // Loop through radio buttons for (var i=0; i Thanks EDIT: The response I selected answers the question I asked, however I like the answer that uses bind() because it also shows how to distinguish the group of radio buttons ANSWER: $( function() { $("input:radio").click(radioClicks).filter("[value='S']").attr("checked", "checked"); });
[ "javascript", "jquery" ]
11
17
34,288
6
0
2008-09-05T19:35:44.157000
2008-09-05T20:12:02.197000
46,709
46,784
Which ORM framework can best handle an MVCC database design?
When designing a database to use MVCC (Multi-Version Concurrency Control), you create tables with either a boolean field like "IsLatest" or an integer "VersionId", and you never do any updates, you only insert new records when things change. MVCC gives you automatic auditing for applications that require a detailed history, and it also relieves pressure on the database with regards to update locks. The cons are that it makes your data size much bigger and slows down selects, due to the extra clause necessary to get the latest version. It also makes foreign keys more complicated. (Note that I'm not talking about the native MVCC support in RDBMSs like SQL Server's snapshot isolation level) This has been discussed in other posts here on Stack Overflow. [todo - links] I am wondering, which of the prevalent entity/ORM frameworks (Linq to Sql, ADO.NET EF, Hibernate, etc) can cleanly support this type of design? This is a major change to the typical ActiveRecord design pattern, so I'm not sure if the majority of tools that are out there could help someone who decides to go this route with their data model. I'm particularly interested in how foreign keys would be handled, because I'm not even sure of the best way to data model them to support MVCC.
I might consider implementing the MVCC tier purely in the DB, using stored procs and views to handle my data operations. Then you could present a reasonable API to any ORM that was capable of mapping to and from stored procs, and you could let the DB deal with the data integrity issues (since it's pretty much build for that). If you went this way, you might want to look at a more pure Mapping solution like IBatis or IBatis.net.
Which ORM framework can best handle an MVCC database design? When designing a database to use MVCC (Multi-Version Concurrency Control), you create tables with either a boolean field like "IsLatest" or an integer "VersionId", and you never do any updates, you only insert new records when things change. MVCC gives you automatic auditing for applications that require a detailed history, and it also relieves pressure on the database with regards to update locks. The cons are that it makes your data size much bigger and slows down selects, due to the extra clause necessary to get the latest version. It also makes foreign keys more complicated. (Note that I'm not talking about the native MVCC support in RDBMSs like SQL Server's snapshot isolation level) This has been discussed in other posts here on Stack Overflow. [todo - links] I am wondering, which of the prevalent entity/ORM frameworks (Linq to Sql, ADO.NET EF, Hibernate, etc) can cleanly support this type of design? This is a major change to the typical ActiveRecord design pattern, so I'm not sure if the majority of tools that are out there could help someone who decides to go this route with their data model. I'm particularly interested in how foreign keys would be handled, because I'm not even sure of the best way to data model them to support MVCC.
TITLE: Which ORM framework can best handle an MVCC database design? QUESTION: When designing a database to use MVCC (Multi-Version Concurrency Control), you create tables with either a boolean field like "IsLatest" or an integer "VersionId", and you never do any updates, you only insert new records when things change. MVCC gives you automatic auditing for applications that require a detailed history, and it also relieves pressure on the database with regards to update locks. The cons are that it makes your data size much bigger and slows down selects, due to the extra clause necessary to get the latest version. It also makes foreign keys more complicated. (Note that I'm not talking about the native MVCC support in RDBMSs like SQL Server's snapshot isolation level) This has been discussed in other posts here on Stack Overflow. [todo - links] I am wondering, which of the prevalent entity/ORM frameworks (Linq to Sql, ADO.NET EF, Hibernate, etc) can cleanly support this type of design? This is a major change to the typical ActiveRecord design pattern, so I'm not sure if the majority of tools that are out there could help someone who decides to go this route with their data model. I'm particularly interested in how foreign keys would be handled, because I'm not even sure of the best way to data model them to support MVCC. ANSWER: I might consider implementing the MVCC tier purely in the DB, using stored procs and views to handle my data operations. Then you could present a reasonable API to any ORM that was capable of mapping to and from stored procs, and you could let the DB deal with the data integrity issues (since it's pretty much build for that). If you went this way, you might want to look at a more pure Mapping solution like IBatis or IBatis.net.
[ "database", "entity-framework", "orm" ]
9
3
2,057
6
0
2008-09-05T19:37:55.553000
2008-09-05T20:04:33.120000
46,714
46,822
Why is ARG_MAX not defined via limits.h?
On Fedora Core 7, I'm writing some code that relies on ARG_MAX. However, even if I #include, the constant is still not defined. My investigations show that it's present in, but this is supposed to be portable across Win32/Mac/Linux, so directly including it isn't an option. What's going on here?
The reason it's not in limits.h is that it's not a quantity giving the limits of the value range of an integral type based on bit width on the current architecture. That's the role assigned to limits.h by the ISO standard. The value in which you're interested is not hardware-bound in practice and can vary from platform to platform and perhaps system build to system build. The correct thing to do is to call sysconf and ask it for "ARG_MAX" or "_POSIX_ARG_MAX". I think that's the POSIX-compliant solution anyway. Acc. to my documentation, you include one or both of unistd.h or limits.h based on what values you're requesting. One other point: many implementations of the exec family of functions return E2BIG or a similar value if you try to call them with an oversized environment. This is one of the defined conditions under which exec can actually return.
Why is ARG_MAX not defined via limits.h? On Fedora Core 7, I'm writing some code that relies on ARG_MAX. However, even if I #include, the constant is still not defined. My investigations show that it's present in, but this is supposed to be portable across Win32/Mac/Linux, so directly including it isn't an option. What's going on here?
TITLE: Why is ARG_MAX not defined via limits.h? QUESTION: On Fedora Core 7, I'm writing some code that relies on ARG_MAX. However, even if I #include, the constant is still not defined. My investigations show that it's present in, but this is supposed to be portable across Win32/Mac/Linux, so directly including it isn't an option. What's going on here? ANSWER: The reason it's not in limits.h is that it's not a quantity giving the limits of the value range of an integral type based on bit width on the current architecture. That's the role assigned to limits.h by the ISO standard. The value in which you're interested is not hardware-bound in practice and can vary from platform to platform and perhaps system build to system build. The correct thing to do is to call sysconf and ask it for "ARG_MAX" or "_POSIX_ARG_MAX". I think that's the POSIX-compliant solution anyway. Acc. to my documentation, you include one or both of unistd.h or limits.h based on what values you're requesting. One other point: many implementations of the exec family of functions return E2BIG or a similar value if you try to call them with an oversized environment. This is one of the defined conditions under which exec can actually return.
[ "linux", "limits" ]
12
8
7,216
3
0
2008-09-05T19:39:37.157000
2008-09-05T20:23:59.627000
46,718
46,724
Best way to make a printer-friendly ASP.NET page?
I'm just curious how most people make their ASP.NET pages printer-friendly? Do you create a separate printer-friendly version of the ASPX page, use CSS or something else? How do you handle situations like page breaks and wide tables? Is there one elegant solution that works for the majority of the cases?
You basically make another CSS file that hide things or gives simpler "printer-friendly" style to things then add that with a media="print" so that it only applies to print media (when it is printed)
Best way to make a printer-friendly ASP.NET page? I'm just curious how most people make their ASP.NET pages printer-friendly? Do you create a separate printer-friendly version of the ASPX page, use CSS or something else? How do you handle situations like page breaks and wide tables? Is there one elegant solution that works for the majority of the cases?
TITLE: Best way to make a printer-friendly ASP.NET page? QUESTION: I'm just curious how most people make their ASP.NET pages printer-friendly? Do you create a separate printer-friendly version of the ASPX page, use CSS or something else? How do you handle situations like page breaks and wide tables? Is there one elegant solution that works for the majority of the cases? ANSWER: You basically make another CSS file that hide things or gives simpler "printer-friendly" style to things then add that with a media="print" so that it only applies to print media (when it is printed)
[ "asp.net" ]
8
14
7,525
3
0
2008-09-05T19:41:01.040000
2008-09-05T19:43:33.840000
46,719
46,785
Want to Encode text during Regex.Replace call
I have a regex call that I need help with. I haven't posted my regex, because it is not relevant here. What I want to be able to do is, during the Replace, I also want to modify the ${test} portion by doing a Html.Encode on the entire text that is effecting the regex. Basically, wrap the entire text that is within the range of the regex with the bold tag, but also Html.Encode the text inbetween the bold tag. RegexOptions regexOptions = RegexOptions.Compiled | RegexOptions.IgnoreCase; text = Regex.Replace(text, regexBold, @" ${text} ", regexOptions);
Heres an implementation of this I've used to pick out special replace strings from content and localize them. protected string FindAndTranslateIn(string content) { return Regex.Replace(content, @"\{\^(.+?);(.+?)?}", new MatchEvaluator(TranslateHandler), RegexOptions.IgnoreCase); } public string TranslateHandler(Match m) { if (m.Success) { string key = m.Groups[1].Value; key = FindAndTranslateIn(key); string def = string.Empty; if (m.Groups.Count > 2) { def = m.Groups[2].Value; if(def.Length > 1) { def = FindAndTranslateIn(def); } } if (group == null) { return Translate(key, def); } else { return Translate(key, group, def); } } return string.Empty; } From the match evaluator delegate you return everything you want replaced, so where I have returns you would have bold tags and an encode call, mine also supports recursion, so a little over complicated for your needs, but you can just pare down the example for your needs. This is equivalent to doing an iteration over the collection of matches and doing parts of the replace methods job. It just saves you some code, and you get to use a fancy shmancy delegate.
Want to Encode text during Regex.Replace call I have a regex call that I need help with. I haven't posted my regex, because it is not relevant here. What I want to be able to do is, during the Replace, I also want to modify the ${test} portion by doing a Html.Encode on the entire text that is effecting the regex. Basically, wrap the entire text that is within the range of the regex with the bold tag, but also Html.Encode the text inbetween the bold tag. RegexOptions regexOptions = RegexOptions.Compiled | RegexOptions.IgnoreCase; text = Regex.Replace(text, regexBold, @" ${text} ", regexOptions);
TITLE: Want to Encode text during Regex.Replace call QUESTION: I have a regex call that I need help with. I haven't posted my regex, because it is not relevant here. What I want to be able to do is, during the Replace, I also want to modify the ${test} portion by doing a Html.Encode on the entire text that is effecting the regex. Basically, wrap the entire text that is within the range of the regex with the bold tag, but also Html.Encode the text inbetween the bold tag. RegexOptions regexOptions = RegexOptions.Compiled | RegexOptions.IgnoreCase; text = Regex.Replace(text, regexBold, @" ${text} ", regexOptions); ANSWER: Heres an implementation of this I've used to pick out special replace strings from content and localize them. protected string FindAndTranslateIn(string content) { return Regex.Replace(content, @"\{\^(.+?);(.+?)?}", new MatchEvaluator(TranslateHandler), RegexOptions.IgnoreCase); } public string TranslateHandler(Match m) { if (m.Success) { string key = m.Groups[1].Value; key = FindAndTranslateIn(key); string def = string.Empty; if (m.Groups.Count > 2) { def = m.Groups[2].Value; if(def.Length > 1) { def = FindAndTranslateIn(def); } } if (group == null) { return Translate(key, def); } else { return Translate(key, group, def); } } return string.Empty; } From the match evaluator delegate you return everything you want replaced, so where I have returns you would have bold tags and an encode call, mine also supports recursion, so a little over complicated for your needs, but you can just pare down the example for your needs. This is equivalent to doing an iteration over the collection of matches and doing parts of the replace methods job. It just saves you some code, and you get to use a fancy shmancy delegate.
[ "regex" ]
4
2
1,875
5
0
2008-09-05T19:41:30.820000
2008-09-05T20:04:33.430000
46,777
46,794
How to control a web application through email? Or how to run php script by sending an email?
I want to run a web application on php and mysql, using the CakePHP framework. And to keep the threshold of using the site at a very low place, I want to not use the standard login with username/password. (And I don't want to hassle my users with something like OpenID either. Goes to user type.) So I'm thinking that the users shall be able to log in by sending an email to login@domain.com with no subject or content required. And they will get, in reply, an email with a link that will log them in (it will contain a hash). Also I will let the users do some actions without even visiting the site at all, just send an email with command@domain.com and the command will be carried out. I will assume that the users and their email providers takes care of their email account security and as such there is no need for it on my site. Now, how do I go from an email is sent to an account that is not read by humans to there being fired off some script (basically a "dummy browser client" calls an url( and the cakephp will take care of the rest)? I have never used a cron job before, but I do think I understand their purpose or how they generally work. I can not have the script be called by random people visiting the site, as that solution won't work for several reasons. I think I would like to hear more about the possibility of having the script be run as response to an email coming in, if anyone has any input at all on that. If it's run as a cron job it would only check every X minutes and users would get a lag in their response (if i understand it correctly). Since there will be different email addresses for different commands, like login @domain.com and I know what to do and how to do it to based on the sender email, i dont even need the content, subject or any other headers from the email. There is a lot of worry about security of this application, I understand the issues, but without giving away my concept, I dont think it is a big issue for what I am doing. Also about the usability issue, there really isnt any. It's just gonna be login to provide changes on a users profile if/when they need that and one other command. And this is the main email and is very easy to remember and the outset of this whole concept.
I have used the pop3 php class with great success (there is also a Pear POP3 module ). Using the pop3 class looks something like this: require ('pop3.php'); $pop3 = new pop3_class(); $pop3->hostname = MAILHOST; $pop3->Open(); $pop3->Login('myemailaddress@mydomain.com', 'mypassword'); foreach($pop3->ListMessages("","") as $msgidx => $msgsize) { $headers = ""; $body = ""; $pop3->RetrieveMessage($msgidx, $headers, $body, -1); } I use it to monitor a POP3 mailbox which feeds into a database. It gets called by a cronjob which uses wget to call the url to my php script. */5 * * * * "wget -q --http-user=me --http-passwd=pass 'http://mydomain.com/mail.php'" >> /dev/null 2>&1 Edit I've been thinking about your need to have users send certain site commands by email. Wouldn't it be easier to have a single address that multiple commands can be sent to rather than having multiple addresses? I think the security concerns are pretty valid too. Unless the commands are non-destructive or aren't doing anything user-specific, the system will be wide open to anyone who knows how to spoof an email address (which would be everyone:) ).
How to control a web application through email? Or how to run php script by sending an email? I want to run a web application on php and mysql, using the CakePHP framework. And to keep the threshold of using the site at a very low place, I want to not use the standard login with username/password. (And I don't want to hassle my users with something like OpenID either. Goes to user type.) So I'm thinking that the users shall be able to log in by sending an email to login@domain.com with no subject or content required. And they will get, in reply, an email with a link that will log them in (it will contain a hash). Also I will let the users do some actions without even visiting the site at all, just send an email with command@domain.com and the command will be carried out. I will assume that the users and their email providers takes care of their email account security and as such there is no need for it on my site. Now, how do I go from an email is sent to an account that is not read by humans to there being fired off some script (basically a "dummy browser client" calls an url( and the cakephp will take care of the rest)? I have never used a cron job before, but I do think I understand their purpose or how they generally work. I can not have the script be called by random people visiting the site, as that solution won't work for several reasons. I think I would like to hear more about the possibility of having the script be run as response to an email coming in, if anyone has any input at all on that. If it's run as a cron job it would only check every X minutes and users would get a lag in their response (if i understand it correctly). Since there will be different email addresses for different commands, like login @domain.com and I know what to do and how to do it to based on the sender email, i dont even need the content, subject or any other headers from the email. There is a lot of worry about security of this application, I understand the issues, but without giving away my concept, I dont think it is a big issue for what I am doing. Also about the usability issue, there really isnt any. It's just gonna be login to provide changes on a users profile if/when they need that and one other command. And this is the main email and is very easy to remember and the outset of this whole concept.
TITLE: How to control a web application through email? Or how to run php script by sending an email? QUESTION: I want to run a web application on php and mysql, using the CakePHP framework. And to keep the threshold of using the site at a very low place, I want to not use the standard login with username/password. (And I don't want to hassle my users with something like OpenID either. Goes to user type.) So I'm thinking that the users shall be able to log in by sending an email to login@domain.com with no subject or content required. And they will get, in reply, an email with a link that will log them in (it will contain a hash). Also I will let the users do some actions without even visiting the site at all, just send an email with command@domain.com and the command will be carried out. I will assume that the users and their email providers takes care of their email account security and as such there is no need for it on my site. Now, how do I go from an email is sent to an account that is not read by humans to there being fired off some script (basically a "dummy browser client" calls an url( and the cakephp will take care of the rest)? I have never used a cron job before, but I do think I understand their purpose or how they generally work. I can not have the script be called by random people visiting the site, as that solution won't work for several reasons. I think I would like to hear more about the possibility of having the script be run as response to an email coming in, if anyone has any input at all on that. If it's run as a cron job it would only check every X minutes and users would get a lag in their response (if i understand it correctly). Since there will be different email addresses for different commands, like login @domain.com and I know what to do and how to do it to based on the sender email, i dont even need the content, subject or any other headers from the email. There is a lot of worry about security of this application, I understand the issues, but without giving away my concept, I dont think it is a big issue for what I am doing. Also about the usability issue, there really isnt any. It's just gonna be login to provide changes on a users profile if/when they need that and one other command. And this is the main email and is very easy to remember and the outset of this whole concept. ANSWER: I have used the pop3 php class with great success (there is also a Pear POP3 module ). Using the pop3 class looks something like this: require ('pop3.php'); $pop3 = new pop3_class(); $pop3->hostname = MAILHOST; $pop3->Open(); $pop3->Login('myemailaddress@mydomain.com', 'mypassword'); foreach($pop3->ListMessages("","") as $msgidx => $msgsize) { $headers = ""; $body = ""; $pop3->RetrieveMessage($msgidx, $headers, $body, -1); } I use it to monitor a POP3 mailbox which feeds into a database. It gets called by a cronjob which uses wget to call the url to my php script. */5 * * * * "wget -q --http-user=me --http-passwd=pass 'http://mydomain.com/mail.php'" >> /dev/null 2>&1 Edit I've been thinking about your need to have users send certain site commands by email. Wouldn't it be easier to have a single address that multiple commands can be sent to rather than having multiple addresses? I think the security concerns are pretty valid too. Unless the commands are non-destructive or aren't doing anything user-specific, the system will be wide open to anyone who knows how to spoof an email address (which would be everyone:) ).
[ "cakephp", "email" ]
3
7
1,401
10
0
2008-09-05T20:02:27.773000
2008-09-05T20:08:59.613000
46,788
46,894
How to bind a MemoryStream to asp:image control?
Is there a way to bind a MemoryStream to asp:image control?
A handler can accept a url parameter like any other request. So instead of linking your to image.ashx you'd set it to image.ashx?ImageID=[Your image ID here].
How to bind a MemoryStream to asp:image control? Is there a way to bind a MemoryStream to asp:image control?
TITLE: How to bind a MemoryStream to asp:image control? QUESTION: Is there a way to bind a MemoryStream to asp:image control? ANSWER: A handler can accept a url parameter like any other request. So instead of linking your to image.ashx you'd set it to image.ashx?ImageID=[Your image ID here].
[ "asp.net", "image", "memorystream" ]
14
7
64,463
8
0
2008-09-05T20:05:53.180000
2008-09-05T21:10:42.633000
46,805
265,989
Custom cursor in WPF?
I want to use an image or icon as a custom cursor in WPF app. How can I do that?
You have two basic options: When the mouse cursor is over your control, hide the system cursor by setting this.Cursor = Cursors.None; and draw your own cursor using whatever technique you like. Then, update the position and appearance of your cursor by responding to mouse events. Here are two examples: http://www.xamlog.com/2006/07/17/creating-a-custom-cursor/ http://www.hanselman.com/blog/DeveloperDesigner.aspx Additional examples can be found here: WPF Tutorial - How To Use Custom Cursors Setting the Cursor to Render Some Text While Dragging Getting fancy and using the Visual we are dragging for feedback [instead of a cursor] How can I drag and drop items between data bound ItemsControls? Create a new Cursor object by loading an image from a.cur or.ani file. You can create and edit these kinds of files in Visual Studio. There are also some free utilites floating around for dealing with them. Basically they're images (or animated images) which specify a "hot spot" indicating what point in the image the cursor is positioned at. If you choose to load from a file, note that you need an absolute file-system path to use the Cursor(string fileName) constructor. Lamely, a relative path or Pack URI will not work. If you need to load the cursor from a relative path or from a resource packed with your assembly, you will need to get a stream from the file and pass it in to the Cursor(Stream cursorStream) constructor. Annoying but true. On the other hand, specifying a cursor as a relative path when loading it using a XAML attribute does work, a fact you could use to get your cursor loaded onto a hidden control and then copy the reference to use on another control. I haven't tried it, but it should work.
Custom cursor in WPF? I want to use an image or icon as a custom cursor in WPF app. How can I do that?
TITLE: Custom cursor in WPF? QUESTION: I want to use an image or icon as a custom cursor in WPF app. How can I do that? ANSWER: You have two basic options: When the mouse cursor is over your control, hide the system cursor by setting this.Cursor = Cursors.None; and draw your own cursor using whatever technique you like. Then, update the position and appearance of your cursor by responding to mouse events. Here are two examples: http://www.xamlog.com/2006/07/17/creating-a-custom-cursor/ http://www.hanselman.com/blog/DeveloperDesigner.aspx Additional examples can be found here: WPF Tutorial - How To Use Custom Cursors Setting the Cursor to Render Some Text While Dragging Getting fancy and using the Visual we are dragging for feedback [instead of a cursor] How can I drag and drop items between data bound ItemsControls? Create a new Cursor object by loading an image from a.cur or.ani file. You can create and edit these kinds of files in Visual Studio. There are also some free utilites floating around for dealing with them. Basically they're images (or animated images) which specify a "hot spot" indicating what point in the image the cursor is positioned at. If you choose to load from a file, note that you need an absolute file-system path to use the Cursor(string fileName) constructor. Lamely, a relative path or Pack URI will not work. If you need to load the cursor from a relative path or from a resource packed with your assembly, you will need to get a stream from the file and pass it in to the Cursor(Stream cursorStream) constructor. Annoying but true. On the other hand, specifying a cursor as a relative path when loading it using a XAML attribute does work, a fact you could use to get your cursor loaded onto a hidden control and then copy the reference to use on another control. I haven't tried it, but it should work.
[ ".net", "wpf" ]
57
39
69,822
15
0
2008-09-05T20:13:48.730000
2008-11-05T17:38:10.477000
46,827
46,832
How do you create a foreign key relationship in a SQL Server CE (Compact Edition) Database?
Visual Studio 2005 doesn't provide an interface for creating relationships between tables in a SQL Server CE database (I'm using version 3.0) and you can't open a Compact Edition DB using Management Studio as far as I know. Any ideas?
Unfortunately there is currently no designer support (unlike for SQL Server 2005) for building relationships between tables in SQL Server CE. To build relationships you need to use SQL commands such as: ALTER TABLE Orders ADD CONSTRAINT FK_Customer_Order FOREIGN KEY (CustomerId) REFERENCES Customers(CustomerId) If you are doing CE development, i would recomend this FAQ: EDIT: In Visual Studio 2008 this is now possible to do in the GUI by right-clicking on your table.
How do you create a foreign key relationship in a SQL Server CE (Compact Edition) Database? Visual Studio 2005 doesn't provide an interface for creating relationships between tables in a SQL Server CE database (I'm using version 3.0) and you can't open a Compact Edition DB using Management Studio as far as I know. Any ideas?
TITLE: How do you create a foreign key relationship in a SQL Server CE (Compact Edition) Database? QUESTION: Visual Studio 2005 doesn't provide an interface for creating relationships between tables in a SQL Server CE database (I'm using version 3.0) and you can't open a Compact Edition DB using Management Studio as far as I know. Any ideas? ANSWER: Unfortunately there is currently no designer support (unlike for SQL Server 2005) for building relationships between tables in SQL Server CE. To build relationships you need to use SQL commands such as: ALTER TABLE Orders ADD CONSTRAINT FK_Customer_Order FOREIGN KEY (CustomerId) REFERENCES Customers(CustomerId) If you are doing CE development, i would recomend this FAQ: EDIT: In Visual Studio 2008 this is now possible to do in the GUI by right-clicking on your table.
[ "database", "visual-studio", "sql-server-ce", "visual-studio-2005" ]
48
71
111,404
7
0
2008-09-05T20:26:12.350000
2008-09-05T20:29:19.893000
46,841
47,237
Why do I get this error "[DBNETLIB][ConnectionRead (recv()).]General network error" with ASP pages
Occasionally, on a ASP (classic) site users will get this error: [DBNETLIB][ConnectionRead (recv()).]General network error. Seems to be random and not connected to any particular page. The SQL server is separated from the web server and my guess is that every once and a while the "link" goes down between the two. Router/switch issue... or has someone else ran into this problem before?
Using the same setup as yours (ie separate web and database server), I've seen it from time to time and it has always been a connection problem between the servers - typically when the database server is being rebooted but sometimes when there's a comms problem somewhere in the system. I've not seen it triggered by any problems with the ASP code itself, which is why you're seeing it apparently at random and not connected to a particular page.
Why do I get this error "[DBNETLIB][ConnectionRead (recv()).]General network error" with ASP pages Occasionally, on a ASP (classic) site users will get this error: [DBNETLIB][ConnectionRead (recv()).]General network error. Seems to be random and not connected to any particular page. The SQL server is separated from the web server and my guess is that every once and a while the "link" goes down between the two. Router/switch issue... or has someone else ran into this problem before?
TITLE: Why do I get this error "[DBNETLIB][ConnectionRead (recv()).]General network error" with ASP pages QUESTION: Occasionally, on a ASP (classic) site users will get this error: [DBNETLIB][ConnectionRead (recv()).]General network error. Seems to be random and not connected to any particular page. The SQL server is separated from the web server and my guess is that every once and a while the "link" goes down between the two. Router/switch issue... or has someone else ran into this problem before? ANSWER: Using the same setup as yours (ie separate web and database server), I've seen it from time to time and it has always been a connection problem between the servers - typically when the database server is being rebooted but sometimes when there's a comms problem somewhere in the system. I've not seen it triggered by any problems with the ASP code itself, which is why you're seeing it apparently at random and not connected to a particular page.
[ "sql-server", "networking", "asp-classic" ]
4
1
31,528
6
0
2008-09-05T20:35:57.833000
2008-09-06T03:49:51.427000
46,855
46,884
C# Game Network Library
I am developing an online strategy game using.Net v2. Although the game is primarily strategic, it does have some tactical elements that require reasonable network performance. I plan to use TCP packets for strategic data and UDP packets for tactical data. {EDIT} I forgot to mention that I am leaning away from WCF and.NET 3+ for a couple of reasons. First, because I want to keep my download small and most of my customers already have.NET 2.0. Second, because I would like to have the option of porting to Mac and Linux and am unsure of WCF availability in Mono. {/EDIT} I am looking for network library recommendations. I have found a few options, such as GarageGames' Torque Network Library (C++), RakNet (C++), and the lidgren network library (C#): http://www.opentnl.org/ http://www.jenkinssoftware.com/ http://code.google.com/p/lidgren-network/ Does anyone have real-world experience with these or other libraries? I just stumbled on RakNetDotNet: http://code.google.com/p/raknetdotnet/ This might be what I'm looking for...
Why limit yourself to.NET 2.0..NET 3.0 (or 3.5) contains WCF and is a solid, performant communications subsystem with good security..NET 3.0 is just.NET 2.0 with additional libraries (WCF, WF, WPF).
C# Game Network Library I am developing an online strategy game using.Net v2. Although the game is primarily strategic, it does have some tactical elements that require reasonable network performance. I plan to use TCP packets for strategic data and UDP packets for tactical data. {EDIT} I forgot to mention that I am leaning away from WCF and.NET 3+ for a couple of reasons. First, because I want to keep my download small and most of my customers already have.NET 2.0. Second, because I would like to have the option of porting to Mac and Linux and am unsure of WCF availability in Mono. {/EDIT} I am looking for network library recommendations. I have found a few options, such as GarageGames' Torque Network Library (C++), RakNet (C++), and the lidgren network library (C#): http://www.opentnl.org/ http://www.jenkinssoftware.com/ http://code.google.com/p/lidgren-network/ Does anyone have real-world experience with these or other libraries? I just stumbled on RakNetDotNet: http://code.google.com/p/raknetdotnet/ This might be what I'm looking for...
TITLE: C# Game Network Library QUESTION: I am developing an online strategy game using.Net v2. Although the game is primarily strategic, it does have some tactical elements that require reasonable network performance. I plan to use TCP packets for strategic data and UDP packets for tactical data. {EDIT} I forgot to mention that I am leaning away from WCF and.NET 3+ for a couple of reasons. First, because I want to keep my download small and most of my customers already have.NET 2.0. Second, because I would like to have the option of porting to Mac and Linux and am unsure of WCF availability in Mono. {/EDIT} I am looking for network library recommendations. I have found a few options, such as GarageGames' Torque Network Library (C++), RakNet (C++), and the lidgren network library (C#): http://www.opentnl.org/ http://www.jenkinssoftware.com/ http://code.google.com/p/lidgren-network/ Does anyone have real-world experience with these or other libraries? I just stumbled on RakNetDotNet: http://code.google.com/p/raknetdotnet/ This might be what I'm looking for... ANSWER: Why limit yourself to.NET 2.0..NET 3.0 (or 3.5) contains WCF and is a solid, performant communications subsystem with good security..NET 3.0 is just.NET 2.0 with additional libraries (WCF, WF, WPF).
[ "c#", "network-programming" ]
6
1
13,892
8
0
2008-09-05T20:45:11.930000
2008-09-05T21:03:49.937000
46,859
50,869
Where do attached properties fit in a class diagram?
What is the most appropriate way to represent attached properties in a UML diagram or an almost-uml diagram like the VS2008 class diagram?
In UML it'll be quoted tag before the member. Something conventional, like this: "attached" Align: ElementAlign
Where do attached properties fit in a class diagram? What is the most appropriate way to represent attached properties in a UML diagram or an almost-uml diagram like the VS2008 class diagram?
TITLE: Where do attached properties fit in a class diagram? QUESTION: What is the most appropriate way to represent attached properties in a UML diagram or an almost-uml diagram like the VS2008 class diagram? ANSWER: In UML it'll be quoted tag before the member. Something conventional, like this: "attached" Align: ElementAlign
[ ".net", "wpf", "uml", "dependency-properties", "class-diagram" ]
1
1
266
1
0
2008-09-05T20:47:44.733000
2008-09-08T22:40:06.077000
46,860
46,866
Showing a hint for a C# winforms edit control
I'm working on a C# winforms application (VS.NET 2008,.NET 3.5 sp 1). I have a search field on a form, and rather than have a label next to the search field I'd like to show some grey text in the background of the search field itself ('Search terms', for example). When the user starts entering text in the search field the text should disappear. How can I achieve this?
You will need to use some P/Inovke interop code to do this. Look for the Win32 API SendMessage function and the EM_SETCUEBANNER message.
Showing a hint for a C# winforms edit control I'm working on a C# winforms application (VS.NET 2008,.NET 3.5 sp 1). I have a search field on a form, and rather than have a label next to the search field I'd like to show some grey text in the background of the search field itself ('Search terms', for example). When the user starts entering text in the search field the text should disappear. How can I achieve this?
TITLE: Showing a hint for a C# winforms edit control QUESTION: I'm working on a C# winforms application (VS.NET 2008,.NET 3.5 sp 1). I have a search field on a form, and rather than have a label next to the search field I'd like to show some grey text in the background of the search field itself ('Search terms', for example). When the user starts entering text in the search field the text should disappear. How can I achieve this? ANSWER: You will need to use some P/Inovke interop code to do this. Look for the Win32 API SendMessage function and the EM_SETCUEBANNER message.
[ "c#", "winforms", "user-interface" ]
9
9
14,400
4
0
2008-09-05T20:47:55.807000
2008-09-05T20:53:36.683000
46,863
47,119
concatenating unknown-length strings in COBOL
How do I concatenate together two strings, of unknown length, in COBOL? So for example: WORKING-STORAGE. FIRST-NAME PIC X(15) VALUE SPACES. LAST-NAME PIC X(15) VALUE SPACES. FULL-NAME PIC X(31) VALUE SPACES. If FIRST-NAME = 'JOHN ' and LAST-NAME = 'DOE ', how can I get: FULL-NAME = 'JOHN DOE ' as opposed to: FULL-NAME = 'JOHN DOE '
I believe the following will give you what you desire. STRING FIRST-NAME DELIMITED BY " ", " ", LAST-NAME DELIMITED BY SIZE INTO FULL-NAME.
concatenating unknown-length strings in COBOL How do I concatenate together two strings, of unknown length, in COBOL? So for example: WORKING-STORAGE. FIRST-NAME PIC X(15) VALUE SPACES. LAST-NAME PIC X(15) VALUE SPACES. FULL-NAME PIC X(31) VALUE SPACES. If FIRST-NAME = 'JOHN ' and LAST-NAME = 'DOE ', how can I get: FULL-NAME = 'JOHN DOE ' as opposed to: FULL-NAME = 'JOHN DOE '
TITLE: concatenating unknown-length strings in COBOL QUESTION: How do I concatenate together two strings, of unknown length, in COBOL? So for example: WORKING-STORAGE. FIRST-NAME PIC X(15) VALUE SPACES. LAST-NAME PIC X(15) VALUE SPACES. FULL-NAME PIC X(31) VALUE SPACES. If FIRST-NAME = 'JOHN ' and LAST-NAME = 'DOE ', how can I get: FULL-NAME = 'JOHN DOE ' as opposed to: FULL-NAME = 'JOHN DOE ' ANSWER: I believe the following will give you what you desire. STRING FIRST-NAME DELIMITED BY " ", " ", LAST-NAME DELIMITED BY SIZE INTO FULL-NAME.
[ "string", "cobol" ]
4
5
24,887
3
0
2008-09-05T20:49:53.743000
2008-09-06T00:11:00.563000
46,869
46,897
What's a good method for extracting text from a PDF using C# or classic ASP (VBScript)?
Is there a good library for extracting text from a PDF? I'm willing to pay for it if I have to. Something that works with C# or classic ASP (VBScript) would be ideal and I also need to be able to separate the pages from the PDF. This question had some interesting stuff, especially pdftotext but I'd like to avoid calling to an external command-line app if I can.
You can use the IFilter interface built into Windows to extract text and properties (author, title, etc.) from any supported file type. It's a COM interface so you would have use the.NET interop facilities. You'd also have to download the free PDF IFilter driver from Adobe.
What's a good method for extracting text from a PDF using C# or classic ASP (VBScript)? Is there a good library for extracting text from a PDF? I'm willing to pay for it if I have to. Something that works with C# or classic ASP (VBScript) would be ideal and I also need to be able to separate the pages from the PDF. This question had some interesting stuff, especially pdftotext but I'd like to avoid calling to an external command-line app if I can.
TITLE: What's a good method for extracting text from a PDF using C# or classic ASP (VBScript)? QUESTION: Is there a good library for extracting text from a PDF? I'm willing to pay for it if I have to. Something that works with C# or classic ASP (VBScript) would be ideal and I also need to be able to separate the pages from the PDF. This question had some interesting stuff, especially pdftotext but I'd like to avoid calling to an external command-line app if I can. ANSWER: You can use the IFilter interface built into Windows to extract text and properties (author, title, etc.) from any supported file type. It's a COM interface so you would have use the.NET interop facilities. You'd also have to download the free PDF IFilter driver from Adobe.
[ "pdf", "text-extraction", "pdf-scraping" ]
4
4
9,726
5
0
2008-09-05T20:55:39.767000
2008-09-05T21:12:38.977000
46,898
46,908
How do I efficiently iterate over each entry in a Java Map?
If I have an object implementing the Map interface in Java and I wish to iterate over every pair contained within it, what is the most efficient way of going through the map? Will the ordering of elements depend on the specific map implementation that I have for the interface?
Map map =... for (Map.Entry entry: map.entrySet()) { System.out.println(entry.getKey() + "/" + entry.getValue()); } On Java 10+: for (var entry: map.entrySet()) { System.out.println(entry.getKey() + "/" + entry.getValue()); }
How do I efficiently iterate over each entry in a Java Map? If I have an object implementing the Map interface in Java and I wish to iterate over every pair contained within it, what is the most efficient way of going through the map? Will the ordering of elements depend on the specific map implementation that I have for the interface?
TITLE: How do I efficiently iterate over each entry in a Java Map? QUESTION: If I have an object implementing the Map interface in Java and I wish to iterate over every pair contained within it, what is the most efficient way of going through the map? Will the ordering of elements depend on the specific map implementation that I have for the interface? ANSWER: Map map =... for (Map.Entry entry: map.entrySet()) { System.out.println(entry.getKey() + "/" + entry.getValue()); } On Java 10+: for (var entry: map.entrySet()) { System.out.println(entry.getKey() + "/" + entry.getValue()); }
[ "java", "dictionary", "collections", "iteration" ]
3,982
5,893
3,364,999
46
0
2008-09-05T21:12:48.370000
2008-09-05T21:15:52.713000
46,907
46,931
Is there anything wrong with this query?
INSERT INTO tblExcel (ename, position, phone, email) VALUES ('Burton, Andrew', 'Web Developer / Network Assistant', '876-9259', 'aburton@wccs.edu') I've got an Access table that has five fields: id, ename, position, phone, and email...each one is plain text field with 50 characters, save for position which is 255 and id which is an autoincrement field. I'm using a VB.NET to read data from an Excel table, which gets pushed into a simple class that's used to fill out that query. I do the same thing with two other tables, whose data are pulled from a DB2 table and a MySQL table through. The other two work, but this simple INSERT loop keeps failing, so I don't think it's my "InsertNoExe" function that handles all the OleDb stuff. So, um, does that query, any of the field titles, etc. look bogus? I can post other bits of code if anyone wants to see it. EDIT: Fixed. I wasn't sure if the wide image counted as a Stack Overflow bug or not, which is why I left it. EDIT 2: I'm dense. I use a try...catch to see the bogus query, and don't even check the ex.messsage. Gah. INSERT INTO tblExcel (ename, position, phone, email) VALUES ('Burton, Andrew', 'Web Developer / Network Assistant', '876-9259', 'aburton@wccs.edu') at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(Int32 hr) at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) at System.Data.OleDb.OleDbCommand.ExecuteNonQuery() at EmployeeList.EmployeeDatabase.ExeNonQuery(String sql) in C:\andy\html\code\vb\EmployeeList\EmployeeDatabase.vb:line 263 Syntax error in INSERT INTO statement. EDIT 3: Thank you, Chris.
I beleive "position" is a reserved word. Try... INSERT into tblExcel (ename, [position], phone, email) VALUES (... Reserved Words
Is there anything wrong with this query? INSERT INTO tblExcel (ename, position, phone, email) VALUES ('Burton, Andrew', 'Web Developer / Network Assistant', '876-9259', 'aburton@wccs.edu') I've got an Access table that has five fields: id, ename, position, phone, and email...each one is plain text field with 50 characters, save for position which is 255 and id which is an autoincrement field. I'm using a VB.NET to read data from an Excel table, which gets pushed into a simple class that's used to fill out that query. I do the same thing with two other tables, whose data are pulled from a DB2 table and a MySQL table through. The other two work, but this simple INSERT loop keeps failing, so I don't think it's my "InsertNoExe" function that handles all the OleDb stuff. So, um, does that query, any of the field titles, etc. look bogus? I can post other bits of code if anyone wants to see it. EDIT: Fixed. I wasn't sure if the wide image counted as a Stack Overflow bug or not, which is why I left it. EDIT 2: I'm dense. I use a try...catch to see the bogus query, and don't even check the ex.messsage. Gah. INSERT INTO tblExcel (ename, position, phone, email) VALUES ('Burton, Andrew', 'Web Developer / Network Assistant', '876-9259', 'aburton@wccs.edu') at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(Int32 hr) at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) at System.Data.OleDb.OleDbCommand.ExecuteNonQuery() at EmployeeList.EmployeeDatabase.ExeNonQuery(String sql) in C:\andy\html\code\vb\EmployeeList\EmployeeDatabase.vb:line 263 Syntax error in INSERT INTO statement. EDIT 3: Thank you, Chris.
TITLE: Is there anything wrong with this query? QUESTION: INSERT INTO tblExcel (ename, position, phone, email) VALUES ('Burton, Andrew', 'Web Developer / Network Assistant', '876-9259', 'aburton@wccs.edu') I've got an Access table that has five fields: id, ename, position, phone, and email...each one is plain text field with 50 characters, save for position which is 255 and id which is an autoincrement field. I'm using a VB.NET to read data from an Excel table, which gets pushed into a simple class that's used to fill out that query. I do the same thing with two other tables, whose data are pulled from a DB2 table and a MySQL table through. The other two work, but this simple INSERT loop keeps failing, so I don't think it's my "InsertNoExe" function that handles all the OleDb stuff. So, um, does that query, any of the field titles, etc. look bogus? I can post other bits of code if anyone wants to see it. EDIT: Fixed. I wasn't sure if the wide image counted as a Stack Overflow bug or not, which is why I left it. EDIT 2: I'm dense. I use a try...catch to see the bogus query, and don't even check the ex.messsage. Gah. INSERT INTO tblExcel (ename, position, phone, email) VALUES ('Burton, Andrew', 'Web Developer / Network Assistant', '876-9259', 'aburton@wccs.edu') at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(Int32 hr) at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) at System.Data.OleDb.OleDbCommand.ExecuteNonQuery() at EmployeeList.EmployeeDatabase.ExeNonQuery(String sql) in C:\andy\html\code\vb\EmployeeList\EmployeeDatabase.vb:line 263 Syntax error in INSERT INTO statement. EDIT 3: Thank you, Chris. ANSWER: I beleive "position" is a reserved word. Try... INSERT into tblExcel (ename, [position], phone, email) VALUES (... Reserved Words
[ "sql", "vb.net", "excel", "ms-access", "oledb" ]
0
5
512
2
0
2008-09-05T21:15:50.547000
2008-09-05T21:30:19.200000
46,909
46,952
Is this the proper use of a mutex?
I have a situation where I might have multiple instances of a program running at once, and it's important that just one specific function not be executing in more than one of these instances at once. Is this the proper way to use a mutex to prevent this from happening? lock (this.GetType()) { _log.Info("Doing Sync"); DoSync(); _log.Info("Sync Completed"); }
You said multiple instances of one application, so we're talking about two program.exe's running, right? The lock statement won't lock across multiple programs, just within the program. If you want a true Mutex, look at the System.Threading.Mutex object. Here is a usage example: bool createdNew; using (Mutex mtx = new Mutex(false, "MyAwesomeMutex", out createdNew)) { try { mtx.WaitOne(); MessageBox.Show("Click OK to release the mutex."); } finally { mtx.ReleaseMutex(); } } The createdNew variable will let you know whether or not it was created the first time. It only tells you if it has been created, though. If you want to acquire the lock, you need to call WaitOne and then call ReleaseMutex to release it. If you just want to see if you created a Mutex, just constructing it is fine.
Is this the proper use of a mutex? I have a situation where I might have multiple instances of a program running at once, and it's important that just one specific function not be executing in more than one of these instances at once. Is this the proper way to use a mutex to prevent this from happening? lock (this.GetType()) { _log.Info("Doing Sync"); DoSync(); _log.Info("Sync Completed"); }
TITLE: Is this the proper use of a mutex? QUESTION: I have a situation where I might have multiple instances of a program running at once, and it's important that just one specific function not be executing in more than one of these instances at once. Is this the proper way to use a mutex to prevent this from happening? lock (this.GetType()) { _log.Info("Doing Sync"); DoSync(); _log.Info("Sync Completed"); } ANSWER: You said multiple instances of one application, so we're talking about two program.exe's running, right? The lock statement won't lock across multiple programs, just within the program. If you want a true Mutex, look at the System.Threading.Mutex object. Here is a usage example: bool createdNew; using (Mutex mtx = new Mutex(false, "MyAwesomeMutex", out createdNew)) { try { mtx.WaitOne(); MessageBox.Show("Click OK to release the mutex."); } finally { mtx.ReleaseMutex(); } } The createdNew variable will let you know whether or not it was created the first time. It only tells you if it has been created, though. If you want to acquire the lock, you need to call WaitOne and then call ReleaseMutex to release it. If you just want to see if you created a Mutex, just constructing it is fine.
[ "c#", "mutex" ]
9
18
3,542
2
0
2008-09-05T21:17:16.783000
2008-09-05T21:38:56.950000
46,915
47,161
How can I detect if a Flex app loses focus
As a follow up to this question: Developing a online exam application, how do I prevent cheaters? Can I detect when Flex application looses its focus? that is if a user has clicked onto another application or opened a browser tab? I read this: Detecting when a Flex application loses focus but was not very clear...
The key part of the code at that link is the systemManager.stage.addEventListener(Event.DEACTIVATE,deactivate); The Flash player send outs activate and deactivate events when the focus enters and leaves the player. All you need to do is create a listenr for them and react appropriately. A more clear example of how to use to the activate and deactivate events can be seen at blog.flexaxamples.com. Also, it looks like the activate and deactivate events have trouble in some browsers. Colin Moock has more info on that here.
How can I detect if a Flex app loses focus As a follow up to this question: Developing a online exam application, how do I prevent cheaters? Can I detect when Flex application looses its focus? that is if a user has clicked onto another application or opened a browser tab? I read this: Detecting when a Flex application loses focus but was not very clear...
TITLE: How can I detect if a Flex app loses focus QUESTION: As a follow up to this question: Developing a online exam application, how do I prevent cheaters? Can I detect when Flex application looses its focus? that is if a user has clicked onto another application or opened a browser tab? I read this: Detecting when a Flex application loses focus but was not very clear... ANSWER: The key part of the code at that link is the systemManager.stage.addEventListener(Event.DEACTIVATE,deactivate); The Flash player send outs activate and deactivate events when the focus enters and leaves the player. All you need to do is create a listenr for them and react appropriately. A more clear example of how to use to the activate and deactivate events can be seen at blog.flexaxamples.com. Also, it looks like the activate and deactivate events have trouble in some browsers. Colin Moock has more info on that here.
[ "apache-flex", "actionscript" ]
3
5
5,162
4
0
2008-09-05T21:19:41.003000
2008-09-06T01:18:36.953000
46,918
47,743
What's the proper way to minimize to tray a C# WinForms app?
What is the proper way to minimize a WinForms app to the system tray? Note: minimize to system tray; on the right side of the taskbar by the clock. I'm not asking about minimizing to taskbar, which is what happens when you hit the "minus" button on the window. I've seen hackish solutions like, "minimize, set ShowInTaskbar = false, then show your NotifyIcon." Solutions like that are hackish because the app doesn't appear to minimize to the tray like other apps, the code has to detect when to set ShowInTaskbar = true, among other issues. What's the proper way to do this?
There is actually no managed way to do that form of animation to the tray in native winforms, however you can P/Invoke shell32.dll to do it: Some good info here (In the comments not the post): http://blogs.msdn.com/jfoscoding/archive/2005/10/20/483300.aspx And here it is in C++: http://www.codeproject.com/KB/shell/minimizetotray.aspx You can use that to figure out what stuff to Pinvoke for your C# version.
What's the proper way to minimize to tray a C# WinForms app? What is the proper way to minimize a WinForms app to the system tray? Note: minimize to system tray; on the right side of the taskbar by the clock. I'm not asking about minimizing to taskbar, which is what happens when you hit the "minus" button on the window. I've seen hackish solutions like, "minimize, set ShowInTaskbar = false, then show your NotifyIcon." Solutions like that are hackish because the app doesn't appear to minimize to the tray like other apps, the code has to detect when to set ShowInTaskbar = true, among other issues. What's the proper way to do this?
TITLE: What's the proper way to minimize to tray a C# WinForms app? QUESTION: What is the proper way to minimize a WinForms app to the system tray? Note: minimize to system tray; on the right side of the taskbar by the clock. I'm not asking about minimizing to taskbar, which is what happens when you hit the "minus" button on the window. I've seen hackish solutions like, "minimize, set ShowInTaskbar = false, then show your NotifyIcon." Solutions like that are hackish because the app doesn't appear to minimize to the tray like other apps, the code has to detect when to set ShowInTaskbar = true, among other issues. What's the proper way to do this? ANSWER: There is actually no managed way to do that form of animation to the tray in native winforms, however you can P/Invoke shell32.dll to do it: Some good info here (In the comments not the post): http://blogs.msdn.com/jfoscoding/archive/2005/10/20/483300.aspx And here it is in C++: http://www.codeproject.com/KB/shell/minimizetotray.aspx You can use that to figure out what stuff to Pinvoke for your C# version.
[ "c#", "winforms", "trayicon" ]
63
20
65,358
9
0
2008-09-05T21:20:47.040000
2008-09-06T19:07:50.017000
46,924
47,002
How can a simple tree algorithm be coded in a functional language?
Suppose I want to implement a reasonably efficient 'keyword recognition algorithm', that is first given a list of keyword, and must then answer if another given word was in the list. In an imperative language, I would store the keywords in a tree (one node per character). Then, when receiving a word to test, I would scan my tree to test if the word is a keyword. I'd like to understand how such an algorithm would be coded in a functional language. How does one get the benefits of 'stateless' programming while keeping the efficiency of 'imperative' algorithms. Isn't it necessary to store the tree somewhere between the lookups if you don't want to rebuild it each time?
I think what you mean is a character per node... sort of like a simple hash tree scheme for keyword lookup. Assuming this or even another kind of tree... imagine doing something like this (in pseudo-LISP): (defun buildtree (wordlist)...code to build tree recursively returns the tree...) (define lookup (tree word)...code to look up word using tree, returns t or nil...) (defun lookupmany (tree querylist) (if (eq querylist nil) nil (cons (lookup tree (car querylist)) (lookupmany tree (cdr querylist)) ) ) (defun main (wordlist querylist); the main entry point (lookupmany (buildtree wordlist) querylist) ) if this is what you mean, this is fairly straight-forward functional programming. Is it really stateless? That's a matter of debate. Some people would say some forms of functional programming store what we normally call "state" on the stack. Moreover, Common LISP even since the first edition of the Steele book has had iterative constructs, and LISP has had setq for a long, long time. But in the theory of programming languages, what we mean by "stateless" is pretty much satisfied by the idea shown here. I think the above is something like the arrangement you mean.
How can a simple tree algorithm be coded in a functional language? Suppose I want to implement a reasonably efficient 'keyword recognition algorithm', that is first given a list of keyword, and must then answer if another given word was in the list. In an imperative language, I would store the keywords in a tree (one node per character). Then, when receiving a word to test, I would scan my tree to test if the word is a keyword. I'd like to understand how such an algorithm would be coded in a functional language. How does one get the benefits of 'stateless' programming while keeping the efficiency of 'imperative' algorithms. Isn't it necessary to store the tree somewhere between the lookups if you don't want to rebuild it each time?
TITLE: How can a simple tree algorithm be coded in a functional language? QUESTION: Suppose I want to implement a reasonably efficient 'keyword recognition algorithm', that is first given a list of keyword, and must then answer if another given word was in the list. In an imperative language, I would store the keywords in a tree (one node per character). Then, when receiving a word to test, I would scan my tree to test if the word is a keyword. I'd like to understand how such an algorithm would be coded in a functional language. How does one get the benefits of 'stateless' programming while keeping the efficiency of 'imperative' algorithms. Isn't it necessary to store the tree somewhere between the lookups if you don't want to rebuild it each time? ANSWER: I think what you mean is a character per node... sort of like a simple hash tree scheme for keyword lookup. Assuming this or even another kind of tree... imagine doing something like this (in pseudo-LISP): (defun buildtree (wordlist)...code to build tree recursively returns the tree...) (define lookup (tree word)...code to look up word using tree, returns t or nil...) (defun lookupmany (tree querylist) (if (eq querylist nil) nil (cons (lookup tree (car querylist)) (lookupmany tree (cdr querylist)) ) ) (defun main (wordlist querylist); the main entry point (lookupmany (buildtree wordlist) querylist) ) if this is what you mean, this is fairly straight-forward functional programming. Is it really stateless? That's a matter of debate. Some people would say some forms of functional programming store what we normally call "state" on the stack. Moreover, Common LISP even since the first edition of the Steele book has had iterative constructs, and LISP has had setq for a long, long time. But in the theory of programming languages, what we mean by "stateless" is pretty much satisfied by the idea shown here. I think the above is something like the arrangement you mean.
[ "algorithm", "functional-programming" ]
4
3
829
2
0
2008-09-05T21:26:51.970000
2008-09-05T22:26:38.613000
46,930
64,674
Reference material for LabVIEW
I'm supposed to learn how to use LabVIEW for my new job, and I'm wondering if anybody can recommend some good books or reference/tutorial web sites. I'm a senior developer with lots of Java/C#/C++ experience. I realize that this question is perhaps more vague than is intended on stack overflow, so how about this? Please answer with one book or web site and a brief description. Then people can vote up their favourites.
It will take some training and some time to learn the style needed to develop maintainable code. Coming from Java/C#/C++, you probably have a good idea of good software architecture. Now you just need to learn the peculiarities of LabView and the common pitfalls. For the basics, National Instruments offers training courses. See if your new employer can send you to a Basics I/II class to get your feet wet. They offer some online classes as well. Following classes, you can sign up to take tests for certification. Get an evaluation copy of Labview from National Instruments; they have a well maintained help file that you can dive right into, with example code included. Look at "Getting Started" and "LabVIEW Environment". You should be able to jump right in and become familiar with the dev environment pretty quickly. LabVIEW, being graphical is nice, but don't throw out your best practices from an application design point of view. It is common to end up with code looking like rainbow sphaghetti, or code that stretches several screens wide. Use subvi's and keep each vi with a specific purpose and function. The official NI support forums and knowledgebase are probably the best resources out there at the moment. Unofficial sites like Tutorials in G have a subset of the information found on the official site and documentation, but still may be useful for cross reference if you get stuck. Edit: Basics I/II are designed to be accessible to users without prior software development experience. Depending on how you feel after using the evaluation version, you may be able to move directly into Intermediate I/II. NI has the course outlines available on their website as well, so you know what you're going to cover in each.
Reference material for LabVIEW I'm supposed to learn how to use LabVIEW for my new job, and I'm wondering if anybody can recommend some good books or reference/tutorial web sites. I'm a senior developer with lots of Java/C#/C++ experience. I realize that this question is perhaps more vague than is intended on stack overflow, so how about this? Please answer with one book or web site and a brief description. Then people can vote up their favourites.
TITLE: Reference material for LabVIEW QUESTION: I'm supposed to learn how to use LabVIEW for my new job, and I'm wondering if anybody can recommend some good books or reference/tutorial web sites. I'm a senior developer with lots of Java/C#/C++ experience. I realize that this question is perhaps more vague than is intended on stack overflow, so how about this? Please answer with one book or web site and a brief description. Then people can vote up their favourites. ANSWER: It will take some training and some time to learn the style needed to develop maintainable code. Coming from Java/C#/C++, you probably have a good idea of good software architecture. Now you just need to learn the peculiarities of LabView and the common pitfalls. For the basics, National Instruments offers training courses. See if your new employer can send you to a Basics I/II class to get your feet wet. They offer some online classes as well. Following classes, you can sign up to take tests for certification. Get an evaluation copy of Labview from National Instruments; they have a well maintained help file that you can dive right into, with example code included. Look at "Getting Started" and "LabVIEW Environment". You should be able to jump right in and become familiar with the dev environment pretty quickly. LabVIEW, being graphical is nice, but don't throw out your best practices from an application design point of view. It is common to end up with code looking like rainbow sphaghetti, or code that stretches several screens wide. Use subvi's and keep each vi with a specific purpose and function. The official NI support forums and knowledgebase are probably the best resources out there at the moment. Unofficial sites like Tutorials in G have a subset of the information found on the official site and documentation, but still may be useful for cross reference if you get stuck. Edit: Basics I/II are designed to be accessible to users without prior software development experience. Depending on how you feel after using the evaluation version, you may be able to move directly into Intermediate I/II. NI has the course outlines available on their website as well, so you know what you're going to cover in each.
[ "reference", "labview" ]
8
5
2,636
10
0
2008-09-05T21:29:34.727000
2008-09-15T16:56:03.783000
46,933
46,946
Why doesn't inheritance work the way I think it should work?
I'm having some inheritance issues as I've got a group of inter-related abstract classes that need to all be overridden together to create a client implementation. Ideally I would like to do something like the following: abstract class Animal { public Leg GetLeg() {...} } abstract class Leg { } class Dog: Animal { public override DogLeg Leg() {...} } class DogLeg: Leg { } This would allow anyone using the Dog class to automatically get DogLegs and anyone using the Animal class to get Legs. The problem is that the overridden function has to have the same type as the base class so this will not compile. I don't see why it shouldn't though, since DogLeg is implicitly castable to Leg. I know there are plenty of ways around this, but I'm more curious why this isn't possible/implemented in C#. EDIT: I modified this somewhat, since I'm actually using properties instead of functions in my code. EDIT: I changed it back to functions, because the answer only applies to that situation (covariance on the value parameter of a property's set function shouldn't work). Sorry for the fluctuations! I realize it makes a lot of the answers seem irrelevant.
The short answer is that GetLeg is invariant in its return type. The long answer can be found here: Covariance and contravariance I'd like to add that while inheritance is usually the first abstraction tool that most developers pull out of their toolbox, it is almost always possible to use composition instead. Composition is slightly more work for the API developer, but makes the API more useful for its consumers.
Why doesn't inheritance work the way I think it should work? I'm having some inheritance issues as I've got a group of inter-related abstract classes that need to all be overridden together to create a client implementation. Ideally I would like to do something like the following: abstract class Animal { public Leg GetLeg() {...} } abstract class Leg { } class Dog: Animal { public override DogLeg Leg() {...} } class DogLeg: Leg { } This would allow anyone using the Dog class to automatically get DogLegs and anyone using the Animal class to get Legs. The problem is that the overridden function has to have the same type as the base class so this will not compile. I don't see why it shouldn't though, since DogLeg is implicitly castable to Leg. I know there are plenty of ways around this, but I'm more curious why this isn't possible/implemented in C#. EDIT: I modified this somewhat, since I'm actually using properties instead of functions in my code. EDIT: I changed it back to functions, because the answer only applies to that situation (covariance on the value parameter of a property's set function shouldn't work). Sorry for the fluctuations! I realize it makes a lot of the answers seem irrelevant.
TITLE: Why doesn't inheritance work the way I think it should work? QUESTION: I'm having some inheritance issues as I've got a group of inter-related abstract classes that need to all be overridden together to create a client implementation. Ideally I would like to do something like the following: abstract class Animal { public Leg GetLeg() {...} } abstract class Leg { } class Dog: Animal { public override DogLeg Leg() {...} } class DogLeg: Leg { } This would allow anyone using the Dog class to automatically get DogLegs and anyone using the Animal class to get Legs. The problem is that the overridden function has to have the same type as the base class so this will not compile. I don't see why it shouldn't though, since DogLeg is implicitly castable to Leg. I know there are plenty of ways around this, but I'm more curious why this isn't possible/implemented in C#. EDIT: I modified this somewhat, since I'm actually using properties instead of functions in my code. EDIT: I changed it back to functions, because the answer only applies to that situation (covariance on the value parameter of a property's set function shouldn't work). Sorry for the fluctuations! I realize it makes a lot of the answers seem irrelevant. ANSWER: The short answer is that GetLeg is invariant in its return type. The long answer can be found here: Covariance and contravariance I'd like to add that while inheritance is usually the first abstraction tool that most developers pull out of their toolbox, it is almost always possible to use composition instead. Composition is slightly more work for the API developer, but makes the API more useful for its consumers.
[ "c#", "oop", "inheritance", "covariance", "contravariance" ]
8
16
1,246
17
0
2008-09-05T21:31:08.183000
2008-09-05T21:37:40.180000
46,938
47,124
How do you convert an aspx or master page file to page and code behind?
I have a project where a.master page was created without a code behind page. Now I want to add a code behind page for this.master page and move the "in page" code to the code behind file. What is the best/easiest way to go about doing this? I'm using Visual Studio 2008.
Create new class file, name it yourmaster.master.cs (Visual Studio will automaticly group it with the.master) and move the code to it, reference it in your masterpage. Then rightclick on your project and click "Convert to Web Application" and Visual Studio will create the designer file.
How do you convert an aspx or master page file to page and code behind? I have a project where a.master page was created without a code behind page. Now I want to add a code behind page for this.master page and move the "in page" code to the code behind file. What is the best/easiest way to go about doing this? I'm using Visual Studio 2008.
TITLE: How do you convert an aspx or master page file to page and code behind? QUESTION: I have a project where a.master page was created without a code behind page. Now I want to add a code behind page for this.master page and move the "in page" code to the code behind file. What is the best/easiest way to go about doing this? I'm using Visual Studio 2008. ANSWER: Create new class file, name it yourmaster.master.cs (Visual Studio will automaticly group it with the.master) and move the code to it, reference it in your masterpage. Then rightclick on your project and click "Convert to Web Application" and Visual Studio will create the designer file.
[ "visual-studio-2008" ]
2
3
2,458
3
0
2008-09-05T21:33:48.163000
2008-09-06T00:15:29.757000
46,982
47,168
Javascript and CSS parsing performance
I am trying to improve the performance of a web application. I have metrics that I can use to optimize the time taken to return the main HTML page, but I'm concerned about the external CSS and JavaScript files that are included from these HTML pages. These are served statically, with HTTP Expires headers, but are shared between all the pages of the application. I'm concerned that the browser has to parse these CSS and JavaScript files for each page that is displayed and so having all the CSS and JavaScript for the site shared into common files will negatively affect performance. Should I be trying to split out these files so I link from each page to only the CSS and JavaScript needed for that page, or would I get little return for my efforts? Are there any tools that could help me generate metrics for this? ­­­­­­­­­­­­­­­­­­­­­­­­­­­
Context: While it's true that HTTP overhead is more significant than parsing JS and CSS, ignoring the impact of parsing on browser performance (even if you have less than a meg of JS) is a good way to get yourself in trouble. YSlow, Fiddler, and Firebug are not the best tools to monitor parsing speed. Unless they've been updated very recently, they don't separate the amount of time required to fetch JS over HTTP or load from cache versus the amount of time spent parsing the actual JS payload. Parse speed is slightly difficult to measure, but we've chased this metric a number of times on projects I've worked on and the impact on pageloads were significant even with ~500k of JS. Obviously the older browsers suffer the most...hopefully Chrome, TraceMonkey and the like help resolve this situation. Suggestion: Depending on the type of traffic you have at your site, it may be well worth your while to split up your JS payload so some large chunks of JS that will never be used on a the most popular pages are never sent down to the client. Of course, this means that when a new client hits a page where this JS is needed, you'll have to send it over the wire. However, it may well be the case that, say, 50% of your JS is never needed by 80% of your users due to your traffic patterns. If this is so, you should definitely user smaller, packaged JS payloads only on pages where the JS is necessary. Otherwise 80% of your users will suffer unnecessary JS parsing penalties on every single pageload. Bottom Line: It's difficult to find the proper balance of JS caching and smaller, packaged payloads, but depending on your traffic pattern it's definitely well worth considering a technique other than smashing all of your JS into every single pageload.
Javascript and CSS parsing performance I am trying to improve the performance of a web application. I have metrics that I can use to optimize the time taken to return the main HTML page, but I'm concerned about the external CSS and JavaScript files that are included from these HTML pages. These are served statically, with HTTP Expires headers, but are shared between all the pages of the application. I'm concerned that the browser has to parse these CSS and JavaScript files for each page that is displayed and so having all the CSS and JavaScript for the site shared into common files will negatively affect performance. Should I be trying to split out these files so I link from each page to only the CSS and JavaScript needed for that page, or would I get little return for my efforts? Are there any tools that could help me generate metrics for this? ­­­­­­­­­­­­­­­­­­­­­­­­­­­
TITLE: Javascript and CSS parsing performance QUESTION: I am trying to improve the performance of a web application. I have metrics that I can use to optimize the time taken to return the main HTML page, but I'm concerned about the external CSS and JavaScript files that are included from these HTML pages. These are served statically, with HTTP Expires headers, but are shared between all the pages of the application. I'm concerned that the browser has to parse these CSS and JavaScript files for each page that is displayed and so having all the CSS and JavaScript for the site shared into common files will negatively affect performance. Should I be trying to split out these files so I link from each page to only the CSS and JavaScript needed for that page, or would I get little return for my efforts? Are there any tools that could help me generate metrics for this? ­­­­­­­­­­­­­­­­­­­­­­­­­­­ ANSWER: Context: While it's true that HTTP overhead is more significant than parsing JS and CSS, ignoring the impact of parsing on browser performance (even if you have less than a meg of JS) is a good way to get yourself in trouble. YSlow, Fiddler, and Firebug are not the best tools to monitor parsing speed. Unless they've been updated very recently, they don't separate the amount of time required to fetch JS over HTTP or load from cache versus the amount of time spent parsing the actual JS payload. Parse speed is slightly difficult to measure, but we've chased this metric a number of times on projects I've worked on and the impact on pageloads were significant even with ~500k of JS. Obviously the older browsers suffer the most...hopefully Chrome, TraceMonkey and the like help resolve this situation. Suggestion: Depending on the type of traffic you have at your site, it may be well worth your while to split up your JS payload so some large chunks of JS that will never be used on a the most popular pages are never sent down to the client. Of course, this means that when a new client hits a page where this JS is needed, you'll have to send it over the wire. However, it may well be the case that, say, 50% of your JS is never needed by 80% of your users due to your traffic patterns. If this is so, you should definitely user smaller, packaged JS payloads only on pages where the JS is necessary. Otherwise 80% of your users will suffer unnecessary JS parsing penalties on every single pageload. Bottom Line: It's difficult to find the proper balance of JS caching and smaller, packaged payloads, but depending on your traffic pattern it's definitely well worth considering a technique other than smashing all of your JS into every single pageload.
[ "javascript", "css", "performance" ]
10
14
3,706
3
0
2008-09-05T22:04:39.680000
2008-09-06T01:37:14.507000
47,003
47,084
C# .NET + PostgreSQL
I'm looking at working on a project which uses C#.NET (sitting on a windows box) as the primary language and PostgreSQL as the backend database (backend is sitting on a linux box). I've heard that ODBC.NET allows for easy integration of these two components. Has anyone had experience actually setting C# and PostgreSQL up to work together? If so, do you have any suggestions about how to go about it, issues you've found, etc.?
I'm working with C# and Postgres using Npgsql2 component, and they work fast, I recommend you. You can download from https://github.com/npgsql/Npgsql/releases Note: If you want an application that works with any database you can use the DbProviderFactory class and make your queries using IDbConnection, IDbCommand, IDataReader and/or IDbTransaction interfaces.
C# .NET + PostgreSQL I'm looking at working on a project which uses C#.NET (sitting on a windows box) as the primary language and PostgreSQL as the backend database (backend is sitting on a linux box). I've heard that ODBC.NET allows for easy integration of these two components. Has anyone had experience actually setting C# and PostgreSQL up to work together? If so, do you have any suggestions about how to go about it, issues you've found, etc.?
TITLE: C# .NET + PostgreSQL QUESTION: I'm looking at working on a project which uses C#.NET (sitting on a windows box) as the primary language and PostgreSQL as the backend database (backend is sitting on a linux box). I've heard that ODBC.NET allows for easy integration of these two components. Has anyone had experience actually setting C# and PostgreSQL up to work together? If so, do you have any suggestions about how to go about it, issues you've found, etc.? ANSWER: I'm working with C# and Postgres using Npgsql2 component, and they work fast, I recommend you. You can download from https://github.com/npgsql/Npgsql/releases Note: If you want an application that works with any database you can use the DbProviderFactory class and make your queries using IDbConnection, IDbCommand, IDataReader and/or IDbTransaction interfaces.
[ "c#", ".net", "postgresql" ]
54
59
67,268
9
0
2008-09-05T22:27:21.717000
2008-09-05T23:33:26.020000
47,005
47,054
MySQL UTF/Unicode migration tips
Does anyone have any tips or gotcha moments to look out for when trying to migrate MySQL tables from the the default case-insenstive swedish or ascii charsets to utf-8? Some of the projects that I'm involved in are striving for better internationalization and the database is going to be a significant part of this change. Before we look to alter the database, we are going to convert each site to use UTF-8 character encoding (from least critical to most) to help ensure all input/output is using the same character set. Thanks for any help
Some hints: Your CHAR and VARCHAR columns will use up to 3 times more disk space. (You probably won't get much disk space grow for Swedish words.) Use SET NAMES utf8 before reading or writing to the database. If you don't this then you will get partially garbled characters.
MySQL UTF/Unicode migration tips Does anyone have any tips or gotcha moments to look out for when trying to migrate MySQL tables from the the default case-insenstive swedish or ascii charsets to utf-8? Some of the projects that I'm involved in are striving for better internationalization and the database is going to be a significant part of this change. Before we look to alter the database, we are going to convert each site to use UTF-8 character encoding (from least critical to most) to help ensure all input/output is using the same character set. Thanks for any help
TITLE: MySQL UTF/Unicode migration tips QUESTION: Does anyone have any tips or gotcha moments to look out for when trying to migrate MySQL tables from the the default case-insenstive swedish or ascii charsets to utf-8? Some of the projects that I'm involved in are striving for better internationalization and the database is going to be a significant part of this change. Before we look to alter the database, we are going to convert each site to use UTF-8 character encoding (from least critical to most) to help ensure all input/output is using the same character set. Thanks for any help ANSWER: Some hints: Your CHAR and VARCHAR columns will use up to 3 times more disk space. (You probably won't get much disk space grow for Swedish words.) Use SET NAMES utf8 before reading or writing to the database. If you don't this then you will get partially garbled characters.
[ "mysql", "unicode", "utf-8", "internationalization" ]
5
2
1,081
5
0
2008-09-05T22:32:26.773000
2008-09-05T23:10:20.210000
47,007
256,455
Determining the last changelist synced to in Perforce
A question that occasionally arises is what is the best way to determine the changelist that you last synced to in Perforce. This is often needed for things like injecting the changelist number into the revision info by the automatic build system.
I recommend the opposite for automatic build systems: you should first get the latest changelist from the server using: p4 changes -s submitted -m1 then sync to that change and record it in the revision info. The reason is as follows. Although Perforce recommends the following to determine the changelist to which the workspace is synced: p4 changes -m1 @clientname they note a few gotchas: This only works if you have not submitted anything from the workspace in question. It is also possible that a client workspace is not synced to any specific changelist. and there's an additional gotcha they don't mention: If the highest changelist to which the sync occured strictly deleted files from the workspace, the next-highest changelist will be reported (unless it, too, strictly deleted files). If you must sync first and record later, Perforce recommends running the following command to determine if you've been bit by the above gotchas; it should indicate nothing was synced or removed: p4 sync -n @changelist_number Note that this method doesn't work if a file is added in a changelist (n-1) and then deleted in the very next changelist (n). p4 changes -m1 @clientname and p4 changes...#have both return n-3 and p4 sync -n @n-3 will say "file(s) up-to-date."
Determining the last changelist synced to in Perforce A question that occasionally arises is what is the best way to determine the changelist that you last synced to in Perforce. This is often needed for things like injecting the changelist number into the revision info by the automatic build system.
TITLE: Determining the last changelist synced to in Perforce QUESTION: A question that occasionally arises is what is the best way to determine the changelist that you last synced to in Perforce. This is often needed for things like injecting the changelist number into the revision info by the automatic build system. ANSWER: I recommend the opposite for automatic build systems: you should first get the latest changelist from the server using: p4 changes -s submitted -m1 then sync to that change and record it in the revision info. The reason is as follows. Although Perforce recommends the following to determine the changelist to which the workspace is synced: p4 changes -m1 @clientname they note a few gotchas: This only works if you have not submitted anything from the workspace in question. It is also possible that a client workspace is not synced to any specific changelist. and there's an additional gotcha they don't mention: If the highest changelist to which the sync occured strictly deleted files from the workspace, the next-highest changelist will be reported (unless it, too, strictly deleted files). If you must sync first and record later, Perforce recommends running the following command to determine if you've been bit by the above gotchas; it should indicate nothing was synced or removed: p4 sync -n @changelist_number Note that this method doesn't work if a file is added in a changelist (n-1) and then deleted in the very next changelist (n). p4 changes -m1 @clientname and p4 changes...#have both return n-3 and p4 sync -n @n-3 will say "file(s) up-to-date."
[ "perforce" ]
124
97
92,639
10
0
2008-09-05T22:36:02.943000
2008-11-02T03:05:32.907000
47,022
47,098
"Phantom" directories in an SVN repository
I've somehow managed to get an SVN repository into a bad state. I've moved a directory and now I can't commit it in its new location. As far as svn status is concerned, the directory is unknown (the name of the directory is type ). $ svn status? type When I try to add the directory, the server says it already exists. $ svn add type svn: warning: 'type' is already under version control If I try to update the directory, it's gone again. $ svn update type svn: '.' is not under version control If I try to commit it, the server complains that it's old parent directory no longer exists. $ svn commit type -m "Moving type" svn: Commit failed (details follow): svn: '/prior/trunk/src/nyu/prior/cvc3/theorem_prover/expression' path not found To add to the mystery, the contents of the directory are marked as modified. $ svn status type A + type M + type/IntegerType.java M + type/BooleanType.java M + type/Type.java M + type/RationalRangeType.java M + type/RationalType.java M + type/IntegerRangeType.java If I try to update from within the directory, I get this. $ cd type $ svn update svn: Two top-level reports with no target Committing from within the directory gives the same path not found error as above. What's going on and how do I fix it? EDIT: @Rob Oxspring caught me out: I got too aggressive moving things around in Eclipse. UPDATE: I'm accepting @Rob Oxspring's answer of "don't do that/just start over" and taking his advice. I'd still be interested if anybody could tell me: (a) what the above error messages mean precisely and (b) how to actually fix the problem.
It looks to me like type was created by some Subversion-aware copy command, then moved into the current directory using a Subversion-unaware copy. In my experience, this sort of thing typically occurs when package refactoring operations have been chained together in Eclipse without commits in between. Typically, Subversion doesn't handle it well when you copy/move a locally copied/moved file or folder, although I think version 1.5 may handle it better. To avoid this in the future, commit between such steps. If you'd like to hide the intervening commits then I'd recommend doing the multi-step refactoring on a branch and then merging the changes back into the mainline in that single commit you were after. If it's not too much work, then I'd recommend getting back to a clean working copy and redoing your changes, committing after each step. If you're happy to lose the history, i.e. allowing the new IntegerType.java to not be linked at all to the old IntegerType.java, then you could take the approach suggested by BCS: Move your changed files into some temporary location, stripping out any.svn directories Update your working copy into a clean working state Copy your changes back to where you want them to be Commit the resulting working copy
"Phantom" directories in an SVN repository I've somehow managed to get an SVN repository into a bad state. I've moved a directory and now I can't commit it in its new location. As far as svn status is concerned, the directory is unknown (the name of the directory is type ). $ svn status? type When I try to add the directory, the server says it already exists. $ svn add type svn: warning: 'type' is already under version control If I try to update the directory, it's gone again. $ svn update type svn: '.' is not under version control If I try to commit it, the server complains that it's old parent directory no longer exists. $ svn commit type -m "Moving type" svn: Commit failed (details follow): svn: '/prior/trunk/src/nyu/prior/cvc3/theorem_prover/expression' path not found To add to the mystery, the contents of the directory are marked as modified. $ svn status type A + type M + type/IntegerType.java M + type/BooleanType.java M + type/Type.java M + type/RationalRangeType.java M + type/RationalType.java M + type/IntegerRangeType.java If I try to update from within the directory, I get this. $ cd type $ svn update svn: Two top-level reports with no target Committing from within the directory gives the same path not found error as above. What's going on and how do I fix it? EDIT: @Rob Oxspring caught me out: I got too aggressive moving things around in Eclipse. UPDATE: I'm accepting @Rob Oxspring's answer of "don't do that/just start over" and taking his advice. I'd still be interested if anybody could tell me: (a) what the above error messages mean precisely and (b) how to actually fix the problem.
TITLE: "Phantom" directories in an SVN repository QUESTION: I've somehow managed to get an SVN repository into a bad state. I've moved a directory and now I can't commit it in its new location. As far as svn status is concerned, the directory is unknown (the name of the directory is type ). $ svn status? type When I try to add the directory, the server says it already exists. $ svn add type svn: warning: 'type' is already under version control If I try to update the directory, it's gone again. $ svn update type svn: '.' is not under version control If I try to commit it, the server complains that it's old parent directory no longer exists. $ svn commit type -m "Moving type" svn: Commit failed (details follow): svn: '/prior/trunk/src/nyu/prior/cvc3/theorem_prover/expression' path not found To add to the mystery, the contents of the directory are marked as modified. $ svn status type A + type M + type/IntegerType.java M + type/BooleanType.java M + type/Type.java M + type/RationalRangeType.java M + type/RationalType.java M + type/IntegerRangeType.java If I try to update from within the directory, I get this. $ cd type $ svn update svn: Two top-level reports with no target Committing from within the directory gives the same path not found error as above. What's going on and how do I fix it? EDIT: @Rob Oxspring caught me out: I got too aggressive moving things around in Eclipse. UPDATE: I'm accepting @Rob Oxspring's answer of "don't do that/just start over" and taking his advice. I'd still be interested if anybody could tell me: (a) what the above error messages mean precisely and (b) how to actually fix the problem. ANSWER: It looks to me like type was created by some Subversion-aware copy command, then moved into the current directory using a Subversion-unaware copy. In my experience, this sort of thing typically occurs when package refactoring operations have been chained together in Eclipse without commits in between. Typically, Subversion doesn't handle it well when you copy/move a locally copied/moved file or folder, although I think version 1.5 may handle it better. To avoid this in the future, commit between such steps. If you'd like to hide the intervening commits then I'd recommend doing the multi-step refactoring on a branch and then merging the changes back into the mainline in that single commit you were after. If it's not too much work, then I'd recommend getting back to a clean working copy and redoing your changes, committing after each step. If you're happy to lose the history, i.e. allowing the new IntegerType.java to not be linked at all to the old IntegerType.java, then you could take the approach suggested by BCS: Move your changed files into some temporary location, stripping out any.svn directories Update your working copy into a clean working state Copy your changes back to where you want them to be Commit the resulting working copy
[ "svn" ]
21
14
11,980
7
0
2008-09-05T22:47:46.707000
2008-09-05T23:45:49.763000
47,045
47,049
Sprintf equivalent in Java
Printf got added to Java with the 1.5 release but I can't seem to find how to send the output to a string rather than a file (which is what sprintf does in C). Does anyone know how to do this?
// Store the formatted string in 'result' String result = String.format("%4d", i * j); // Write the result to standard output System.out.println( result ); See format and its syntax
Sprintf equivalent in Java Printf got added to Java with the 1.5 release but I can't seem to find how to send the output to a string rather than a file (which is what sprintf does in C). Does anyone know how to do this?
TITLE: Sprintf equivalent in Java QUESTION: Printf got added to Java with the 1.5 release but I can't seem to find how to send the output to a string rather than a file (which is what sprintf does in C). Does anyone know how to do this? ANSWER: // Store the formatted string in 'result' String result = String.format("%4d", i * j); // Write the result to standard output System.out.println( result ); See format and its syntax
[ "java", "string", "formatting" ]
309
522
226,443
5
0
2008-09-05T23:05:35.320000
2008-09-05T23:06:53.820000
47,066
47,071
"Getting" the path in Linux
I am writing a C program in Linux. Commands like execv() require a path in the form of a C string. Is there a command that will return the current path in the form of a C-style string?
getcwd(): SYNOPSIS #include char *getcwd(char *buf, size_t size); DESCRIPTION The getcwd() function shall place an absolute pathname of the current working directory in the array pointed to by buf, and return buf. The pathname copied to the array shall contain no components that are symbolic links. The size argument is the size in bytes of the character array pointed to by the buf argument. If buf is a null pointer, the behavior of getcwd() is unspecified. RETURN VALUE Upon successful completion, getcwd() shall return the buf argument. Otherwise, getcwd() shall return a null pointer and set errno to indicate the error. The contents of the array pointed to by buf are then undefined....
"Getting" the path in Linux I am writing a C program in Linux. Commands like execv() require a path in the form of a C string. Is there a command that will return the current path in the form of a C-style string?
TITLE: "Getting" the path in Linux QUESTION: I am writing a C program in Linux. Commands like execv() require a path in the form of a C string. Is there a command that will return the current path in the form of a C-style string? ANSWER: getcwd(): SYNOPSIS #include char *getcwd(char *buf, size_t size); DESCRIPTION The getcwd() function shall place an absolute pathname of the current working directory in the array pointed to by buf, and return buf. The pathname copied to the array shall contain no components that are symbolic links. The size argument is the size in bytes of the character array pointed to by the buf argument. If buf is a null pointer, the behavior of getcwd() is unspecified. RETURN VALUE Upon successful completion, getcwd() shall return the buf argument. Otherwise, getcwd() shall return a null pointer and set errno to indicate the error. The contents of the array pointed to by buf are then undefined....
[ "c", "linux", "operating-system" ]
4
11
5,515
5
0
2008-09-05T23:21:18.340000
2008-09-05T23:25:49.330000
47,078
3,988,952
Javascript tree views that support multiple item drag/drop
We are currently using the ExtJS tree view in an application - a requirement has arisen requiring a user to select multiple nodes (which the tree view supports currently through a pluggable selection model) - but you can not then drag the multiple selections to another part of the tree. Does anyone know of an ajax control (commercial or non-commercial) that supports multiple-selection drag / drop - or a example of enabling this functionality in ExtJS?
Got the same issue. I just found the solution:..new Ext.tree.TreePanel({... selModel: new Ext.tree.MultiSelectionModel()... })
Javascript tree views that support multiple item drag/drop We are currently using the ExtJS tree view in an application - a requirement has arisen requiring a user to select multiple nodes (which the tree view supports currently through a pluggable selection model) - but you can not then drag the multiple selections to another part of the tree. Does anyone know of an ajax control (commercial or non-commercial) that supports multiple-selection drag / drop - or a example of enabling this functionality in ExtJS?
TITLE: Javascript tree views that support multiple item drag/drop QUESTION: We are currently using the ExtJS tree view in an application - a requirement has arisen requiring a user to select multiple nodes (which the tree view supports currently through a pluggable selection model) - but you can not then drag the multiple selections to another part of the tree. Does anyone know of an ajax control (commercial or non-commercial) that supports multiple-selection drag / drop - or a example of enabling this functionality in ExtJS? ANSWER: Got the same issue. I just found the solution:..new Ext.tree.TreePanel({... selModel: new Ext.tree.MultiSelectionModel()... })
[ "javascript", "ajax", "treeview", "drag-and-drop", "extjs" ]
8
1
4,035
3
0
2008-09-05T23:28:54.813000
2010-10-21T15:09:27.023000
47,087
47,111
How do you prevent SQL injection in LAMP applications?
Here are a few possibilities to get the conversation started: Escape all input upon initialization. Escape each value, preferably when generating the SQL. The first solution is suboptimal, because you then need to unescape each value if you want to use it in anything other than SQL, like outputting it on a web page. The second solution makes much more sense, but manually escaping each value is a pain. I'm aware of prepared statements, however I find MySQLi cumbersome. Also, separating the query from the inputs concerns me, because although it's crucial to get the order correct it's easy to make a mistake, and thus write the wrong data to the wrong fields.
as @Rob Walker states, parameterized queries are your best bet. If you're using the latest and greatest PHP, I'd highly recommend taking a look at PDO (PHP Data Objects). This is a native database abstraction library that has support for a wide range of databases (including MySQL of course) as well as prepared statements with named parameters.
How do you prevent SQL injection in LAMP applications? Here are a few possibilities to get the conversation started: Escape all input upon initialization. Escape each value, preferably when generating the SQL. The first solution is suboptimal, because you then need to unescape each value if you want to use it in anything other than SQL, like outputting it on a web page. The second solution makes much more sense, but manually escaping each value is a pain. I'm aware of prepared statements, however I find MySQLi cumbersome. Also, separating the query from the inputs concerns me, because although it's crucial to get the order correct it's easy to make a mistake, and thus write the wrong data to the wrong fields.
TITLE: How do you prevent SQL injection in LAMP applications? QUESTION: Here are a few possibilities to get the conversation started: Escape all input upon initialization. Escape each value, preferably when generating the SQL. The first solution is suboptimal, because you then need to unescape each value if you want to use it in anything other than SQL, like outputting it on a web page. The second solution makes much more sense, but manually escaping each value is a pain. I'm aware of prepared statements, however I find MySQLi cumbersome. Also, separating the query from the inputs concerns me, because although it's crucial to get the order correct it's easy to make a mistake, and thus write the wrong data to the wrong fields. ANSWER: as @Rob Walker states, parameterized queries are your best bet. If you're using the latest and greatest PHP, I'd highly recommend taking a look at PDO (PHP Data Objects). This is a native database abstraction library that has support for a wide range of databases (including MySQL of course) as well as prepared statements with named parameters.
[ "php", "sql", "mysql", "lamp" ]
8
7
1,172
5
0
2008-09-05T23:34:31.897000
2008-09-06T00:04:10.500000
47,089
47,095
Best way in asp.net to force https for an entire site?
About 6 months ago I rolled out a site where every request needed to be over https. The only way at the time I could find to ensure that every request to a page was over https was to check it in the page load event. If the request was not over http I would response.redirect(" https://example.com ") Is there a better way -- ideally some setting in the web.config?
Please use HSTS (HTTP Strict Transport Security) from http://www.hanselman.com/blog/HowToEnableHTTPStrictTransportSecurityHSTSInIIS7.aspx Original Answer (replaced with the above on 4 December 2015) basically protected void Application_BeginRequest(Object sender, EventArgs e) { if (HttpContext.Current.Request.IsSecureConnection.Equals(false) && HttpContext.Current.Request.IsLocal.Equals(false)) { Response.Redirect("https://" + Request.ServerVariables["HTTP_HOST"] + HttpContext.Current.Request.RawUrl); } } that would go in the global.asax.cs (or global.asax.vb) i dont know of a way to specify it in the web.config
Best way in asp.net to force https for an entire site? About 6 months ago I rolled out a site where every request needed to be over https. The only way at the time I could find to ensure that every request to a page was over https was to check it in the page load event. If the request was not over http I would response.redirect(" https://example.com ") Is there a better way -- ideally some setting in the web.config?
TITLE: Best way in asp.net to force https for an entire site? QUESTION: About 6 months ago I rolled out a site where every request needed to be over https. The only way at the time I could find to ensure that every request to a page was over https was to check it in the page load event. If the request was not over http I would response.redirect(" https://example.com ") Is there a better way -- ideally some setting in the web.config? ANSWER: Please use HSTS (HTTP Strict Transport Security) from http://www.hanselman.com/blog/HowToEnableHTTPStrictTransportSecurityHSTSInIIS7.aspx Original Answer (replaced with the above on 4 December 2015) basically protected void Application_BeginRequest(Object sender, EventArgs e) { if (HttpContext.Current.Request.IsSecureConnection.Equals(false) && HttpContext.Current.Request.IsLocal.Equals(false)) { Response.Redirect("https://" + Request.ServerVariables["HTTP_HOST"] + HttpContext.Current.Request.RawUrl); } } that would go in the global.asax.cs (or global.asax.vb) i dont know of a way to specify it in the web.config
[ "c#", "asp.net", "vb.net", "webforms", "https" ]
212
275
207,360
16
0
2008-09-05T23:34:53.583000
2008-09-05T23:42:16.480000
47,144
47,147
Is there a way to ensure entire code block execution in a .NET thread?
In my C# program, I have a thread that represents a running test, which can be aborted by a click on a button labeled "Interrupt execution". In order for the thread (and therefore the test) to terminate in an elegant manner (and do some vital work beforehand), this button is enabled only in some well-defined moments, in which I catch ThreadAbortedException, do Thread.ResetAbort() and die beautifully (that is, the thread). The problem is that, in the time window in which aborting is possible, there are some tasks that need to be done from start to finish once initiated, and, so, I fear TAE. Locks don't provide a solution for this, and, although finally blocks do, I don't find it elegant to wrap important code in the following manner: try { } finally { // vital code } However, I didn't find any other solution. Is this another way to delay the interference of ThreadAbortException until the end of the block?
The situations under which a ThreadAbortException will be generated can be complex. A better option might be to ask why you are using ThreadAbortExceptions at all. A better pattern would be to simply use a flag to indicate to the running thread that it should abort, and then test the flag regularly while it is working. If it is set you can throw an exception at that point if you want. With this pattern you are totally in control of when the thread will act on the abort, and don't have to worry about the critical operations being interrupted.
Is there a way to ensure entire code block execution in a .NET thread? In my C# program, I have a thread that represents a running test, which can be aborted by a click on a button labeled "Interrupt execution". In order for the thread (and therefore the test) to terminate in an elegant manner (and do some vital work beforehand), this button is enabled only in some well-defined moments, in which I catch ThreadAbortedException, do Thread.ResetAbort() and die beautifully (that is, the thread). The problem is that, in the time window in which aborting is possible, there are some tasks that need to be done from start to finish once initiated, and, so, I fear TAE. Locks don't provide a solution for this, and, although finally blocks do, I don't find it elegant to wrap important code in the following manner: try { } finally { // vital code } However, I didn't find any other solution. Is this another way to delay the interference of ThreadAbortException until the end of the block?
TITLE: Is there a way to ensure entire code block execution in a .NET thread? QUESTION: In my C# program, I have a thread that represents a running test, which can be aborted by a click on a button labeled "Interrupt execution". In order for the thread (and therefore the test) to terminate in an elegant manner (and do some vital work beforehand), this button is enabled only in some well-defined moments, in which I catch ThreadAbortedException, do Thread.ResetAbort() and die beautifully (that is, the thread). The problem is that, in the time window in which aborting is possible, there are some tasks that need to be done from start to finish once initiated, and, so, I fear TAE. Locks don't provide a solution for this, and, although finally blocks do, I don't find it elegant to wrap important code in the following manner: try { } finally { // vital code } However, I didn't find any other solution. Is this another way to delay the interference of ThreadAbortException until the end of the block? ANSWER: The situations under which a ThreadAbortException will be generated can be complex. A better option might be to ask why you are using ThreadAbortExceptions at all. A better pattern would be to simply use a flag to indicate to the running thread that it should abort, and then test the flag regularly while it is working. If it is set you can throw an exception at that point if you want. With this pattern you are totally in control of when the thread will act on the abort, and don't have to worry about the critical operations being interrupted.
[ ".net", "multithreading" ]
3
5
605
2
0
2008-09-06T00:59:14.160000
2008-09-06T01:06:30.787000
47,163
47,209
How to set the order in subnodes of a tree structure
I have a tree representation of pages in a CMS application. I understand how to persist the tree in the database. However, I don't have a good way to: A) Reorder subpages under a particular parent page. B) Provide a UI implementation that allows the user to change the order. Any suggestions?
Changing the order itself will require you store some sort of ordering along with each page in the database. Just the current highest / lowest value +/- 1 would probably be a fine starting point. Once you've got that ordering in there, reordering becomes a case of swapping two values or changing the value for one page to be between two others (you could use floats I guess, but you may need to renumber if you split it too many times). Anyway, once you've got that, you need a UI. I've seen a very simple 'swap this with the one above/below' approach which can be a simple web link or an AJAX call. You could also present all the page values to the user and ask them to renumber them as they see fit. If you want to get fancy, JavaScript drag and drop might be a good approach. I've used ExtJS and Mootools as frameworks in this kind of area. If you don't need all the Extjs widgets, I'd say well away from it in future, and look at something like the Mootools Dynamic Sortables demo.
How to set the order in subnodes of a tree structure I have a tree representation of pages in a CMS application. I understand how to persist the tree in the database. However, I don't have a good way to: A) Reorder subpages under a particular parent page. B) Provide a UI implementation that allows the user to change the order. Any suggestions?
TITLE: How to set the order in subnodes of a tree structure QUESTION: I have a tree representation of pages in a CMS application. I understand how to persist the tree in the database. However, I don't have a good way to: A) Reorder subpages under a particular parent page. B) Provide a UI implementation that allows the user to change the order. Any suggestions? ANSWER: Changing the order itself will require you store some sort of ordering along with each page in the database. Just the current highest / lowest value +/- 1 would probably be a fine starting point. Once you've got that ordering in there, reordering becomes a case of swapping two values or changing the value for one page to be between two others (you could use floats I guess, but you may need to renumber if you split it too many times). Anyway, once you've got that, you need a UI. I've seen a very simple 'swap this with the one above/below' approach which can be a simple web link or an AJAX call. You could also present all the page values to the user and ask them to renumber them as they see fit. If you want to get fancy, JavaScript drag and drop might be a good approach. I've used ExtJS and Mootools as frameworks in this kind of area. If you don't need all the Extjs widgets, I'd say well away from it in future, and look at something like the Mootools Dynamic Sortables demo.
[ "treeview", "tree" ]
2
0
382
2
0
2008-09-06T01:24:19.543000
2008-09-06T02:45:33.407000
47,167
47,170
Do you know of any "best practice" or "what works" vi tutorial for programmers?
There are thousands of vi tutorials on the web, most of them generically listing all the commands. There are even videos on youtube which show basic functionality. But does anyone know of a vi tutorial which focuses on the needs of programmers? For example when I program in Perl with vi, moving to the "next paragraph" is meaningless. I want to know which commands seasoned vi users combine to e.g: copy everything inside of parentheses copy a function copy and paste a variable (e.g. 2yw) etc. I am sure there are lots of functions using multiple-file capability, and the maps, macros, reading in of files for template code, regular expression search, jumping to functions, perhaps minimal code completion, or other features that emulate what programmers have gotten used to in Visual Studio and Eclipse, etc.
A nice collection of vimtips. And the best Vim cheatsheet around.
Do you know of any "best practice" or "what works" vi tutorial for programmers? There are thousands of vi tutorials on the web, most of them generically listing all the commands. There are even videos on youtube which show basic functionality. But does anyone know of a vi tutorial which focuses on the needs of programmers? For example when I program in Perl with vi, moving to the "next paragraph" is meaningless. I want to know which commands seasoned vi users combine to e.g: copy everything inside of parentheses copy a function copy and paste a variable (e.g. 2yw) etc. I am sure there are lots of functions using multiple-file capability, and the maps, macros, reading in of files for template code, regular expression search, jumping to functions, perhaps minimal code completion, or other features that emulate what programmers have gotten used to in Visual Studio and Eclipse, etc.
TITLE: Do you know of any "best practice" or "what works" vi tutorial for programmers? QUESTION: There are thousands of vi tutorials on the web, most of them generically listing all the commands. There are even videos on youtube which show basic functionality. But does anyone know of a vi tutorial which focuses on the needs of programmers? For example when I program in Perl with vi, moving to the "next paragraph" is meaningless. I want to know which commands seasoned vi users combine to e.g: copy everything inside of parentheses copy a function copy and paste a variable (e.g. 2yw) etc. I am sure there are lots of functions using multiple-file capability, and the maps, macros, reading in of files for template code, regular expression search, jumping to functions, perhaps minimal code completion, or other features that emulate what programmers have gotten used to in Visual Studio and Eclipse, etc. ANSWER: A nice collection of vimtips. And the best Vim cheatsheet around.
[ "unix", "vim", "editor", "keyboard-shortcuts", "text-editor" ]
3
10
3,158
3
0
2008-09-06T01:31:37.390000
2008-09-06T01:37:59.933000
47,169
47,200
Is there an event that triggers if the number of ListViewItems in a ListView changes? (Windows Forms)
I'd like to enable/disable some other controls based on how many items are in my ListView control. I can't find any event that would do this, either on the ListView itself or on the ListViewItemCollection. Maybe there's a way to generically watch any collection in C# for changes? I'd be happy with other events too, even ones that sometimes fire when the items don't change, but for example the ControlAdded and Layout events didn't work:(.
@Domenic Not too sure, Never quite got that far in the thought process. Another solution might be to extend ListView, and when adding and removing stuff, instead of calling.items.add, and items.remove, you call your other functions. It would still be possible to add and remove without events being raised, but with a little code review to make sure.items.add and.items.remove weren't called directly, it could work out quite well. Here's a little example. I only showed 1 Add function, but there are 6 you would have to implement, if you wanted to have use of all the available add functions. There's also.AddRange, and.Clear that you might want to take a look at. Public Class MonitoredListView Inherits ListView Public Event ItemAdded() Public Event ItemRemoved() Public Sub New() MyBase.New() End Sub Public Function AddItem(ByVal Text As String) As ListViewItem RaiseEvent ItemAdded() MyBase.Items.Add(Text) End Function Public Sub RemoveItem(ByVal Item As ListViewItem) RaiseEvent ItemRemoved() MyBase.Items.Remove(Item) End Sub End Class
Is there an event that triggers if the number of ListViewItems in a ListView changes? (Windows Forms) I'd like to enable/disable some other controls based on how many items are in my ListView control. I can't find any event that would do this, either on the ListView itself or on the ListViewItemCollection. Maybe there's a way to generically watch any collection in C# for changes? I'd be happy with other events too, even ones that sometimes fire when the items don't change, but for example the ControlAdded and Layout events didn't work:(.
TITLE: Is there an event that triggers if the number of ListViewItems in a ListView changes? (Windows Forms) QUESTION: I'd like to enable/disable some other controls based on how many items are in my ListView control. I can't find any event that would do this, either on the ListView itself or on the ListViewItemCollection. Maybe there's a way to generically watch any collection in C# for changes? I'd be happy with other events too, even ones that sometimes fire when the items don't change, but for example the ControlAdded and Layout events didn't work:(. ANSWER: @Domenic Not too sure, Never quite got that far in the thought process. Another solution might be to extend ListView, and when adding and removing stuff, instead of calling.items.add, and items.remove, you call your other functions. It would still be possible to add and remove without events being raised, but with a little code review to make sure.items.add and.items.remove weren't called directly, it could work out quite well. Here's a little example. I only showed 1 Add function, but there are 6 you would have to implement, if you wanted to have use of all the available add functions. There's also.AddRange, and.Clear that you might want to take a look at. Public Class MonitoredListView Inherits ListView Public Event ItemAdded() Public Event ItemRemoved() Public Sub New() MyBase.New() End Sub Public Function AddItem(ByVal Text As String) As ListViewItem RaiseEvent ItemAdded() MyBase.Items.Add(Text) End Function Public Sub RemoveItem(ByVal Item As ListViewItem) RaiseEvent ItemRemoved() MyBase.Items.Remove(Item) End Sub End Class
[ "winforms", "events", "listview" ]
3
2
6,843
3
0
2008-09-06T01:37:52.553000
2008-09-06T02:26:58.253000
47,177
47,290
How do I monitor the computer's CPU, memory, and disk usage in Java?
I would like to monitor the following system information in Java: Current CPU usage** (percent) Available memory* (free/total) Available disk space (free/total) *Note that I mean overall memory available to the whole system, not just the JVM. I'm looking for a cross-platform solution (Linux, Mac, and Windows) that doesn't rely on my own code calling external programs or using JNI. Although these are viable options, I would prefer not to maintain OS-specific code myself if someone already has a better solution. If there's a free library out there that does this in a reliable, cross-platform manner, that would be great (even if it makes external calls or uses native code itself). Any suggestions are much appreciated. To clarify, I would like to get the current CPU usage for the whole system, not just the Java process(es). The SIGAR API provides all the functionality I'm looking for in one package, so it's the best answer to my question so far. However, due it being licensed under the GPL, I cannot use it for my original purpose (a closed source, commercial product). It's possible that Hyperic may license SIGAR for commercial use, but I haven't looked into it. For my GPL projects, I will definitely consider SIGAR in the future. For my current needs, I'm leaning towards the following: For CPU usage, OperatingSystemMXBean.getSystemLoadAverage() / OperatingSystemMXBean.getAvailableProcessors() (load average per cpu) For memory, OperatingSystemMXBean.getTotalPhysicalMemorySize() and OperatingSystemMXBean.getFreePhysicalMemorySize() For disk space, File.getTotalSpace() and File.getUsableSpace() Limitations: The getSystemLoadAverage() and disk space querying methods are only available under Java 6. Also, some JMX functionality may not be available to all platforms (i.e. it's been reported that getSystemLoadAverage() returns -1 on Windows). Although originally licensed under GPL, it has been changed to Apache 2.0, which can generally be used for closed source, commercial products.
Along the lines of what I mentioned in this post. I recommend you use the SIGAR API. I use the SIGAR API in one of my own applications and it is great. You'll find it is stable, well supported, and full of useful examples. It is open-source with a GPL 2 Apache 2.0 license. Check it out. I have a feeling it will meet your needs. Using Java and the Sigar API you can get Memory, CPU, Disk, Load-Average, Network Interface info and metrics, Process Table information, Route info, etc.
How do I monitor the computer's CPU, memory, and disk usage in Java? I would like to monitor the following system information in Java: Current CPU usage** (percent) Available memory* (free/total) Available disk space (free/total) *Note that I mean overall memory available to the whole system, not just the JVM. I'm looking for a cross-platform solution (Linux, Mac, and Windows) that doesn't rely on my own code calling external programs or using JNI. Although these are viable options, I would prefer not to maintain OS-specific code myself if someone already has a better solution. If there's a free library out there that does this in a reliable, cross-platform manner, that would be great (even if it makes external calls or uses native code itself). Any suggestions are much appreciated. To clarify, I would like to get the current CPU usage for the whole system, not just the Java process(es). The SIGAR API provides all the functionality I'm looking for in one package, so it's the best answer to my question so far. However, due it being licensed under the GPL, I cannot use it for my original purpose (a closed source, commercial product). It's possible that Hyperic may license SIGAR for commercial use, but I haven't looked into it. For my GPL projects, I will definitely consider SIGAR in the future. For my current needs, I'm leaning towards the following: For CPU usage, OperatingSystemMXBean.getSystemLoadAverage() / OperatingSystemMXBean.getAvailableProcessors() (load average per cpu) For memory, OperatingSystemMXBean.getTotalPhysicalMemorySize() and OperatingSystemMXBean.getFreePhysicalMemorySize() For disk space, File.getTotalSpace() and File.getUsableSpace() Limitations: The getSystemLoadAverage() and disk space querying methods are only available under Java 6. Also, some JMX functionality may not be available to all platforms (i.e. it's been reported that getSystemLoadAverage() returns -1 on Windows). Although originally licensed under GPL, it has been changed to Apache 2.0, which can generally be used for closed source, commercial products.
TITLE: How do I monitor the computer's CPU, memory, and disk usage in Java? QUESTION: I would like to monitor the following system information in Java: Current CPU usage** (percent) Available memory* (free/total) Available disk space (free/total) *Note that I mean overall memory available to the whole system, not just the JVM. I'm looking for a cross-platform solution (Linux, Mac, and Windows) that doesn't rely on my own code calling external programs or using JNI. Although these are viable options, I would prefer not to maintain OS-specific code myself if someone already has a better solution. If there's a free library out there that does this in a reliable, cross-platform manner, that would be great (even if it makes external calls or uses native code itself). Any suggestions are much appreciated. To clarify, I would like to get the current CPU usage for the whole system, not just the Java process(es). The SIGAR API provides all the functionality I'm looking for in one package, so it's the best answer to my question so far. However, due it being licensed under the GPL, I cannot use it for my original purpose (a closed source, commercial product). It's possible that Hyperic may license SIGAR for commercial use, but I haven't looked into it. For my GPL projects, I will definitely consider SIGAR in the future. For my current needs, I'm leaning towards the following: For CPU usage, OperatingSystemMXBean.getSystemLoadAverage() / OperatingSystemMXBean.getAvailableProcessors() (load average per cpu) For memory, OperatingSystemMXBean.getTotalPhysicalMemorySize() and OperatingSystemMXBean.getFreePhysicalMemorySize() For disk space, File.getTotalSpace() and File.getUsableSpace() Limitations: The getSystemLoadAverage() and disk space querying methods are only available under Java 6. Also, some JMX functionality may not be available to all platforms (i.e. it's been reported that getSystemLoadAverage() returns -1 on Windows). Although originally licensed under GPL, it has been changed to Apache 2.0, which can generally be used for closed source, commercial products. ANSWER: Along the lines of what I mentioned in this post. I recommend you use the SIGAR API. I use the SIGAR API in one of my own applications and it is great. You'll find it is stable, well supported, and full of useful examples. It is open-source with a GPL 2 Apache 2.0 license. Check it out. I have a feeling it will meet your needs. Using Java and the Sigar API you can get Memory, CPU, Disk, Load-Average, Network Interface info and metrics, Process Table information, Route info, etc.
[ "java", "memory", "cross-platform", "cpu", "diskspace" ]
206
68
327,104
12
0
2008-09-06T01:44:06.563000
2008-09-06T06:31:29.400000
47,198
47,208
Which Version of Python to Use for Maximum Compatibility
If I was going to start an open source project using Python what version should I use to ensure that the vast majority of users can use it on their system? I'm the kind of person who quickly jumps to the next version (which I'll do when Python 3 comes out) but many people may be more conservative if their current version seems to be working fine. What version would hit the sweet spot but still allow me to enjoy the newest and coolest language enhancements?
As python is in kind of an transition phase towards python 3 with breaking backward compatibility I don't think it is a good idea to go python 3 only. Based on the time line there will be at least one or two following releases of the 2.x series after 2.6/3.0 in october. Beside not having python 3 available on your target platforms, it will take some time until important external python libraries will be ported and usable on python 3. So as Matthew suggests staying at 2.4/2.5 and keeping the transition plan to python 3 in mind is a solid choice.
Which Version of Python to Use for Maximum Compatibility If I was going to start an open source project using Python what version should I use to ensure that the vast majority of users can use it on their system? I'm the kind of person who quickly jumps to the next version (which I'll do when Python 3 comes out) but many people may be more conservative if their current version seems to be working fine. What version would hit the sweet spot but still allow me to enjoy the newest and coolest language enhancements?
TITLE: Which Version of Python to Use for Maximum Compatibility QUESTION: If I was going to start an open source project using Python what version should I use to ensure that the vast majority of users can use it on their system? I'm the kind of person who quickly jumps to the next version (which I'll do when Python 3 comes out) but many people may be more conservative if their current version seems to be working fine. What version would hit the sweet spot but still allow me to enjoy the newest and coolest language enhancements? ANSWER: As python is in kind of an transition phase towards python 3 with breaking backward compatibility I don't think it is a good idea to go python 3 only. Based on the time line there will be at least one or two following releases of the 2.x series after 2.6/3.0 in october. Beside not having python 3 available on your target platforms, it will take some time until important external python libraries will be ported and usable on python 3. So as Matthew suggests staying at 2.4/2.5 and keeping the transition plan to python 3 in mind is a solid choice.
[ "python", "compatibility" ]
15
6
3,841
6
0
2008-09-06T02:22:50.683000
2008-09-06T02:44:31.067000
47,203
47,214
SQL Server, nvarchar(MAX) or ntext, image or varbinary?
When should I choose one or the other? What are the implications regarding space and (full-text) indexing? BTW: I'm currently using SQL Server 2005 planing to upgrade to 2008 in the following months. Thanks
The new (max) fields make it a lot easier to deal with the data from.NET code. With varbinary(max), you simply set the value of a SqlParameter to a byte array and you are done. WIth the image field, you need to write a few hundred lines of code to stream the data into and out of the field. Also, the image/text fields are deprecated in favor of varbinary(max) and varchar(max), and future versions of Sql Server will discontinue support for them.
SQL Server, nvarchar(MAX) or ntext, image or varbinary? When should I choose one or the other? What are the implications regarding space and (full-text) indexing? BTW: I'm currently using SQL Server 2005 planing to upgrade to 2008 in the following months. Thanks
TITLE: SQL Server, nvarchar(MAX) or ntext, image or varbinary? QUESTION: When should I choose one or the other? What are the implications regarding space and (full-text) indexing? BTW: I'm currently using SQL Server 2005 planing to upgrade to 2008 in the following months. Thanks ANSWER: The new (max) fields make it a lot easier to deal with the data from.NET code. With varbinary(max), you simply set the value of a SqlParameter to a byte array and you are done. WIth the image field, you need to write a few hundred lines of code to stream the data into and out of the field. Also, the image/text fields are deprecated in favor of varbinary(max) and varchar(max), and future versions of Sql Server will discontinue support for them.
[ "sql-server", "t-sql", "sql-server-2005", "sql-types" ]
9
13
6,512
2
0
2008-09-06T02:31:47.010000
2008-09-06T02:50:26.140000
47,207
47,304
Django: Print url of view without hardcoding the url
Can i print out a url /admin/manage/products/add of a certain view in a template? Here is the rule i want to create a link for (r'^manage/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}), I would like to have /manage/products/add in a template without hardcoding it. How can i do this? Edit: I am not using the default admin (well, i am but it is at another url), this is my own
You can use get_absolute_url, but that will only work for a particular object. Since your object hasn't been created yet, it won't work in this case. You want to use named URL patterns. Here's a quick intro: Change the line in your urls.py to: (r'^manage/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}, "create-product"), Then, in your template you use this to display the URL: {% url create-product %} If you're using Django 1.5 or higher you need this: {% url 'create-product' %} You can do some more powerful things with named URL patterns, they're very handy. Note that they are only in the development version (and also 1.0).
Django: Print url of view without hardcoding the url Can i print out a url /admin/manage/products/add of a certain view in a template? Here is the rule i want to create a link for (r'^manage/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}), I would like to have /manage/products/add in a template without hardcoding it. How can i do this? Edit: I am not using the default admin (well, i am but it is at another url), this is my own
TITLE: Django: Print url of view without hardcoding the url QUESTION: Can i print out a url /admin/manage/products/add of a certain view in a template? Here is the rule i want to create a link for (r'^manage/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}), I would like to have /manage/products/add in a template without hardcoding it. How can i do this? Edit: I am not using the default admin (well, i am but it is at another url), this is my own ANSWER: You can use get_absolute_url, but that will only work for a particular object. Since your object hasn't been created yet, it won't work in this case. You want to use named URL patterns. Here's a quick intro: Change the line in your urls.py to: (r'^manage/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}, "create-product"), Then, in your template you use this to display the URL: {% url create-product %} If you're using Django 1.5 or higher you need this: {% url 'create-product' %} You can do some more powerful things with named URL patterns, they're very handy. Note that they are only in the development version (and also 1.0).
[ "python", "django" ]
10
17
8,182
3
0
2008-09-06T02:42:49.357000
2008-09-06T07:22:52.583000
47,210
54,788
Is there a good Fogbugz client for Mac OS X?
And/or: do I need one? I've recently started using FogBugz for my hobby projects, and I'm very happy with things so far. Having read more about it, especially the evidence-based scheduling, I'd like to start using it for my PhD as well. (Heh; something tells me my supervisors won't be opening tickets for me, though.) Last night I stumbled onto TimePost, which looks like a tidy app that doesn't do much but could be a real bonus to logging my time in FogBugz effectively. I tried looking around for similar apps but came up a little empty-handed. Are there any other FogBugz clients that you've used and recommend for Mac OS X? Or are you happy with the web interface?
The official answer is no, there is not a dedicated Mac client, other than Safari:) There's a command line version that runs on Linux, Windows, and Mac. There are also plans for an iPhone version although I'm not technically supposed to announce features before they are done or even spec'd so pretend I didn't say that.
Is there a good Fogbugz client for Mac OS X? And/or: do I need one? I've recently started using FogBugz for my hobby projects, and I'm very happy with things so far. Having read more about it, especially the evidence-based scheduling, I'd like to start using it for my PhD as well. (Heh; something tells me my supervisors won't be opening tickets for me, though.) Last night I stumbled onto TimePost, which looks like a tidy app that doesn't do much but could be a real bonus to logging my time in FogBugz effectively. I tried looking around for similar apps but came up a little empty-handed. Are there any other FogBugz clients that you've used and recommend for Mac OS X? Or are you happy with the web interface?
TITLE: Is there a good Fogbugz client for Mac OS X? QUESTION: And/or: do I need one? I've recently started using FogBugz for my hobby projects, and I'm very happy with things so far. Having read more about it, especially the evidence-based scheduling, I'd like to start using it for my PhD as well. (Heh; something tells me my supervisors won't be opening tickets for me, though.) Last night I stumbled onto TimePost, which looks like a tidy app that doesn't do much but could be a real bonus to logging my time in FogBugz effectively. I tried looking around for similar apps but came up a little empty-handed. Are there any other FogBugz clients that you've used and recommend for Mac OS X? Or are you happy with the web interface? ANSWER: The official answer is no, there is not a dedicated Mac client, other than Safari:) There's a command line version that runs on Linux, Windows, and Mac. There are also plans for an iPhone version although I'm not technically supposed to announce features before they are done or even spec'd so pretend I didn't say that.
[ "macos", "fogbugz" ]
7
9
2,519
12
0
2008-09-06T02:47:19.110000
2008-09-10T17:35:29.800000
47,217
1,905,709
"Cannot change DataType of a column once it has data" error in Visual Studio 2005 DataSet Designer
I've got a DataSet in VisualStudio 2005. I need to change the datatype of a column in one of the datatables from System.Int32 to System.Decimal. When I try to change the datatype in the DataSet Designer I receive the following error: Property value is not valid. Cannot change DataType of a column once it has data. From my understanding, this should be changing the datatype in the schema for the DataSet. I don't see how there can be any data to cause this error. Does any one have any ideas?
I get the same error but only for columns with its DefaultValue set to any value (except the default ). So the way I got around this issue was: Column DefaultValue: Type in Save and reopen the dataset
"Cannot change DataType of a column once it has data" error in Visual Studio 2005 DataSet Designer I've got a DataSet in VisualStudio 2005. I need to change the datatype of a column in one of the datatables from System.Int32 to System.Decimal. When I try to change the datatype in the DataSet Designer I receive the following error: Property value is not valid. Cannot change DataType of a column once it has data. From my understanding, this should be changing the datatype in the schema for the DataSet. I don't see how there can be any data to cause this error. Does any one have any ideas?
TITLE: "Cannot change DataType of a column once it has data" error in Visual Studio 2005 DataSet Designer QUESTION: I've got a DataSet in VisualStudio 2005. I need to change the datatype of a column in one of the datatables from System.Int32 to System.Decimal. When I try to change the datatype in the DataSet Designer I receive the following error: Property value is not valid. Cannot change DataType of a column once it has data. From my understanding, this should be changing the datatype in the schema for the DataSet. I don't see how there can be any data to cause this error. Does any one have any ideas? ANSWER: I get the same error but only for columns with its DefaultValue set to any value (except the default ). So the way I got around this issue was: Column DefaultValue: Type in Save and reopen the dataset
[ "visual-studio", "dataset", ".net-2.0", "dataset-designer" ]
24
46
25,836
6
0
2008-09-06T02:55:19.513000
2009-12-15T07:17:51.557000
47,225
67,198
How would you migrate hundreds of MS Access databases to a central service?
We have literally 100's of Access databases floating around the network. Some with light usage and some with quite heavy usage, and some no usage whatsoever. What we would like to do is centralise these databases onto a managed database and retain as much as possible of the reports and forms within them. The benefits of doing this would be to have some sort of usage tracking, and also the ability to pay more attention to some of the important decentralised data that is stored in these apps. There is no real constraints on RDBMS (Oracle, MS SQL server) or the stack it would run on (LAMP, ASP.net, Java) and there obviously won't be a silver bullet for this. We would like something that can remove the initial grunt work in an automated fashion.
Upsizing an Access application is no magic bullet. It may be that some things will be faster, but some types of operations will be real dogs. That means that an upsized app has to be tested thoroughly and performance bottlenecks addressed, usually by moving the data retrieval logic server-side (views, stored procedures, passthrough queries). It's not really an answer to the question, though. I don't think there is any automated answer to the problem. Indeed, I'd say this is a people problem and not a programming problem at all. Somebody has to survey the network and determine ownership of all the Access databases and then interview the users to find out what's in use and what's not. Then each app should be evaluated as to whether or not it should be folded into an Enterprise-wide data store/app, or whether its original implementation as a small app for a few users was the better approach. That's not the answer you want to hear, but it's the right answer precisely because it's a people/management problem, not a programming task.
How would you migrate hundreds of MS Access databases to a central service? We have literally 100's of Access databases floating around the network. Some with light usage and some with quite heavy usage, and some no usage whatsoever. What we would like to do is centralise these databases onto a managed database and retain as much as possible of the reports and forms within them. The benefits of doing this would be to have some sort of usage tracking, and also the ability to pay more attention to some of the important decentralised data that is stored in these apps. There is no real constraints on RDBMS (Oracle, MS SQL server) or the stack it would run on (LAMP, ASP.net, Java) and there obviously won't be a silver bullet for this. We would like something that can remove the initial grunt work in an automated fashion.
TITLE: How would you migrate hundreds of MS Access databases to a central service? QUESTION: We have literally 100's of Access databases floating around the network. Some with light usage and some with quite heavy usage, and some no usage whatsoever. What we would like to do is centralise these databases onto a managed database and retain as much as possible of the reports and forms within them. The benefits of doing this would be to have some sort of usage tracking, and also the ability to pay more attention to some of the important decentralised data that is stored in these apps. There is no real constraints on RDBMS (Oracle, MS SQL server) or the stack it would run on (LAMP, ASP.net, Java) and there obviously won't be a silver bullet for this. We would like something that can remove the initial grunt work in an automated fashion. ANSWER: Upsizing an Access application is no magic bullet. It may be that some things will be faster, but some types of operations will be real dogs. That means that an upsized app has to be tested thoroughly and performance bottlenecks addressed, usually by moving the data retrieval logic server-side (views, stored procedures, passthrough queries). It's not really an answer to the question, though. I don't think there is any automated answer to the problem. Indeed, I'd say this is a people problem and not a programming problem at all. Somebody has to survey the network and determine ownership of all the Access databases and then interview the users to find out what's in use and what's not. Then each app should be evaluated as to whether or not it should be folded into an Enterprise-wide data store/app, or whether its original implementation as a small app for a few users was the better approach. That's not the answer you want to hear, but it's the right answer precisely because it's a people/management problem, not a programming task.
[ "sql-server", "oracle", "ms-access" ]
5
3
522
5
0
2008-09-06T03:25:44.697000
2008-09-15T21:31:07.430000
47,235
47,245
What is the .MSPX file extension?
I've noticed a lot of Microsoft sites have the *.MSPX extension. While I'm very familiar with ASP.NET, I've not seen this extension before. Does anyone know what this identifies?
A few internet searches led me to http://www.microsoft.com/backstage/bkst_column_46.mspx, but it was a dead link. Fortunately, it was archived on the Wayback Machine and you can read it here: http://web.archive.org/web/20040803120105/http://www.microsoft.com/backstage/bkst_column_46.mspx The.MSPX extension is part of the "Microsoft Network Project," which according to the article above, is designed to give Microsoft's sites a consistent look-and-feel worldwide, as well as keep the design of the site seperate from the content. Here's the gist of the article: The presentation framework includes a custom Web handler built in ASP.NET. Pages that use the presentation framework have the.mspx filename extension, which is registered in Microsoft Internet Information Services (IIS) on the Web servers. When one of the Microsoft.com Web servers receives a request for an.mspx page, this custom Web handler intercepts that call and passes it to the framework for processing. The framework first checks to see whether the result is cached. If it is, the page is rendered immediately. If the page is not cached, the handler looks up the URL for that page in the table of contents provided by the site owner (see below) to determine where the XML content for the page is stored. The framework then checks to see if the XML is cached, and either returns the cached content or retrieves the XML from the data store identified in the table of contents file. Within the file that holds the content for the page, XML tags identify the content template to be used. The framework retrieves the appropriate template and uses a series of XSLTs to assemble the page, including the masthead, the footer, and the primary navigational column, finally rendering the content within the content pane.
What is the .MSPX file extension? I've noticed a lot of Microsoft sites have the *.MSPX extension. While I'm very familiar with ASP.NET, I've not seen this extension before. Does anyone know what this identifies?
TITLE: What is the .MSPX file extension? QUESTION: I've noticed a lot of Microsoft sites have the *.MSPX extension. While I'm very familiar with ASP.NET, I've not seen this extension before. Does anyone know what this identifies? ANSWER: A few internet searches led me to http://www.microsoft.com/backstage/bkst_column_46.mspx, but it was a dead link. Fortunately, it was archived on the Wayback Machine and you can read it here: http://web.archive.org/web/20040803120105/http://www.microsoft.com/backstage/bkst_column_46.mspx The.MSPX extension is part of the "Microsoft Network Project," which according to the article above, is designed to give Microsoft's sites a consistent look-and-feel worldwide, as well as keep the design of the site seperate from the content. Here's the gist of the article: The presentation framework includes a custom Web handler built in ASP.NET. Pages that use the presentation framework have the.mspx filename extension, which is registered in Microsoft Internet Information Services (IIS) on the Web servers. When one of the Microsoft.com Web servers receives a request for an.mspx page, this custom Web handler intercepts that call and passes it to the framework for processing. The framework first checks to see whether the result is cached. If it is, the page is rendered immediately. If the page is not cached, the handler looks up the URL for that page in the table of contents provided by the site owner (see below) to determine where the XML content for the page is stored. The framework then checks to see if the XML is cached, and either returns the cached content or retrieves the XML from the data store identified in the table of contents file. Within the file that holds the content for the page, XML tags identify the content template to be used. The framework retrieves the appropriate template and uses a series of XSLTs to assemble the page, including the masthead, the footer, and the primary navigational column, finally rendering the content within the content pane.
[ "asp.net", ".net", "file-extension" ]
8
9
5,267
4
0
2008-09-06T03:44:23.297000
2008-09-06T04:06:24.037000
47,239
47,273
How can I generate database tables from C# classes?
Does anyone know a way to auto-generate database tables for a given class? I'm not looking for an entire persistence layer - I already have a data access solution I'm using, but I suddenly have to store a lot of information from a large number of classes and I really don't want to have to create all these tables by hand. For example, given the following class: class Foo { private string property1; public string Property1 { get { return property1; } set { property1 = value; } } private int property2; public int Property2 { get { return property2; } set { property2 = value; } } } I'd expect the following SQL: CREATE TABLE Foo ( Property1 VARCHAR(500), Property2 INT ) I'm also wondering how you could handle complex types. For example, in the previously cited class, if we changed that to be: class Foo { private string property1; public string Property1 { get { return property1; } set { property1 = value; } } private System.Management.ManagementObject property2; public System.Management.ManagementObject Property2 { get { return property2; } set { property2 = value; } } } How could I handle this? I've looked at trying to auto-generate the database scripts by myself using reflection to enumerate through each class' properties, but it's clunky and the complex data types have me stumped.
It's really late, and I only spent about 10 minutes on this, so its extremely sloppy, however it does work and will give you a good jumping off point: using System; using System.Collections.Generic; using System.Text; using System.Reflection; namespace TableGenerator { class Program { static void Main(string[] args) { List tables = new List (); // Pass assembly name via argument Assembly a = Assembly.LoadFile(args[0]); Type[] types = a.GetTypes(); // Get Types in the assembly. foreach (Type t in types) { TableClass tc = new TableClass(t); tables.Add(tc); } // Create SQL for each table foreach (TableClass table in tables) { Console.WriteLine(table.CreateTableScript()); Console.WriteLine(); } // Total Hacked way to find FK relationships! Too lazy to fix right now foreach (TableClass table in tables) { foreach (KeyValuePair field in table.Fields) { foreach (TableClass t2 in tables) { if (field.Value.Name == t2.ClassName) { // We have a FK Relationship! Console.WriteLine("GO"); Console.WriteLine("ALTER TABLE " + table.ClassName + " WITH NOCHECK"); Console.WriteLine("ADD CONSTRAINT FK_" + field.Key + " FOREIGN KEY (" + field.Key + ") REFERENCES " + t2.ClassName + "(ID)"); Console.WriteLine("GO"); } } } } } } public class TableClass { private List > _fieldInfo = new List >(); private string _className = String.Empty; private Dictionary dataMapper { get { // Add the rest of your CLR Types to SQL Types mapping here Dictionary dataMapper = new Dictionary (); dataMapper.Add(typeof(int), "BIGINT"); dataMapper.Add(typeof(string), "NVARCHAR(500)"); dataMapper.Add(typeof(bool), "BIT"); dataMapper.Add(typeof(DateTime), "DATETIME"); dataMapper.Add(typeof(float), "FLOAT"); dataMapper.Add(typeof(decimal), "DECIMAL(18,0)"); dataMapper.Add(typeof(Guid), "UNIQUEIDENTIFIER"); return dataMapper; } } public List > Fields { get { return this._fieldInfo; } set { this._fieldInfo = value; } } public string ClassName { get { return this._className; } set { this._className = value; } } public TableClass(Type t) { this._className = t.Name; foreach (PropertyInfo p in t.GetProperties()) { KeyValuePair field = new KeyValuePair (p.Name, p.PropertyType); this.Fields.Add(field); } } public string CreateTableScript() { System.Text.StringBuilder script = new StringBuilder(); script.AppendLine("CREATE TABLE " + this.ClassName); script.AppendLine("("); script.AppendLine("\t ID BIGINT,"); for (int i = 0; i < this.Fields.Count; i++) { KeyValuePair field = this.Fields[i]; if (dataMapper.ContainsKey(field.Value)) { script.Append("\t " + field.Key + " " + dataMapper[field.Value]); } else { // Complex Type? script.Append("\t " + field.Key + " BIGINT"); } if (i!= this.Fields.Count - 1) { script.Append(","); } script.Append(Environment.NewLine); } script.AppendLine(")"); return script.ToString(); } } } I put these classes in an assembly to test it: public class FakeDataClass { public int AnInt { get; set; } public string AString { get; set; } public float AFloat { get; set; } public FKClass AFKReference { get; set; } } public class FKClass { public int AFKInt { get; set; } } And it generated the following SQL: CREATE TABLE FakeDataClass ( ID BIGINT, AnInt BIGINT, AString NVARCHAR(255), AFloat FLOAT, AFKReference BIGINT ) CREATE TABLE FKClass ( ID BIGINT, AFKInt BIGINT ) GO ALTER TABLE FakeDataClass WITH NOCHECK ADD CONSTRAINT FK_AFKReference FOREIGN KEY (AFKReference) REFERENCES FKClass(ID) GO Some further thoughts...I'd consider adding an attribute such as [SqlTable] to your classes, that way it only generates tables for the classes you want. Also, this can be cleaned up a ton, bugs fixed, optimized (the FK Checker is a joke) etc etc...Just to get you started.
How can I generate database tables from C# classes? Does anyone know a way to auto-generate database tables for a given class? I'm not looking for an entire persistence layer - I already have a data access solution I'm using, but I suddenly have to store a lot of information from a large number of classes and I really don't want to have to create all these tables by hand. For example, given the following class: class Foo { private string property1; public string Property1 { get { return property1; } set { property1 = value; } } private int property2; public int Property2 { get { return property2; } set { property2 = value; } } } I'd expect the following SQL: CREATE TABLE Foo ( Property1 VARCHAR(500), Property2 INT ) I'm also wondering how you could handle complex types. For example, in the previously cited class, if we changed that to be: class Foo { private string property1; public string Property1 { get { return property1; } set { property1 = value; } } private System.Management.ManagementObject property2; public System.Management.ManagementObject Property2 { get { return property2; } set { property2 = value; } } } How could I handle this? I've looked at trying to auto-generate the database scripts by myself using reflection to enumerate through each class' properties, but it's clunky and the complex data types have me stumped.
TITLE: How can I generate database tables from C# classes? QUESTION: Does anyone know a way to auto-generate database tables for a given class? I'm not looking for an entire persistence layer - I already have a data access solution I'm using, but I suddenly have to store a lot of information from a large number of classes and I really don't want to have to create all these tables by hand. For example, given the following class: class Foo { private string property1; public string Property1 { get { return property1; } set { property1 = value; } } private int property2; public int Property2 { get { return property2; } set { property2 = value; } } } I'd expect the following SQL: CREATE TABLE Foo ( Property1 VARCHAR(500), Property2 INT ) I'm also wondering how you could handle complex types. For example, in the previously cited class, if we changed that to be: class Foo { private string property1; public string Property1 { get { return property1; } set { property1 = value; } } private System.Management.ManagementObject property2; public System.Management.ManagementObject Property2 { get { return property2; } set { property2 = value; } } } How could I handle this? I've looked at trying to auto-generate the database scripts by myself using reflection to enumerate through each class' properties, but it's clunky and the complex data types have me stumped. ANSWER: It's really late, and I only spent about 10 minutes on this, so its extremely sloppy, however it does work and will give you a good jumping off point: using System; using System.Collections.Generic; using System.Text; using System.Reflection; namespace TableGenerator { class Program { static void Main(string[] args) { List tables = new List (); // Pass assembly name via argument Assembly a = Assembly.LoadFile(args[0]); Type[] types = a.GetTypes(); // Get Types in the assembly. foreach (Type t in types) { TableClass tc = new TableClass(t); tables.Add(tc); } // Create SQL for each table foreach (TableClass table in tables) { Console.WriteLine(table.CreateTableScript()); Console.WriteLine(); } // Total Hacked way to find FK relationships! Too lazy to fix right now foreach (TableClass table in tables) { foreach (KeyValuePair field in table.Fields) { foreach (TableClass t2 in tables) { if (field.Value.Name == t2.ClassName) { // We have a FK Relationship! Console.WriteLine("GO"); Console.WriteLine("ALTER TABLE " + table.ClassName + " WITH NOCHECK"); Console.WriteLine("ADD CONSTRAINT FK_" + field.Key + " FOREIGN KEY (" + field.Key + ") REFERENCES " + t2.ClassName + "(ID)"); Console.WriteLine("GO"); } } } } } } public class TableClass { private List > _fieldInfo = new List >(); private string _className = String.Empty; private Dictionary dataMapper { get { // Add the rest of your CLR Types to SQL Types mapping here Dictionary dataMapper = new Dictionary (); dataMapper.Add(typeof(int), "BIGINT"); dataMapper.Add(typeof(string), "NVARCHAR(500)"); dataMapper.Add(typeof(bool), "BIT"); dataMapper.Add(typeof(DateTime), "DATETIME"); dataMapper.Add(typeof(float), "FLOAT"); dataMapper.Add(typeof(decimal), "DECIMAL(18,0)"); dataMapper.Add(typeof(Guid), "UNIQUEIDENTIFIER"); return dataMapper; } } public List > Fields { get { return this._fieldInfo; } set { this._fieldInfo = value; } } public string ClassName { get { return this._className; } set { this._className = value; } } public TableClass(Type t) { this._className = t.Name; foreach (PropertyInfo p in t.GetProperties()) { KeyValuePair field = new KeyValuePair (p.Name, p.PropertyType); this.Fields.Add(field); } } public string CreateTableScript() { System.Text.StringBuilder script = new StringBuilder(); script.AppendLine("CREATE TABLE " + this.ClassName); script.AppendLine("("); script.AppendLine("\t ID BIGINT,"); for (int i = 0; i < this.Fields.Count; i++) { KeyValuePair field = this.Fields[i]; if (dataMapper.ContainsKey(field.Value)) { script.Append("\t " + field.Key + " " + dataMapper[field.Value]); } else { // Complex Type? script.Append("\t " + field.Key + " BIGINT"); } if (i!= this.Fields.Count - 1) { script.Append(","); } script.Append(Environment.NewLine); } script.AppendLine(")"); return script.ToString(); } } } I put these classes in an assembly to test it: public class FakeDataClass { public int AnInt { get; set; } public string AString { get; set; } public float AFloat { get; set; } public FKClass AFKReference { get; set; } } public class FKClass { public int AFKInt { get; set; } } And it generated the following SQL: CREATE TABLE FakeDataClass ( ID BIGINT, AnInt BIGINT, AString NVARCHAR(255), AFloat FLOAT, AFKReference BIGINT ) CREATE TABLE FKClass ( ID BIGINT, AFKInt BIGINT ) GO ALTER TABLE FakeDataClass WITH NOCHECK ADD CONSTRAINT FK_AFKReference FOREIGN KEY (AFKReference) REFERENCES FKClass(ID) GO Some further thoughts...I'd consider adding an attribute such as [SqlTable] to your classes, that way it only generates tables for the classes you want. Also, this can be cleaned up a ton, bugs fixed, optimized (the FK Checker is a joke) etc etc...Just to get you started.
[ "c#", "code-generation", "data-access" ]
66
112
85,307
12
0
2008-09-06T03:52:15.180000
2008-09-06T05:50:12.650000
47,253
47,266
How do you set up a Python WSGI server under IIS?
I work in a Windows environment and would prefer to deploy code to IIS. At the same time I would like to code in Python. Having read that IIS can run fastCGI application, I went to the IIS site where it describes in detail how to get PHP up and running but not much about anything else. Does anyone have experience getting a Python framework running under IIS using something other that plain old CGI? If so can you explain to direct me to some instructions on setting this up?
There shouldn't be any need to use FastCGI. There exists a ISAPI extension for WSGI.
How do you set up a Python WSGI server under IIS? I work in a Windows environment and would prefer to deploy code to IIS. At the same time I would like to code in Python. Having read that IIS can run fastCGI application, I went to the IIS site where it describes in detail how to get PHP up and running but not much about anything else. Does anyone have experience getting a Python framework running under IIS using something other that plain old CGI? If so can you explain to direct me to some instructions on setting this up?
TITLE: How do you set up a Python WSGI server under IIS? QUESTION: I work in a Windows environment and would prefer to deploy code to IIS. At the same time I would like to code in Python. Having read that IIS can run fastCGI application, I went to the IIS site where it describes in detail how to get PHP up and running but not much about anything else. Does anyone have experience getting a Python framework running under IIS using something other that plain old CGI? If so can you explain to direct me to some instructions on setting this up? ANSWER: There shouldn't be any need to use FastCGI. There exists a ISAPI extension for WSGI.
[ "python", "iis", "deployment", "windows-server", "iis-modules" ]
31
24
16,575
3
0
2008-09-06T04:26:49.807000
2008-09-06T05:32:39.557000
47,262
47,263
Storing Windows passwords
I'm writing (in C# with.NET 3.5) an administrative application which will poll multiple Windows systems for various bits of data. In many cases it will use WMI, but in some cases it may need to read remote registry or remotely execute some command or script on the polled system. This polling will happen at repeating intervals - usually nightly, but can be configured to happen more (or less) frequently. So the poll could happen as often as every 10 minutes or as rarely as once a month. It needs to happen in an automated way, without any human intervention. These functions will require admin-level access to the polled systems. Now, I expect that in most use cases, there will be a domain, and the polling application can run as a service with Domain Admin (or equivalent) privileges, which means I do not have to worry about storing passwords - the admin setting up the app will define the service's username/password via standard Windows mechanisms. But there's always a few black sheep out there. The program may run in nondomain environments, or in cases where some polled systems are not members of the domain. In these cases we will have to define a username and password, store them securely, then invoke this user/pass pair at the time we poll that system. So keep in mind - in this case the program being written is the user who sends password to the authenticating system. I am not sure whether I will need to use a reversible hash which I then decrypt to plaintext at time of use, or if there is some Windows mechanism which would allow me to store and then reuse the hash only. Obviously the second mechanism is preferable; I'd like my program to either never know the password's plaintext value, or know it for the shortest amount of time possible. I need suggestions for smart and secure ways to accomplish this. Thanks for looking!
The answer is here: How to store passwords in Winforms application?
Storing Windows passwords I'm writing (in C# with.NET 3.5) an administrative application which will poll multiple Windows systems for various bits of data. In many cases it will use WMI, but in some cases it may need to read remote registry or remotely execute some command or script on the polled system. This polling will happen at repeating intervals - usually nightly, but can be configured to happen more (or less) frequently. So the poll could happen as often as every 10 minutes or as rarely as once a month. It needs to happen in an automated way, without any human intervention. These functions will require admin-level access to the polled systems. Now, I expect that in most use cases, there will be a domain, and the polling application can run as a service with Domain Admin (or equivalent) privileges, which means I do not have to worry about storing passwords - the admin setting up the app will define the service's username/password via standard Windows mechanisms. But there's always a few black sheep out there. The program may run in nondomain environments, or in cases where some polled systems are not members of the domain. In these cases we will have to define a username and password, store them securely, then invoke this user/pass pair at the time we poll that system. So keep in mind - in this case the program being written is the user who sends password to the authenticating system. I am not sure whether I will need to use a reversible hash which I then decrypt to plaintext at time of use, or if there is some Windows mechanism which would allow me to store and then reuse the hash only. Obviously the second mechanism is preferable; I'd like my program to either never know the password's plaintext value, or know it for the shortest amount of time possible. I need suggestions for smart and secure ways to accomplish this. Thanks for looking!
TITLE: Storing Windows passwords QUESTION: I'm writing (in C# with.NET 3.5) an administrative application which will poll multiple Windows systems for various bits of data. In many cases it will use WMI, but in some cases it may need to read remote registry or remotely execute some command or script on the polled system. This polling will happen at repeating intervals - usually nightly, but can be configured to happen more (or less) frequently. So the poll could happen as often as every 10 minutes or as rarely as once a month. It needs to happen in an automated way, without any human intervention. These functions will require admin-level access to the polled systems. Now, I expect that in most use cases, there will be a domain, and the polling application can run as a service with Domain Admin (or equivalent) privileges, which means I do not have to worry about storing passwords - the admin setting up the app will define the service's username/password via standard Windows mechanisms. But there's always a few black sheep out there. The program may run in nondomain environments, or in cases where some polled systems are not members of the domain. In these cases we will have to define a username and password, store them securely, then invoke this user/pass pair at the time we poll that system. So keep in mind - in this case the program being written is the user who sends password to the authenticating system. I am not sure whether I will need to use a reversible hash which I then decrypt to plaintext at time of use, or if there is some Windows mechanism which would allow me to store and then reuse the hash only. Obviously the second mechanism is preferable; I'd like my program to either never know the password's plaintext value, or know it for the shortest amount of time possible. I need suggestions for smart and secure ways to accomplish this. Thanks for looking! ANSWER: The answer is here: How to store passwords in Winforms application?
[ "c#", ".net", "windows", "security", "passwords" ]
10
6
1,510
2
0
2008-09-06T05:02:37.430000
2008-09-06T05:15:23.403000
47,279
845,174
Are there any good oracle podcasts?
Are there any good oracle podcasts around? The only ones I've found is produced by oracle corp, and as such are little more than advertising pieces pushing their technology of the moment. I'm specifically interested in Database technologies.
Oracle Podcast Center Green Enterprise Podcasts Host: Paul Salinger, VP Marketing Listen to discussions with customers, partners, and Oracle green experts, exploring topics that can help Oracle customers better understand how Oracle products can support their sustainability initiatives and enable a green enterprise. Oracle AppCasts Host: Cliff Godwin, SVP, Applications Technology Tune into "Live with Cliff" to hear from application technology experts, product and industry experts, and customers about what's saving Oracle customers time and money when using Oracle E-Business Suite, PeopleSoft, and JD Edwards applications. Oracle Customer SuccessCasts Tune into Oracle Customer SuccessCasts, where customers describe how Oracle helps them to run their businesses more successfully. Oracle Database Podcasts Tune into this podcast series to get the latest information on Oracle Database from Oracle technical experts. Oracle Fusion Middleware Radio Host: Rick Schultz, VP, Product Marketing for Oracle Fusion Middleware & Security Products Tune into this podcast series about Oracle Fusion Middleware to hear about Oracle's middleware product strategy and explore what middleware means to your business—growth, agility, insight, and reduced risk. Oracle Magazine Feature Casts Tune into conversations with Oracle Magazine editors, authors, and Oracle subject matter experts about featured articles in Oracle Magazine. Go beyond print with additional insight into Oracle products, technologies, customers, and more. Oracle PartnerNetwork (OPN) PartnerCast Tune in and learn how to grow your business with Oracle, exclusively for Oracle PartnerNetwork members. Oracle Technology Network Arch2Arch Podcast Host: Bob Rhubart, Manager, Architect Community, OTN Listen in as architects and other experts from across the Oracle community discuss the topics, tools, and technologies that drive the evolution of software architecture. Oracle Technology Network TechCasts Host: Justin Kestelyn, OTN Editor-in-Chief Tune into "fireside chats" with experts about new tools, technologies, and trends in application development. Oracle@Work Through Oracle@Work Video Podcasts you'll learn how Oracle customers from aerospace and automotive to travel and television address business and technical issues with the latest Oracle technology and applications solutions. Oracle@Works play like short television news magazine pieces shot on location, world wide. See Oracle customers in action, first hand, with Oracle@Work Video Podcasts. Profit Online Executive Briefing Audiocasts Every month, Profit Online presents conversations with Oracle executives, customers, and partners, discussing developments in their businesses and trends in their industries. Tune into and stay up to date on how IT and business leaders are expanding into new markets, improving business processes, and creating the future of the enterprise. Reference: Oracle Podcasts
Are there any good oracle podcasts? Are there any good oracle podcasts around? The only ones I've found is produced by oracle corp, and as such are little more than advertising pieces pushing their technology of the moment. I'm specifically interested in Database technologies.
TITLE: Are there any good oracle podcasts? QUESTION: Are there any good oracle podcasts around? The only ones I've found is produced by oracle corp, and as such are little more than advertising pieces pushing their technology of the moment. I'm specifically interested in Database technologies. ANSWER: Oracle Podcast Center Green Enterprise Podcasts Host: Paul Salinger, VP Marketing Listen to discussions with customers, partners, and Oracle green experts, exploring topics that can help Oracle customers better understand how Oracle products can support their sustainability initiatives and enable a green enterprise. Oracle AppCasts Host: Cliff Godwin, SVP, Applications Technology Tune into "Live with Cliff" to hear from application technology experts, product and industry experts, and customers about what's saving Oracle customers time and money when using Oracle E-Business Suite, PeopleSoft, and JD Edwards applications. Oracle Customer SuccessCasts Tune into Oracle Customer SuccessCasts, where customers describe how Oracle helps them to run their businesses more successfully. Oracle Database Podcasts Tune into this podcast series to get the latest information on Oracle Database from Oracle technical experts. Oracle Fusion Middleware Radio Host: Rick Schultz, VP, Product Marketing for Oracle Fusion Middleware & Security Products Tune into this podcast series about Oracle Fusion Middleware to hear about Oracle's middleware product strategy and explore what middleware means to your business—growth, agility, insight, and reduced risk. Oracle Magazine Feature Casts Tune into conversations with Oracle Magazine editors, authors, and Oracle subject matter experts about featured articles in Oracle Magazine. Go beyond print with additional insight into Oracle products, technologies, customers, and more. Oracle PartnerNetwork (OPN) PartnerCast Tune in and learn how to grow your business with Oracle, exclusively for Oracle PartnerNetwork members. Oracle Technology Network Arch2Arch Podcast Host: Bob Rhubart, Manager, Architect Community, OTN Listen in as architects and other experts from across the Oracle community discuss the topics, tools, and technologies that drive the evolution of software architecture. Oracle Technology Network TechCasts Host: Justin Kestelyn, OTN Editor-in-Chief Tune into "fireside chats" with experts about new tools, technologies, and trends in application development. Oracle@Work Through Oracle@Work Video Podcasts you'll learn how Oracle customers from aerospace and automotive to travel and television address business and technical issues with the latest Oracle technology and applications solutions. Oracle@Works play like short television news magazine pieces shot on location, world wide. See Oracle customers in action, first hand, with Oracle@Work Video Podcasts. Profit Online Executive Briefing Audiocasts Every month, Profit Online presents conversations with Oracle executives, customers, and partners, discussing developments in their businesses and trends in their industries. Tune into and stay up to date on how IT and business leaders are expanding into new markets, improving business processes, and creating the future of the enterprise. Reference: Oracle Podcasts
[ "oracle", "podcast" ]
5
3
2,613
3
0
2008-09-06T06:19:13.110000
2009-05-10T11:44:58.167000
47,309
47,678
GODI installation issue
I'm trying to install GODI on linux (Ubuntu). It's a library management tool for the ocaml language. I've actually installed this before --twice, but awhile ago-- with no issues --that I can remember-- but this time I just can't figure out what I'm missing. $./bootstrap --prefix /home/nlucaroni/godi $./bootstrap_stage2.: 1: godi_confdir: not found Error: Command fails with code 2: /bin/sh Failure! I had added the proper directories to the path, and they show up with a quick echo $path, and godi_confdir reported as being: /home/nlucaroni/godi/etc (...and the directory exists, with the godi.conf file present). So, I can't figure out why./bootstrap_stage2 isn't working.
Hey Chris, I just figured it out. Silly mistake. It was just a permission issue, running everything from /tmp/ worked fine --well after enabling GODI_BASEPKG_PCRE in godi.conf. I had been running it from my home directory, you forget simple things like that at 3:00am. -- Actually I'm having another problem. Installing conf-opengl-6: GODI can't seen to find the GL/gl.h file, though I can --you can see that it is Checking the suggestion. > ===> Configuring for conf-opengl-6 > Checking the suggestion > Include=/usr/include/GL/gl.h Library=/ > Checking /usr: > Include=/usr/include/GL/gl.h Library=/usr/lib/ > Checking /usr: > Include=/usr/local/include/GL/gl.h Library=/usr/local/lib/ > Checking /usr/local: > Include=/usr/local/include/GL/gl.h Library=/usr/local/lib/ > Exception: Failure "Cannot find library". > Error: Exec error: File /home/nlucaroni/godi/build/conf/conf-opengl/./../../mk/bsd.pkg.mk, line 1022: Command returned with non-zero exit code > Error: Exec error: File /home/nlucaroni/godi/build/conf/conf-opengl/./../../mk/bsd.pkg.mk, line 1375: Command returned with non-zero exit code ### Error: Command fails with code 1: godi_console edit - Ok, this is fixed too... just needed GLU, weird since the test configuration option said everything was fine.
GODI installation issue I'm trying to install GODI on linux (Ubuntu). It's a library management tool for the ocaml language. I've actually installed this before --twice, but awhile ago-- with no issues --that I can remember-- but this time I just can't figure out what I'm missing. $./bootstrap --prefix /home/nlucaroni/godi $./bootstrap_stage2.: 1: godi_confdir: not found Error: Command fails with code 2: /bin/sh Failure! I had added the proper directories to the path, and they show up with a quick echo $path, and godi_confdir reported as being: /home/nlucaroni/godi/etc (...and the directory exists, with the godi.conf file present). So, I can't figure out why./bootstrap_stage2 isn't working.
TITLE: GODI installation issue QUESTION: I'm trying to install GODI on linux (Ubuntu). It's a library management tool for the ocaml language. I've actually installed this before --twice, but awhile ago-- with no issues --that I can remember-- but this time I just can't figure out what I'm missing. $./bootstrap --prefix /home/nlucaroni/godi $./bootstrap_stage2.: 1: godi_confdir: not found Error: Command fails with code 2: /bin/sh Failure! I had added the proper directories to the path, and they show up with a quick echo $path, and godi_confdir reported as being: /home/nlucaroni/godi/etc (...and the directory exists, with the godi.conf file present). So, I can't figure out why./bootstrap_stage2 isn't working. ANSWER: Hey Chris, I just figured it out. Silly mistake. It was just a permission issue, running everything from /tmp/ worked fine --well after enabling GODI_BASEPKG_PCRE in godi.conf. I had been running it from my home directory, you forget simple things like that at 3:00am. -- Actually I'm having another problem. Installing conf-opengl-6: GODI can't seen to find the GL/gl.h file, though I can --you can see that it is Checking the suggestion. > ===> Configuring for conf-opengl-6 > Checking the suggestion > Include=/usr/include/GL/gl.h Library=/ > Checking /usr: > Include=/usr/include/GL/gl.h Library=/usr/lib/ > Checking /usr: > Include=/usr/local/include/GL/gl.h Library=/usr/local/lib/ > Checking /usr/local: > Include=/usr/local/include/GL/gl.h Library=/usr/local/lib/ > Exception: Failure "Cannot find library". > Error: Exec error: File /home/nlucaroni/godi/build/conf/conf-opengl/./../../mk/bsd.pkg.mk, line 1022: Command returned with non-zero exit code > Error: Exec error: File /home/nlucaroni/godi/build/conf/conf-opengl/./../../mk/bsd.pkg.mk, line 1375: Command returned with non-zero exit code ### Error: Command fails with code 1: godi_console edit - Ok, this is fixed too... just needed GLU, weird since the test configuration option said everything was fine.
[ "linux", "ocaml", "godi" ]
7
1
891
2
0
2008-09-06T07:36:31.817000
2008-09-06T17:15:42.517000
47,323
47,325
Top tips for secure web applications
I am looking for easy steps that are simple and effective in making a web application more secure. What are your top tips for secure web applications, and what kind of attack will they stop?
Microsoft Technet has en excellent article: Ten Tips for Designing, Building, and Deploying More Secure Web Applications Here are the topics for the tips answered in that article: Never Directly Trust User Input Services Should Have Neither System nor Administrator Access Follow SQL Server Best Practices Protect the Assets Include Auditing, Logging, and Reporting Features Analyze the Source Code Deploy Components Using Defense in Depth Turn Off In-Depth Error Messages for End Users Know the 10 Laws of Security Administration Have a Security Incident Response Plan
Top tips for secure web applications I am looking for easy steps that are simple and effective in making a web application more secure. What are your top tips for secure web applications, and what kind of attack will they stop?
TITLE: Top tips for secure web applications QUESTION: I am looking for easy steps that are simple and effective in making a web application more secure. What are your top tips for secure web applications, and what kind of attack will they stop? ANSWER: Microsoft Technet has en excellent article: Ten Tips for Designing, Building, and Deploying More Secure Web Applications Here are the topics for the tips answered in that article: Never Directly Trust User Input Services Should Have Neither System nor Administrator Access Follow SQL Server Best Practices Protect the Assets Include Auditing, Logging, and Reporting Features Analyze the Source Code Deploy Components Using Defense in Depth Turn Off In-Depth Error Messages for End Users Know the 10 Laws of Security Administration Have a Security Incident Response Plan
[ "security", "web-applications" ]
12
10
2,092
6
0
2008-09-06T08:21:35.283000
2008-09-06T08:23:56.867000
47,329
47,344
UserControl rendering: write link to current page?
I'm implementing a custom control and in this control I need to write a bunch of links to the current page, each one with a different query parameter. I need to keep existing query string intact, and add (or modify the value of ) an extra query item (eg. "page"): "Default.aspx?page=1" "Default.aspx?page=2" "Default.aspx?someother=true&page=2" etc. Is there a simple helper method that I can use in the Render method... uhmm... like: Page.ClientScript.SomeURLBuilderMethodHere(this,"page","1"); Page.ClientScript.SomeURLBuilderMethodHere(this,"page","2"); That will take care of generating a correct URL, maintain existing query string items and not create duplicates eg. page=1&page=2&page=3? Rolling up my own seems like such an unappealing task.
I'm afraid I don't know of any built-in method for this, we use this method that takes the querystring and sets parameters /// /// Set a parameter value in a query string. If the parameter is not found in the passed in query string, /// it is added to the end of the query string /// /// The query string that is to be manipulated /// The name of the parameter /// The value that the parameter is to be set to /// The query string with the parameter set to the new value. public static string SetParameter(string queryString, string paramName, object paramValue) { //create the regex //match paramname=* //string regex = String.Format(@"{0}=[^&]*", paramName); string regex = @"([&?]{0,1})" + String.Format(@"({0}=[^&]*)", paramName); RegexOptions options = RegexOptions.RightToLeft; // Querystring has parameters... if (Regex.IsMatch(queryString, regex, options)) { queryString = Regex.Replace(queryString, regex, String.Format("$1{0}={1}", paramName, paramValue)); } else { // If no querystring just return the Parameter Key/Value if (queryString == String.Empty) { return String.Format("{0}={1}", paramName, paramValue); } else { // Append the new parameter key/value to the end of querystring queryString = String.Format("{0}&{1}={2}", queryString, paramName, paramValue); } } return queryString; } Obviously you could use the QueryString NameValueCollection property of the URI object to make looking up the values easier, but we wanted to be able to parse any querystring.
UserControl rendering: write link to current page? I'm implementing a custom control and in this control I need to write a bunch of links to the current page, each one with a different query parameter. I need to keep existing query string intact, and add (or modify the value of ) an extra query item (eg. "page"): "Default.aspx?page=1" "Default.aspx?page=2" "Default.aspx?someother=true&page=2" etc. Is there a simple helper method that I can use in the Render method... uhmm... like: Page.ClientScript.SomeURLBuilderMethodHere(this,"page","1"); Page.ClientScript.SomeURLBuilderMethodHere(this,"page","2"); That will take care of generating a correct URL, maintain existing query string items and not create duplicates eg. page=1&page=2&page=3? Rolling up my own seems like such an unappealing task.
TITLE: UserControl rendering: write link to current page? QUESTION: I'm implementing a custom control and in this control I need to write a bunch of links to the current page, each one with a different query parameter. I need to keep existing query string intact, and add (or modify the value of ) an extra query item (eg. "page"): "Default.aspx?page=1" "Default.aspx?page=2" "Default.aspx?someother=true&page=2" etc. Is there a simple helper method that I can use in the Render method... uhmm... like: Page.ClientScript.SomeURLBuilderMethodHere(this,"page","1"); Page.ClientScript.SomeURLBuilderMethodHere(this,"page","2"); That will take care of generating a correct URL, maintain existing query string items and not create duplicates eg. page=1&page=2&page=3? Rolling up my own seems like such an unappealing task. ANSWER: I'm afraid I don't know of any built-in method for this, we use this method that takes the querystring and sets parameters /// /// Set a parameter value in a query string. If the parameter is not found in the passed in query string, /// it is added to the end of the query string /// /// The query string that is to be manipulated /// The name of the parameter /// The value that the parameter is to be set to /// The query string with the parameter set to the new value. public static string SetParameter(string queryString, string paramName, object paramValue) { //create the regex //match paramname=* //string regex = String.Format(@"{0}=[^&]*", paramName); string regex = @"([&?]{0,1})" + String.Format(@"({0}=[^&]*)", paramName); RegexOptions options = RegexOptions.RightToLeft; // Querystring has parameters... if (Regex.IsMatch(queryString, regex, options)) { queryString = Regex.Replace(queryString, regex, String.Format("$1{0}={1}", paramName, paramValue)); } else { // If no querystring just return the Parameter Key/Value if (queryString == String.Empty) { return String.Format("{0}={1}", paramName, paramValue); } else { // Append the new parameter key/value to the end of querystring queryString = String.Format("{0}&{1}={2}", queryString, paramName, paramValue); } } return queryString; } Obviously you could use the QueryString NameValueCollection property of the URI object to make looking up the values easier, but we wanted to be able to parse any querystring.
[ "asp.net", "web-applications", "custom-server-controls" ]
3
1
1,018
2
0
2008-09-06T08:30:22.233000
2008-09-06T09:01:16.280000
47,338
47,418
ASP.NET MVC Preview 5 routing ambiguity
I have a problem with a sample routing with the preview 5 of asp.net mvc. In the AccountController I have 2 actions: public ActionResult Delete() public ActionResult Delete(string username) While trying to look for Account/Delete or Account/Delete?username=davide the ControllerActionInvoker throws a exception saying that Delete request is ambiguous between my tow actions methods. The default route in the global.asax hasn't been changed. Shouldn't the action invoker understand what's the method to call looking in the parameters list? Using the preview 4 I hadn't these kind of problem performing the same operation. Any idea?
Solution found! With the introduction of the ActionNameAttribute, it's now necessary to filter manually which method to call depending on the request. This is done by the ActionSelectionAttribute. Full explanation here: http://haacked.com/archive/2008/08/29/how-a-method-becomes-an-action.aspx
ASP.NET MVC Preview 5 routing ambiguity I have a problem with a sample routing with the preview 5 of asp.net mvc. In the AccountController I have 2 actions: public ActionResult Delete() public ActionResult Delete(string username) While trying to look for Account/Delete or Account/Delete?username=davide the ControllerActionInvoker throws a exception saying that Delete request is ambiguous between my tow actions methods. The default route in the global.asax hasn't been changed. Shouldn't the action invoker understand what's the method to call looking in the parameters list? Using the preview 4 I hadn't these kind of problem performing the same operation. Any idea?
TITLE: ASP.NET MVC Preview 5 routing ambiguity QUESTION: I have a problem with a sample routing with the preview 5 of asp.net mvc. In the AccountController I have 2 actions: public ActionResult Delete() public ActionResult Delete(string username) While trying to look for Account/Delete or Account/Delete?username=davide the ControllerActionInvoker throws a exception saying that Delete request is ambiguous between my tow actions methods. The default route in the global.asax hasn't been changed. Shouldn't the action invoker understand what's the method to call looking in the parameters list? Using the preview 4 I hadn't these kind of problem performing the same operation. Any idea? ANSWER: Solution found! With the introduction of the ActionNameAttribute, it's now necessary to filter manually which method to call depending on the request. This is done by the ActionSelectionAttribute. Full explanation here: http://haacked.com/archive/2008/08/29/how-a-method-becomes-an-action.aspx
[ "asp.net-mvc", "routes" ]
1
3
815
4
0
2008-09-06T08:49:26.103000
2008-09-06T12:44:07.523000
47,340
47,368
Versioning library like SQLite database library?
I like how SQLite library can be included into an application and the application has a full-fledged database to use. Similarly, is there an open source versioning library that I can include into my application so that I can save versions of files as well as do diffs and merges?
SVN doesn't require any prerequisites on end user machine. You can embed SVN right into you app. To learn more on subversion integration, visit " Application Integration/Embedding " thread on SVN forum.
Versioning library like SQLite database library? I like how SQLite library can be included into an application and the application has a full-fledged database to use. Similarly, is there an open source versioning library that I can include into my application so that I can save versions of files as well as do diffs and merges?
TITLE: Versioning library like SQLite database library? QUESTION: I like how SQLite library can be included into an application and the application has a full-fledged database to use. Similarly, is there an open source versioning library that I can include into my application so that I can save versions of files as well as do diffs and merges? ANSWER: SVN doesn't require any prerequisites on end user machine. You can embed SVN right into you app. To learn more on subversion integration, visit " Application Integration/Embedding " thread on SVN forum.
[ "version-control", "open-source" ]
4
3
1,002
5
0
2008-09-06T08:52:34.817000
2008-09-06T10:18:36.123000
47,363
47,364
Show all triggers in a MySQL database
What is the command to list all triggers in a MySQL database?
The command for listing all triggers is: show triggers; or you can access the INFORMATION_SCHEMA table directly by: select trigger_schema, trigger_name, action_statement from information_schema.triggers You can do this from version 5.0.10 onwards. More information about the TRIGGERS table is here.
Show all triggers in a MySQL database What is the command to list all triggers in a MySQL database?
TITLE: Show all triggers in a MySQL database QUESTION: What is the command to list all triggers in a MySQL database? ANSWER: The command for listing all triggers is: show triggers; or you can access the INFORMATION_SCHEMA table directly by: select trigger_schema, trigger_name, action_statement from information_schema.triggers You can do this from version 5.0.10 onwards. More information about the TRIGGERS table is here.
[ "sql", "mysql", "database", "triggers", "sqlcommand" ]
128
200
164,873
8
0
2008-09-06T10:02:26.770000
2008-09-06T10:02:40.827000
47,366
1,521,408
SQL Compare-Like tool for Oracle?
We're a.NET team which uses the Oracle DB for a lot of reasons that I won't get into. But deployment has been a bitch. We are manually keeping track of all the changes to the schema in each version, by keeping a record of all the scripts that we run during development. Now, if a developer forgets to check-in his script to the source control after he ran it - which is not that rare - at the end of the iteration we get a great big headache. I hear that SQL Compare by Red-Gate might solve these kind of issues, but it only has SQL Server support. Anybody knows of a similar tool for Oracle? I've been unable to find one.
Red Gate Schema Compare for Oracle has now been released! http://www.red-gate.com/products/schema_compare_for_oracle/index.htm There is a 28-day fully functional free trial. Please give it a go and let us know your feedback!
SQL Compare-Like tool for Oracle? We're a.NET team which uses the Oracle DB for a lot of reasons that I won't get into. But deployment has been a bitch. We are manually keeping track of all the changes to the schema in each version, by keeping a record of all the scripts that we run during development. Now, if a developer forgets to check-in his script to the source control after he ran it - which is not that rare - at the end of the iteration we get a great big headache. I hear that SQL Compare by Red-Gate might solve these kind of issues, but it only has SQL Server support. Anybody knows of a similar tool for Oracle? I've been unable to find one.
TITLE: SQL Compare-Like tool for Oracle? QUESTION: We're a.NET team which uses the Oracle DB for a lot of reasons that I won't get into. But deployment has been a bitch. We are manually keeping track of all the changes to the schema in each version, by keeping a record of all the scripts that we run during development. Now, if a developer forgets to check-in his script to the source control after he ran it - which is not that rare - at the end of the iteration we get a great big headache. I hear that SQL Compare by Red-Gate might solve these kind of issues, but it only has SQL Server support. Anybody knows of a similar tool for Oracle? I've been unable to find one. ANSWER: Red Gate Schema Compare for Oracle has now been released! http://www.red-gate.com/products/schema_compare_for_oracle/index.htm There is a 28-day fully functional free trial. Please give it a go and let us know your feedback!
[ "oracle", "sqlcompare" ]
9
11
4,244
7
0
2008-09-06T10:06:32.970000
2009-10-05T17:41:03.967000
47,374
130,400
Best practices re: LINQ To SQL for data access
Part of the web application I'm working on is an area displaying messages from management to 1...n users. I have a DataAccess project that contains the LINQ to SQL classes, and a website project that is the UI. My database looks like this: User -> MessageDetail <- Message <- MessageCategory MessageDetail is a join table that also contains an IsRead flag. The list of messages is grouped by category. I have two nested ListView controls on the page -- One outputs the group name, while a second one nested inside that is bound to MessageDetails and outputs the messages themselves. In the code-behind for the page listing the messages I have the following code: protected void MessageListDataSource_Selecting(object sender, LinqDataSourceSelectEventArgs e) { var db = new DataContext(); // parse the input strings from the web form int categoryIDFilter; DateTime dateFilter; string catFilterString = MessagesCategoryFilter.SelectedValue; string dateFilterString = MessagesDateFilter.SelectedValue; // TryParse will return default values if parsing is unsuccessful (i.e. if "all" is selected"): // DateTime.MinValue for dates, 0 for int DateTime.TryParse(dateFilterString, out dateFilter); Int32.TryParse(catFilterString, out categoryIDFilter); bool showRead = MessagesReadFilter.Checked; var messages = from detail in db.MessageDetails where detail.UserID == (int)Session["UserID"] where detail.Message.IsPublished where detail.Message.MessageCategoryID == categoryIDFilter || (categoryIDFilter == 0) where dateFilter == detail.Message.PublishDate.Value.Date || (dateFilter == DateTime.MinValue) // is unread, showRead filter is on, or message was marked read today where detail.IsRead == false || showRead || detail.ReadDate.Value.Date == DateTime.Today orderby detail.Message.PublishDate descending group detail by detail.Message.MessageCategory into categories orderby categories.Key.Name select new { MessageCategory = categories.Key, MessageDetails = categories.Select(d => d) }; e.Result = messages; } This code works, but sticking a huge LINQ statement like this in the code-behind for a LinqDataSource control just doesn't sit right with me. It seems like I'm still coding queries into the user interface, only now it's LINQ instead of SQL. However, I feel that building another layer between the L2S classes and the UI would cut back on some of the flexibility of LINQ. Isn't the whole point to reduce the amount of code you write to fetch data? Is there some possible middle ground I'm not seeing, or am I just misunderstanding the way LINQ to SQL is supposed to be used? Advice would be greatly appreciated.
All your LINQ querys should be in a business logic class, no change from older methodologies like ADO. If you are a purist you should always return List(of T) from your methods in the business class, in fact, the datacontext should only be visible to the business classes. Then you can manipulate the list in the user interface. If you are a pragmatist, you can return a IQueryable object and make some manipulations in the user interface.
Best practices re: LINQ To SQL for data access Part of the web application I'm working on is an area displaying messages from management to 1...n users. I have a DataAccess project that contains the LINQ to SQL classes, and a website project that is the UI. My database looks like this: User -> MessageDetail <- Message <- MessageCategory MessageDetail is a join table that also contains an IsRead flag. The list of messages is grouped by category. I have two nested ListView controls on the page -- One outputs the group name, while a second one nested inside that is bound to MessageDetails and outputs the messages themselves. In the code-behind for the page listing the messages I have the following code: protected void MessageListDataSource_Selecting(object sender, LinqDataSourceSelectEventArgs e) { var db = new DataContext(); // parse the input strings from the web form int categoryIDFilter; DateTime dateFilter; string catFilterString = MessagesCategoryFilter.SelectedValue; string dateFilterString = MessagesDateFilter.SelectedValue; // TryParse will return default values if parsing is unsuccessful (i.e. if "all" is selected"): // DateTime.MinValue for dates, 0 for int DateTime.TryParse(dateFilterString, out dateFilter); Int32.TryParse(catFilterString, out categoryIDFilter); bool showRead = MessagesReadFilter.Checked; var messages = from detail in db.MessageDetails where detail.UserID == (int)Session["UserID"] where detail.Message.IsPublished where detail.Message.MessageCategoryID == categoryIDFilter || (categoryIDFilter == 0) where dateFilter == detail.Message.PublishDate.Value.Date || (dateFilter == DateTime.MinValue) // is unread, showRead filter is on, or message was marked read today where detail.IsRead == false || showRead || detail.ReadDate.Value.Date == DateTime.Today orderby detail.Message.PublishDate descending group detail by detail.Message.MessageCategory into categories orderby categories.Key.Name select new { MessageCategory = categories.Key, MessageDetails = categories.Select(d => d) }; e.Result = messages; } This code works, but sticking a huge LINQ statement like this in the code-behind for a LinqDataSource control just doesn't sit right with me. It seems like I'm still coding queries into the user interface, only now it's LINQ instead of SQL. However, I feel that building another layer between the L2S classes and the UI would cut back on some of the flexibility of LINQ. Isn't the whole point to reduce the amount of code you write to fetch data? Is there some possible middle ground I'm not seeing, or am I just misunderstanding the way LINQ to SQL is supposed to be used? Advice would be greatly appreciated.
TITLE: Best practices re: LINQ To SQL for data access QUESTION: Part of the web application I'm working on is an area displaying messages from management to 1...n users. I have a DataAccess project that contains the LINQ to SQL classes, and a website project that is the UI. My database looks like this: User -> MessageDetail <- Message <- MessageCategory MessageDetail is a join table that also contains an IsRead flag. The list of messages is grouped by category. I have two nested ListView controls on the page -- One outputs the group name, while a second one nested inside that is bound to MessageDetails and outputs the messages themselves. In the code-behind for the page listing the messages I have the following code: protected void MessageListDataSource_Selecting(object sender, LinqDataSourceSelectEventArgs e) { var db = new DataContext(); // parse the input strings from the web form int categoryIDFilter; DateTime dateFilter; string catFilterString = MessagesCategoryFilter.SelectedValue; string dateFilterString = MessagesDateFilter.SelectedValue; // TryParse will return default values if parsing is unsuccessful (i.e. if "all" is selected"): // DateTime.MinValue for dates, 0 for int DateTime.TryParse(dateFilterString, out dateFilter); Int32.TryParse(catFilterString, out categoryIDFilter); bool showRead = MessagesReadFilter.Checked; var messages = from detail in db.MessageDetails where detail.UserID == (int)Session["UserID"] where detail.Message.IsPublished where detail.Message.MessageCategoryID == categoryIDFilter || (categoryIDFilter == 0) where dateFilter == detail.Message.PublishDate.Value.Date || (dateFilter == DateTime.MinValue) // is unread, showRead filter is on, or message was marked read today where detail.IsRead == false || showRead || detail.ReadDate.Value.Date == DateTime.Today orderby detail.Message.PublishDate descending group detail by detail.Message.MessageCategory into categories orderby categories.Key.Name select new { MessageCategory = categories.Key, MessageDetails = categories.Select(d => d) }; e.Result = messages; } This code works, but sticking a huge LINQ statement like this in the code-behind for a LinqDataSource control just doesn't sit right with me. It seems like I'm still coding queries into the user interface, only now it's LINQ instead of SQL. However, I feel that building another layer between the L2S classes and the UI would cut back on some of the flexibility of LINQ. Isn't the whole point to reduce the amount of code you write to fetch data? Is there some possible middle ground I'm not seeing, or am I just misunderstanding the way LINQ to SQL is supposed to be used? Advice would be greatly appreciated. ANSWER: All your LINQ querys should be in a business logic class, no change from older methodologies like ADO. If you are a purist you should always return List(of T) from your methods in the business class, in fact, the datacontext should only be visible to the business classes. Then you can manipulate the list in the user interface. If you are a pragmatist, you can return a IQueryable object and make some manipulations in the user interface.
[ "asp.net", "linq", "linq-to-sql" ]
6
5
1,729
2
0
2008-09-06T10:43:39.497000
2008-09-24T22:46:45.073000
47,376
47,380
How can I monitor the executed sql statements on a SQL Server 2005
In a project of mine the SQL statements that are executed against a SQL Server are failing for some unknown reason. Some of the code is already used in production so debugging it is not an easy task. Therefore I need a way to see in the database itself what SQL statements are used, as the statements are generated at runtime by the project and could be flawed when certain conditions are met. I therefore considered the possibility to monitor the incoming statements and check myself if I see any flaws. The database is running on a SQL Server 2005, and I use SQL server management studio express as primary tool to manipulate the database. So my question is, what is the best way to do this?
Seeing how you use the Management Studio Express, I will assume you don't have access to the MSSQL 2005 client tools. If you do, install those, because it includes the SQL profiler which does exactly what you want (and more!). For more info about that one, see msdn. I found this a while ago, because I was thinking about the exact same thing. I have access to the client tools myself, so I don't really need to yet, but that access is not unlimited (it's through my current job). If you try it out, let me know if it works;-)
How can I monitor the executed sql statements on a SQL Server 2005 In a project of mine the SQL statements that are executed against a SQL Server are failing for some unknown reason. Some of the code is already used in production so debugging it is not an easy task. Therefore I need a way to see in the database itself what SQL statements are used, as the statements are generated at runtime by the project and could be flawed when certain conditions are met. I therefore considered the possibility to monitor the incoming statements and check myself if I see any flaws. The database is running on a SQL Server 2005, and I use SQL server management studio express as primary tool to manipulate the database. So my question is, what is the best way to do this?
TITLE: How can I monitor the executed sql statements on a SQL Server 2005 QUESTION: In a project of mine the SQL statements that are executed against a SQL Server are failing for some unknown reason. Some of the code is already used in production so debugging it is not an easy task. Therefore I need a way to see in the database itself what SQL statements are used, as the statements are generated at runtime by the project and could be flawed when certain conditions are met. I therefore considered the possibility to monitor the incoming statements and check myself if I see any flaws. The database is running on a SQL Server 2005, and I use SQL server management studio express as primary tool to manipulate the database. So my question is, what is the best way to do this? ANSWER: Seeing how you use the Management Studio Express, I will assume you don't have access to the MSSQL 2005 client tools. If you do, install those, because it includes the SQL profiler which does exactly what you want (and more!). For more info about that one, see msdn. I found this a while ago, because I was thinking about the exact same thing. I have access to the client tools myself, so I don't really need to yet, but that access is not unlimited (it's through my current job). If you try it out, let me know if it works;-)
[ "sql", "sql-server", "sql-server-2005", "monitoring" ]
18
22
28,545
2
0
2008-09-06T10:48:06.990000
2008-09-06T10:53:04.637000
47,387
47,393
Setting Up MySQL Triggers
I've been hearing about triggers, and I have a few questions. What are triggers? How do I set them up? Are there any precautions, aside from typical SQL stuff, that should be taken?
Triggers allow you to perform a function in the database as certain events happen (eg, an insert into a table). I can't comment on mysql specifically. Precaution: Triggers can be very alluring, when you first start using them they seem like a magic bullet to all kinds of problems. But, they make "magic" stuff happen, if you don't know the database inside out, it can seem like really strange things happen (such as inserts into other tables, input data changing, etc). Before implementing things as a trigger I'd seriously consider instead enforcing the use of an API around the schema (preferably in the database, but outside if you can't). Some things I'd still use triggers for Keeping track of "date_created" and "date_last_edited" fields Inserting "ID"'s (in oracle, where there is no auto id field) Keeping change history Things you wouldn't want to use triggers for business rules/logic anything which connects outside of the database (eg a webservice call) Access control Anything which isn't transactional ( anything you do in the trigger MUST be able to rollback with the transaction )
Setting Up MySQL Triggers I've been hearing about triggers, and I have a few questions. What are triggers? How do I set them up? Are there any precautions, aside from typical SQL stuff, that should be taken?
TITLE: Setting Up MySQL Triggers QUESTION: I've been hearing about triggers, and I have a few questions. What are triggers? How do I set them up? Are there any precautions, aside from typical SQL stuff, that should be taken? ANSWER: Triggers allow you to perform a function in the database as certain events happen (eg, an insert into a table). I can't comment on mysql specifically. Precaution: Triggers can be very alluring, when you first start using them they seem like a magic bullet to all kinds of problems. But, they make "magic" stuff happen, if you don't know the database inside out, it can seem like really strange things happen (such as inserts into other tables, input data changing, etc). Before implementing things as a trigger I'd seriously consider instead enforcing the use of an API around the schema (preferably in the database, but outside if you can't). Some things I'd still use triggers for Keeping track of "date_created" and "date_last_edited" fields Inserting "ID"'s (in oracle, where there is no auto id field) Keeping change history Things you wouldn't want to use triggers for business rules/logic anything which connects outside of the database (eg a webservice call) Access control Anything which isn't transactional ( anything you do in the trigger MUST be able to rollback with the transaction )
[ "mysql", "triggers" ]
10
15
2,111
4
0
2008-09-06T11:24:53
2008-09-06T11:35:21.883000
47,402
47,426
Efficiently reverse the order of the words (not characters) in an array of characters
Given an array of characters which forms a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it. Example input and output: >>> reverse_words("this is a string") 'string a is this' It should be O(N) time and O(1) space ( split() and pushing on / popping off the stack are not allowed). The puzzle is taken from here.
A solution in C/C++: void swap(char* str, int i, int j){ char t = str[i]; str[i] = str[j]; str[j] = t; } void reverse_string(char* str, int length){ for(int i=0; i This should be O(n) in time and O(1) in space. Edit: Cleaned it up a bit. The first pass over the string is obviously O(n/2) = O(n). The second pass is O(n + combined length of all words / 2) = O(n + n/2) = O(n), which makes this an O(n) algorithm.
Efficiently reverse the order of the words (not characters) in an array of characters Given an array of characters which forms a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it. Example input and output: >>> reverse_words("this is a string") 'string a is this' It should be O(N) time and O(1) space ( split() and pushing on / popping off the stack are not allowed). The puzzle is taken from here.
TITLE: Efficiently reverse the order of the words (not characters) in an array of characters QUESTION: Given an array of characters which forms a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it. Example input and output: >>> reverse_words("this is a string") 'string a is this' It should be O(N) time and O(1) space ( split() and pushing on / popping off the stack are not allowed). The puzzle is taken from here. ANSWER: A solution in C/C++: void swap(char* str, int i, int j){ char t = str[i]; str[i] = str[j]; str[j] = t; } void reverse_string(char* str, int length){ for(int i=0; i This should be O(n) in time and O(1) in space. Edit: Cleaned it up a bit. The first pass over the string is obviously O(n/2) = O(n). The second pass is O(n + combined length of all words / 2) = O(n + n/2) = O(n), which makes this an O(n) algorithm.
[ "algorithm", "language-agnostic", "reverse", "puzzle" ]
15
34
31,647
21
0
2008-09-06T12:09:57.057000
2008-09-06T12:53:35.377000
47,413
47,431
MS-Access design pattern for last value for a grouping
It's common to have a table where for example the the fields are account, value, and time. What's the best design pattern for retrieving the last value for each account? Unfortunately the last keyword in a grouping gives you the last physical record in the database, not the last record by any sorting. Which means IMHO it should never be used. The two clumsy approaches I use are either a subquery approach or a secondary query to determine the last record, and then joining to the table to find the value. Isn't there a more elegant approach?
The subquery option sounds best to me, something like the following psuedo-sql. It may be possible/necessary to optimize it via a join, that will depend on the capabilities of the SQL engine. select * from table where account+time in (select account+max(time) from table group by account order by time)
MS-Access design pattern for last value for a grouping It's common to have a table where for example the the fields are account, value, and time. What's the best design pattern for retrieving the last value for each account? Unfortunately the last keyword in a grouping gives you the last physical record in the database, not the last record by any sorting. Which means IMHO it should never be used. The two clumsy approaches I use are either a subquery approach or a secondary query to determine the last record, and then joining to the table to find the value. Isn't there a more elegant approach?
TITLE: MS-Access design pattern for last value for a grouping QUESTION: It's common to have a table where for example the the fields are account, value, and time. What's the best design pattern for retrieving the last value for each account? Unfortunately the last keyword in a grouping gives you the last physical record in the database, not the last record by any sorting. Which means IMHO it should never be used. The two clumsy approaches I use are either a subquery approach or a secondary query to determine the last record, and then joining to the table to find the value. Isn't there a more elegant approach? ANSWER: The subquery option sounds best to me, something like the following psuedo-sql. It may be possible/necessary to optimize it via a join, that will depend on the capabilities of the SQL engine. select * from table where account+time in (select account+max(time) from table group by account order by time)
[ "ms-access" ]
3
1
3,596
8
0
2008-09-06T12:37:41.110000
2008-09-06T13:03:12.687000
47,414
53,790
Standard way to merge Entities in LlblGenPro
I start with an entity A with primary key A1, it has child collections B and C, but they are empty, because I haven't prefetched them. I now get a new occurrence of A (A prime) with primary key A1 with the child collections B and C filled. What is a good way to get the A and A prime to be the same object and to get A collections of B and C filled?
Once you, have 2 separate objects in memory and you have references to both of them the only way to merge them is to change all references to point to one of the objects, which might be impossible. However there's something you can do not to arrive in this situation you can use a SD.LLBLGen.Pro.ORMSupportClasses.Context class which you can attach to an adapter and which acts as a caching layer and when entities are loaded it returns the same object for a unique entity, basically it does't let you duplicate entities in memory and always returns the reference to a already loaded entity.
Standard way to merge Entities in LlblGenPro I start with an entity A with primary key A1, it has child collections B and C, but they are empty, because I haven't prefetched them. I now get a new occurrence of A (A prime) with primary key A1 with the child collections B and C filled. What is a good way to get the A and A prime to be the same object and to get A collections of B and C filled?
TITLE: Standard way to merge Entities in LlblGenPro QUESTION: I start with an entity A with primary key A1, it has child collections B and C, but they are empty, because I haven't prefetched them. I now get a new occurrence of A (A prime) with primary key A1 with the child collections B and C filled. What is a good way to get the A and A prime to be the same object and to get A collections of B and C filled? ANSWER: Once you, have 2 separate objects in memory and you have references to both of them the only way to merge them is to change all references to point to one of the objects, which might be impossible. However there's something you can do not to arrive in this situation you can use a SD.LLBLGen.Pro.ORMSupportClasses.Context class which you can attach to an adapter and which acts as a caching layer and when entities are loaded it returns the same object for a unique entity, basically it does't let you duplicate entities in memory and always returns the reference to a already loaded entity.
[ "c#", "orm", "llblgenpro" ]
4
3
548
1
0
2008-09-06T12:37:55.133000
2008-09-10T11:19:53.387000
47,427
47,428
Why do some websites add "Slugs" to the end of URLs?
Many websites, including this one, add what are apparently called slugs - descriptive but as far as I can tell useless bits of text - to the end of URLs. For example, the URL the site gives for this question is: https://stackoverflow.com/questions/47427/why-do-some-websites-add-slugs-to-the-end-of-urls But the following URL works just as well: https://stackoverflow.com/questions/47427/ Is the point of this text just to somehow make the URL more user friendly or are there some other benefits?
The slugs make the URL more user-friendly and you know what to expect when you click a link. Search engines such as Google, rank the pages higher if the searchword is in the URL.
Why do some websites add "Slugs" to the end of URLs? Many websites, including this one, add what are apparently called slugs - descriptive but as far as I can tell useless bits of text - to the end of URLs. For example, the URL the site gives for this question is: https://stackoverflow.com/questions/47427/why-do-some-websites-add-slugs-to-the-end-of-urls But the following URL works just as well: https://stackoverflow.com/questions/47427/ Is the point of this text just to somehow make the URL more user friendly or are there some other benefits?
TITLE: Why do some websites add "Slugs" to the end of URLs? QUESTION: Many websites, including this one, add what are apparently called slugs - descriptive but as far as I can tell useless bits of text - to the end of URLs. For example, the URL the site gives for this question is: https://stackoverflow.com/questions/47427/why-do-some-websites-add-slugs-to-the-end-of-urls But the following URL works just as well: https://stackoverflow.com/questions/47427/ Is the point of this text just to somehow make the URL more user friendly or are there some other benefits? ANSWER: The slugs make the URL more user-friendly and you know what to expect when you click a link. Search engines such as Google, rank the pages higher if the searchword is in the URL.
[ "url", "seo", "friendly-url", "slug" ]
115
170
45,562
14
0
2008-09-06T13:00:32.333000
2008-09-06T13:01:53.237000
47,432
48,229
Would you recommend using "The C5 Generic Collection Library for C# and CLI" based on your experience with it?
This free collection library comes from IT University of Copenhagen. http://www.itu.dk/research/c5/ There is a video with one of the authors on Channel 9. I am trying to learn how to use these collections and I was wondering whether anyone has more experiences or what are your thoughts on this specific collection library for.NET. Do you like the way they are designed, do you like their performance and what were your major problems with them?
I've used it in the past and there are a couple of notes I must make: The library is very good, very fast and very useful. It has lots of very nice data structures, some of which I did not know before starting to use this library. It's Open-Source! This is a huge benefit. Sometimes you don't have exactly what you want. As far as my experience showed, the library's authors decided to go with a very fault-intolerant attitude, throwing exceptions about everything. This caused me to add a few fault-tolerant methods. All in all, a very nice library with some advanced data structures. Unfortunately, support for it is very lacking, as you can see from the fact that new releases (bugfixes, et al) range somewhere from 6 months to a year. Note: Starting with Mono 2.0, C5 is bundled as a 3rd party API, which I believe to be a wonderful show of faith in the product from the Mono team.
Would you recommend using "The C5 Generic Collection Library for C# and CLI" based on your experience with it? This free collection library comes from IT University of Copenhagen. http://www.itu.dk/research/c5/ There is a video with one of the authors on Channel 9. I am trying to learn how to use these collections and I was wondering whether anyone has more experiences or what are your thoughts on this specific collection library for.NET. Do you like the way they are designed, do you like their performance and what were your major problems with them?
TITLE: Would you recommend using "The C5 Generic Collection Library for C# and CLI" based on your experience with it? QUESTION: This free collection library comes from IT University of Copenhagen. http://www.itu.dk/research/c5/ There is a video with one of the authors on Channel 9. I am trying to learn how to use these collections and I was wondering whether anyone has more experiences or what are your thoughts on this specific collection library for.NET. Do you like the way they are designed, do you like their performance and what were your major problems with them? ANSWER: I've used it in the past and there are a couple of notes I must make: The library is very good, very fast and very useful. It has lots of very nice data structures, some of which I did not know before starting to use this library. It's Open-Source! This is a huge benefit. Sometimes you don't have exactly what you want. As far as my experience showed, the library's authors decided to go with a very fault-intolerant attitude, throwing exceptions about everything. This caused me to add a few fault-tolerant methods. All in all, a very nice library with some advanced data structures. Unfortunately, support for it is very lacking, as you can see from the fact that new releases (bugfixes, et al) range somewhere from 6 months to a year. Note: Starting with Mono 2.0, C5 is bundled as a 3rd party API, which I believe to be a wonderful show of faith in the product from the Mono team.
[ ".net", "collections" ]
21
18
5,533
3
0
2008-09-06T13:05:24.007000
2008-09-07T07:51:41.273000
47,433
47,449
subselect vs outer join
Consider the following 2 queries: select tblA.a,tblA.b,tblA.c,tblA.d from tblA where tblA.a not in (select tblB.a from tblB) select tblA.a,tblA.b,tblA.c,tblA.d from tblA left outer join tblB on tblA.a = tblB.a where tblB.a is null Which will perform better? My assumption is that in general the join will be better except in cases where the subselect returns a very small result set.
RDBMSs "rewrite" queries to optimize them, so it depends on system you're using, and I would guess they end up giving the same performance on most "good" databases. I suggest picking the one that is clearer and easier to maintain, for my money, that's the first one. It's much easier to debug the subquery as it can be run independently to check for sanity.
subselect vs outer join Consider the following 2 queries: select tblA.a,tblA.b,tblA.c,tblA.d from tblA where tblA.a not in (select tblB.a from tblB) select tblA.a,tblA.b,tblA.c,tblA.d from tblA left outer join tblB on tblA.a = tblB.a where tblB.a is null Which will perform better? My assumption is that in general the join will be better except in cases where the subselect returns a very small result set.
TITLE: subselect vs outer join QUESTION: Consider the following 2 queries: select tblA.a,tblA.b,tblA.c,tblA.d from tblA where tblA.a not in (select tblB.a from tblB) select tblA.a,tblA.b,tblA.c,tblA.d from tblA left outer join tblB on tblA.a = tblB.a where tblB.a is null Which will perform better? My assumption is that in general the join will be better except in cases where the subselect returns a very small result set. ANSWER: RDBMSs "rewrite" queries to optimize them, so it depends on system you're using, and I would guess they end up giving the same performance on most "good" databases. I suggest picking the one that is clearer and easier to maintain, for my money, that's the first one. It's much easier to debug the subquery as it can be run independently to check for sanity.
[ "sql", "sql-server", "database", "performance" ]
8
16
6,206
8
0
2008-09-06T13:05:42.587000
2008-09-06T13:17:00.783000
47,447
47,466
Child spans of the same width
I am trying to create a horizontal menu with the elements represented by 's. The menu itself (parent ) has a fixed width, but the elements number is always different. I would like to have child 's of the same width, independently of how many of them are there. What I've done so far: added a float: left; style for every span and specified its percentage width (percents are more or less fine, as the server knows at the time of the page generation, how many menu items are there and could divide 100% by this number). This works, except for the case when we have a division remainder (like for 3 elements), in this case I have a one-pixel hole to the right of the parent, and if I rounding the percents up, the last menu element is wrapped. I also don't really like style generation on the fly, but if there's no other solution, it's fine. What else could I try? It seems like this is a very common problem, however googling for "child elements of the same width" didn't help.
You might try a table with a fixed table layout. It should calculate the column widths without concerning itself with the cell contents. table.ClassName { table-layout: fixed }
Child spans of the same width I am trying to create a horizontal menu with the elements represented by 's. The menu itself (parent ) has a fixed width, but the elements number is always different. I would like to have child 's of the same width, independently of how many of them are there. What I've done so far: added a float: left; style for every span and specified its percentage width (percents are more or less fine, as the server knows at the time of the page generation, how many menu items are there and could divide 100% by this number). This works, except for the case when we have a division remainder (like for 3 elements), in this case I have a one-pixel hole to the right of the parent, and if I rounding the percents up, the last menu element is wrapped. I also don't really like style generation on the fly, but if there's no other solution, it's fine. What else could I try? It seems like this is a very common problem, however googling for "child elements of the same width" didn't help.
TITLE: Child spans of the same width QUESTION: I am trying to create a horizontal menu with the elements represented by 's. The menu itself (parent ) has a fixed width, but the elements number is always different. I would like to have child 's of the same width, independently of how many of them are there. What I've done so far: added a float: left; style for every span and specified its percentage width (percents are more or less fine, as the server knows at the time of the page generation, how many menu items are there and could divide 100% by this number). This works, except for the case when we have a division remainder (like for 3 elements), in this case I have a one-pixel hole to the right of the parent, and if I rounding the percents up, the last menu element is wrapped. I also don't really like style generation on the fly, but if there's no other solution, it's fine. What else could I try? It seems like this is a very common problem, however googling for "child elements of the same width" didn't help. ANSWER: You might try a table with a fixed table layout. It should calculate the column widths without concerning itself with the cell contents. table.ClassName { table-layout: fixed }
[ "html", "css" ]
2
2
528
4
0
2008-09-06T13:15:49.270000
2008-09-06T13:42:53.230000
47,475
47,478
Are unit-test names important?
If unit-test names can become outdated over time and if you consider that the test itself is the most important thing, then is it important to choose wise test names? ie [Test] public void ShouldValidateUserNameIsLessThan100Characters() {} verse [Test] public void UserNameTestValidation1() {}
The name of any method should make it clear what it does. IMO, your first suggestion is a bit long and the second one isn't informative enough. Also it's probably a bad idea to put "100" in the name, as that's very likely to change. What about: public void validateUserNameLength() If the test changes, the name should be updated accordingly.
Are unit-test names important? If unit-test names can become outdated over time and if you consider that the test itself is the most important thing, then is it important to choose wise test names? ie [Test] public void ShouldValidateUserNameIsLessThan100Characters() {} verse [Test] public void UserNameTestValidation1() {}
TITLE: Are unit-test names important? QUESTION: If unit-test names can become outdated over time and if you consider that the test itself is the most important thing, then is it important to choose wise test names? ie [Test] public void ShouldValidateUserNameIsLessThan100Characters() {} verse [Test] public void UserNameTestValidation1() {} ANSWER: The name of any method should make it clear what it does. IMO, your first suggestion is a bit long and the second one isn't informative enough. Also it's probably a bad idea to put "100" in the name, as that's very likely to change. What about: public void validateUserNameLength() If the test changes, the name should be updated accordingly.
[ "unit-testing" ]
18
18
1,746
13
0
2008-09-06T13:59:55.657000
2008-09-06T14:05:19.900000
47,483
47,689
Passing switches to Xcode 3.1 user scripts
I have a user script that would be much more useful if it could dynamically change some of its execution dependent on what the user wanted. Passing simple switches would easily solve this problem but I don't see any way to do it. I also tried embedding a keyword in the script name, but Xcode copies the script to a guid-looking filename before execution, so that won't work either. So does anyone know of a way to call a user script with some sort of argument? (other that the normal %%%var%%% variables) EDIT: User scripts are accessible via the script menu in Xcode's menubar (between the Window and Help menus). My question is not about "run script" build phase scripts. My apologies for leaving that somewhat ambiguous.
You can't pass parameters to user scripts — instead, user scripts operate on the context you're working in (e.g. the selected file, the selected text, etc.). You should use the context to determine what the user really wants.
Passing switches to Xcode 3.1 user scripts I have a user script that would be much more useful if it could dynamically change some of its execution dependent on what the user wanted. Passing simple switches would easily solve this problem but I don't see any way to do it. I also tried embedding a keyword in the script name, but Xcode copies the script to a guid-looking filename before execution, so that won't work either. So does anyone know of a way to call a user script with some sort of argument? (other that the normal %%%var%%% variables) EDIT: User scripts are accessible via the script menu in Xcode's menubar (between the Window and Help menus). My question is not about "run script" build phase scripts. My apologies for leaving that somewhat ambiguous.
TITLE: Passing switches to Xcode 3.1 user scripts QUESTION: I have a user script that would be much more useful if it could dynamically change some of its execution dependent on what the user wanted. Passing simple switches would easily solve this problem but I don't see any way to do it. I also tried embedding a keyword in the script name, but Xcode copies the script to a guid-looking filename before execution, so that won't work either. So does anyone know of a way to call a user script with some sort of argument? (other that the normal %%%var%%% variables) EDIT: User scripts are accessible via the script menu in Xcode's menubar (between the Window and Help menus). My question is not about "run script" build phase scripts. My apologies for leaving that somewhat ambiguous. ANSWER: You can't pass parameters to user scripts — instead, user scripts operate on the context you're working in (e.g. the selected file, the selected text, etc.). You should use the context to determine what the user really wants.
[ "xcode", "scripting", "arguments", "xcode3.1" ]
1
1
862
4
0
2008-09-06T14:11:38.467000
2008-09-06T17:45:21.543000
47,486
47,501
Tips for database design in a web application
Does someone have any tips/advice on database design for a web application? The kind of stuff that can save me a lot of time/effort in the future when/if the application I'm working on takes off and starts having a lot of usage. To be a bit more specific, the application is a strategy game (browser based, just text) that will mostly involve players issuing "orders" that will be stored in the database and processed later, with the results also being stored there (the history of "orders" and the corresponding results will probably get quite big). Edited to add more details (as requested): platform: Django database engine: I was thinking of using MySQL (unless there's a big advantage in using another) the schema: all I have now are some Django models, and that's far too much detail to post here. And if I start posting schemas this becomes too specific, and I was looking for general tips. For example, consider that I issue "orders" that will be later processed and return a result that I have to store to display some kind of "history". In this case is it better to have a separate table for the "history" or just one that aggregates both the "orders" and the result? I guess I could cache the "history" table, but this would take more space in the database and also more database operations because I would have to constantly create new rows instead of just altering them in the aggregate table.
You have probably touched on a much larger issue of designing for high scalability and performance in general. Essentially, for your database design I would follow good practices such as adding foreign keys and indexes to data you expect to be used frequently, normalise your data by splitting it into smaller tables and identify which data is to be read frequently and which is to be written frequently and optimise. Much more important than your database design for high performance web applications, is your effective use of caching both at the client level through HTML page caching and at the server level through cached data or serving up static files in place of dynamic files. The great thing about caching is that it can be added as it is needed, so that when your application does take off then you evolve accordingly. As far as your historical data is concerned, this is a great thing to cache as you do not expect it to change frequently. If you wish to produce regular and fairly intensive reports from your data, then it is good practise to put this data into another database so as not to bring your web application to a halt whilst they run. Of course this kind of optimisation really isn't necessary unless you think your application will warrant it.
Tips for database design in a web application Does someone have any tips/advice on database design for a web application? The kind of stuff that can save me a lot of time/effort in the future when/if the application I'm working on takes off and starts having a lot of usage. To be a bit more specific, the application is a strategy game (browser based, just text) that will mostly involve players issuing "orders" that will be stored in the database and processed later, with the results also being stored there (the history of "orders" and the corresponding results will probably get quite big). Edited to add more details (as requested): platform: Django database engine: I was thinking of using MySQL (unless there's a big advantage in using another) the schema: all I have now are some Django models, and that's far too much detail to post here. And if I start posting schemas this becomes too specific, and I was looking for general tips. For example, consider that I issue "orders" that will be later processed and return a result that I have to store to display some kind of "history". In this case is it better to have a separate table for the "history" or just one that aggregates both the "orders" and the result? I guess I could cache the "history" table, but this would take more space in the database and also more database operations because I would have to constantly create new rows instead of just altering them in the aggregate table.
TITLE: Tips for database design in a web application QUESTION: Does someone have any tips/advice on database design for a web application? The kind of stuff that can save me a lot of time/effort in the future when/if the application I'm working on takes off and starts having a lot of usage. To be a bit more specific, the application is a strategy game (browser based, just text) that will mostly involve players issuing "orders" that will be stored in the database and processed later, with the results also being stored there (the history of "orders" and the corresponding results will probably get quite big). Edited to add more details (as requested): platform: Django database engine: I was thinking of using MySQL (unless there's a big advantage in using another) the schema: all I have now are some Django models, and that's far too much detail to post here. And if I start posting schemas this becomes too specific, and I was looking for general tips. For example, consider that I issue "orders" that will be later processed and return a result that I have to store to display some kind of "history". In this case is it better to have a separate table for the "history" or just one that aggregates both the "orders" and the result? I guess I could cache the "history" table, but this would take more space in the database and also more database operations because I would have to constantly create new rows instead of just altering them in the aggregate table. ANSWER: You have probably touched on a much larger issue of designing for high scalability and performance in general. Essentially, for your database design I would follow good practices such as adding foreign keys and indexes to data you expect to be used frequently, normalise your data by splitting it into smaller tables and identify which data is to be read frequently and which is to be written frequently and optimise. Much more important than your database design for high performance web applications, is your effective use of caching both at the client level through HTML page caching and at the server level through cached data or serving up static files in place of dynamic files. The great thing about caching is that it can be added as it is needed, so that when your application does take off then you evolve accordingly. As far as your historical data is concerned, this is a great thing to cache as you do not expect it to change frequently. If you wish to produce regular and fairly intensive reports from your data, then it is good practise to put this data into another database so as not to bring your web application to a halt whilst they run. Of course this kind of optimisation really isn't necessary unless you think your application will warrant it.
[ "database-design", "web-applications" ]
5
10
8,898
4
0
2008-09-06T14:16:50.607000
2008-09-06T14:35:39.157000
47,487
47,508
Create a variable in .CSS file for use within that .CSS file
Possible Duplicate: Avoiding repeated constants in CSS We have some "theme colors" that are reused in our CSS sheet. Is there a way to set a variable and then reuse it? E.g..css OurColor: Blue H1 { color:OurColor; }
There's no requirement that all styles for a selector reside in a single rule, and a single rule can apply to multiple selectors... so flip it around: /* Theme color: text */ H1, P, TABLE, UL { color: blue; } /* Theme color: emphasis */ B, I, STRONG, EM { color: #00006F; } /*... */ /* Theme font: header */ H1, H2, H3, H4, H5, H6 { font-family: Comic Sans MS; } /*... */ /* H1-specific styles */ H1 { font-size: 2em; margin-bottom: 1em; } This way, you avoid repeating styles that are conceptually the same, while also making it clear which parts of the document they affect. Note the emphasis on "conceptually" in that last sentence... This just came up in the comments, so I'm gonna expand on it a bit, since I've seen people making this same mistake over and over again for years - predating even the existence of CSS: two attributes sharing the same value does not necessarily mean they represent the same concept. The sky may appear red in the evening, and so do tomatoes - but the sky and the tomato are not red for the same reason, and their colors will vary over time independently. By the same token, just because you happen to have two elements in your stylesheet that are given the same color, or size or positioning does not mean they will always share these values. A naive designer who uses grouping (as described here) or a variable processor such as SASS or LESS to avoid value repetition risks making future changes to styling incredibly error-prone; always focus on the contextual meaning of styles when looking to reduce repetition, ignoring their current values.
Create a variable in .CSS file for use within that .CSS file Possible Duplicate: Avoiding repeated constants in CSS We have some "theme colors" that are reused in our CSS sheet. Is there a way to set a variable and then reuse it? E.g..css OurColor: Blue H1 { color:OurColor; }
TITLE: Create a variable in .CSS file for use within that .CSS file QUESTION: Possible Duplicate: Avoiding repeated constants in CSS We have some "theme colors" that are reused in our CSS sheet. Is there a way to set a variable and then reuse it? E.g..css OurColor: Blue H1 { color:OurColor; } ANSWER: There's no requirement that all styles for a selector reside in a single rule, and a single rule can apply to multiple selectors... so flip it around: /* Theme color: text */ H1, P, TABLE, UL { color: blue; } /* Theme color: emphasis */ B, I, STRONG, EM { color: #00006F; } /*... */ /* Theme font: header */ H1, H2, H3, H4, H5, H6 { font-family: Comic Sans MS; } /*... */ /* H1-specific styles */ H1 { font-size: 2em; margin-bottom: 1em; } This way, you avoid repeating styles that are conceptually the same, while also making it clear which parts of the document they affect. Note the emphasis on "conceptually" in that last sentence... This just came up in the comments, so I'm gonna expand on it a bit, since I've seen people making this same mistake over and over again for years - predating even the existence of CSS: two attributes sharing the same value does not necessarily mean they represent the same concept. The sky may appear red in the evening, and so do tomatoes - but the sky and the tomato are not red for the same reason, and their colors will vary over time independently. By the same token, just because you happen to have two elements in your stylesheet that are given the same color, or size or positioning does not mean they will always share these values. A naive designer who uses grouping (as described here) or a variable processor such as SASS or LESS to avoid value repetition risks making future changes to styling incredibly error-prone; always focus on the contextual meaning of styles when looking to reduce repetition, ignoring their current values.
[ "css", "variables" ]
52
90
39,144
13
0
2008-09-06T14:21:25.293000
2008-09-06T14:43:01.247000
47,519
47,584
How to make your website look the same on Linux
I have a fairly standards compliant XHTML+CSS site that looks great on all browsers on PC and Mac. The other day I saw it on FF3 on Linux and the letter spacing was slightly larger, throwing everything out of whack and causing unwanted wrapping and clipping of text. The CSS in question has font-size: 11px; font-family: Arial, Helvetica, sans-serif; I know it's going with the generic sans-serif, whatever that maps to. If I add the following, the text scrunches up enough to be close to what I get on the other platforms: letter-spacing: -1.5px; but this would involve some nasty server-side OS sniffing. If there's a pure CSS solution to this I'd love to hear it. The system in question is Ubuntu 7.04 but that is irrelevant as I'm looking to fix it for at least the majority of, if not all, Linux users. Of course asking the user to install a font is not an option!
Sizing/spacing differences are usually difficult to catch. What you can do is create a Linux-specific CSS file that will contain these values adjusted for Linux, then do a simple JS-based detect to inject that CSS if the User agent is a Linux one. This is probably not the cleanest approach, but it will work, and with the least intrusion into your otherwise clean HTML/CSS.
How to make your website look the same on Linux I have a fairly standards compliant XHTML+CSS site that looks great on all browsers on PC and Mac. The other day I saw it on FF3 on Linux and the letter spacing was slightly larger, throwing everything out of whack and causing unwanted wrapping and clipping of text. The CSS in question has font-size: 11px; font-family: Arial, Helvetica, sans-serif; I know it's going with the generic sans-serif, whatever that maps to. If I add the following, the text scrunches up enough to be close to what I get on the other platforms: letter-spacing: -1.5px; but this would involve some nasty server-side OS sniffing. If there's a pure CSS solution to this I'd love to hear it. The system in question is Ubuntu 7.04 but that is irrelevant as I'm looking to fix it for at least the majority of, if not all, Linux users. Of course asking the user to install a font is not an option!
TITLE: How to make your website look the same on Linux QUESTION: I have a fairly standards compliant XHTML+CSS site that looks great on all browsers on PC and Mac. The other day I saw it on FF3 on Linux and the letter spacing was slightly larger, throwing everything out of whack and causing unwanted wrapping and clipping of text. The CSS in question has font-size: 11px; font-family: Arial, Helvetica, sans-serif; I know it's going with the generic sans-serif, whatever that maps to. If I add the following, the text scrunches up enough to be close to what I get on the other platforms: letter-spacing: -1.5px; but this would involve some nasty server-side OS sniffing. If there's a pure CSS solution to this I'd love to hear it. The system in question is Ubuntu 7.04 but that is irrelevant as I'm looking to fix it for at least the majority of, if not all, Linux users. Of course asking the user to install a font is not an option! ANSWER: Sizing/spacing differences are usually difficult to catch. What you can do is create a Linux-specific CSS file that will contain these values adjusted for Linux, then do a simple JS-based detect to inject that CSS if the User agent is a Linux one. This is probably not the cleanest approach, but it will work, and with the least intrusion into your otherwise clean HTML/CSS.
[ "css", "linux" ]
4
0
1,387
5
0
2008-09-06T14:52:07.340000
2008-09-06T15:46:46.787000
47,521
47,799
Using yield to iterate over a datareader might not close the connection?
Here is a sample code to retrieve data from a database using the yield keyword that I found in a few place while googling around: public IEnumerable ExecuteSelect(string commandText) { using (IDbConnection connection = CreateConnection()) { using (IDbCommand cmd = CreateCommand(commandText, connection)) { connection.Open(); using (IDbDataReader reader = cmd.ExecuteReader()) { while(reader.Read()) { yield return reader["SomeField"]; } } connection.Close(); } } } Am I correct in thinking that in this sample code, the connection would not be closed if we do not iterate over the whole datareader? Here is an example that would not close the connection, if I understand yield correctly.. foreach(object obj in ExecuteSelect(commandText)) { break; } For a db connection that might not be catastrophic, I suppose the GC would clean it up eventually, but what if instead of a connection it was a more critical resource?
The Iterator that the compiler synthesises implements IDisposable, which foreach calls when the foreach loop is exited. The Iterator's Dispose() method will clean up the using statements on early exit. As long as you use the iterator in a foreach loop, using() block, or call the Dispose() method in some other way, the cleanup of the Iterator will happen.
Using yield to iterate over a datareader might not close the connection? Here is a sample code to retrieve data from a database using the yield keyword that I found in a few place while googling around: public IEnumerable ExecuteSelect(string commandText) { using (IDbConnection connection = CreateConnection()) { using (IDbCommand cmd = CreateCommand(commandText, connection)) { connection.Open(); using (IDbDataReader reader = cmd.ExecuteReader()) { while(reader.Read()) { yield return reader["SomeField"]; } } connection.Close(); } } } Am I correct in thinking that in this sample code, the connection would not be closed if we do not iterate over the whole datareader? Here is an example that would not close the connection, if I understand yield correctly.. foreach(object obj in ExecuteSelect(commandText)) { break; } For a db connection that might not be catastrophic, I suppose the GC would clean it up eventually, but what if instead of a connection it was a more critical resource?
TITLE: Using yield to iterate over a datareader might not close the connection? QUESTION: Here is a sample code to retrieve data from a database using the yield keyword that I found in a few place while googling around: public IEnumerable ExecuteSelect(string commandText) { using (IDbConnection connection = CreateConnection()) { using (IDbCommand cmd = CreateCommand(commandText, connection)) { connection.Open(); using (IDbDataReader reader = cmd.ExecuteReader()) { while(reader.Read()) { yield return reader["SomeField"]; } } connection.Close(); } } } Am I correct in thinking that in this sample code, the connection would not be closed if we do not iterate over the whole datareader? Here is an example that would not close the connection, if I understand yield correctly.. foreach(object obj in ExecuteSelect(commandText)) { break; } For a db connection that might not be catastrophic, I suppose the GC would clean it up eventually, but what if instead of a connection it was a more critical resource? ANSWER: The Iterator that the compiler synthesises implements IDisposable, which foreach calls when the foreach loop is exited. The Iterator's Dispose() method will clean up the using statements on early exit. As long as you use the iterator in a foreach loop, using() block, or call the Dispose() method in some other way, the cleanup of the Iterator will happen.
[ ".net-2.0", "yield" ]
15
12
6,531
4
0
2008-09-06T14:53:45.447000
2008-09-06T20:15:18.453000
47,524
47,540
JUnit for database code
I've been trying to implement unit testing and currently have some code that does the following: query external database, loading into a feed table query a view, which is a delta of my feed and data tables, updating data table to match feed table my unit testing strategy is this: I have a testing database that I am free to manipulate. in setUP(), load some data into my testing db run my code, using my testing db as the source inspect the data table, checking for counts and the existence/non existence of certain records clear testing db, loading in a different set of data run code again inspect data table again Obviously I have the data sets that I load into the source db set up such that I know certain records should be added,deleted,updated, etc. It seems like this is a bit cumbersome and there should be an easier way? any suggestions?
Is it your intent to test the view which generates the deltas, or to test that your code correctly adds, deletes and updates in response to the view? If you want to test the view, you could use a tool like DBUnit to populate your feed and data tables with various data whose delta you've manually calculated. Then, for each test you would verify that the view returns a matching set. If you want to test how your code responds to diffs detected by the view, I would try to abstract away database access. I imagine an java method to which you can pass a result set (or list of POJO/DTO's) and returns a list of parameter Object arrays (again, or POJO's) to be added. Other methods would parse the diff list for items to be removed and updated. You could then create a mock result set or pojo's, pass them to your code and verify the correct parameters are returned. All without touching a database. I think the key is to break your process into parts and test each of those as independently as possible.
JUnit for database code I've been trying to implement unit testing and currently have some code that does the following: query external database, loading into a feed table query a view, which is a delta of my feed and data tables, updating data table to match feed table my unit testing strategy is this: I have a testing database that I am free to manipulate. in setUP(), load some data into my testing db run my code, using my testing db as the source inspect the data table, checking for counts and the existence/non existence of certain records clear testing db, loading in a different set of data run code again inspect data table again Obviously I have the data sets that I load into the source db set up such that I know certain records should be added,deleted,updated, etc. It seems like this is a bit cumbersome and there should be an easier way? any suggestions?
TITLE: JUnit for database code QUESTION: I've been trying to implement unit testing and currently have some code that does the following: query external database, loading into a feed table query a view, which is a delta of my feed and data tables, updating data table to match feed table my unit testing strategy is this: I have a testing database that I am free to manipulate. in setUP(), load some data into my testing db run my code, using my testing db as the source inspect the data table, checking for counts and the existence/non existence of certain records clear testing db, loading in a different set of data run code again inspect data table again Obviously I have the data sets that I load into the source db set up such that I know certain records should be added,deleted,updated, etc. It seems like this is a bit cumbersome and there should be an easier way? any suggestions? ANSWER: Is it your intent to test the view which generates the deltas, or to test that your code correctly adds, deletes and updates in response to the view? If you want to test the view, you could use a tool like DBUnit to populate your feed and data tables with various data whose delta you've manually calculated. Then, for each test you would verify that the view returns a matching set. If you want to test how your code responds to diffs detected by the view, I would try to abstract away database access. I imagine an java method to which you can pass a result set (or list of POJO/DTO's) and returns a list of parameter Object arrays (again, or POJO's) to be added. Other methods would parse the diff list for items to be removed and updated. You could then create a mock result set or pojo's, pass them to your code and verify the correct parameters are returned. All without touching a database. I think the key is to break your process into parts and test each of those as independently as possible.
[ "java", "database", "unit-testing", "junit" ]
8
8
13,397
5
0
2008-09-06T14:57:31.290000
2008-09-06T15:11:11.647000
47,533
47,583
Reading from a socket in C#
I am trying to read ASCII text response from a tcp open streaming socket This is what I have come up with so far. I want to know what is the best way to do this that includes error handling. Should I also be checking the SocketError after the Receive call in the do loop? IPEndPoint ep = new IPEndPoint(IPAddress.Parse("192.168.1.1"), 9000); Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sock.SendTimeout = 5000; sock.ReceiveTimeout = 5000; if (null!= sock) { try { sock.Connect(ep); if (sock.Connected) { // Blocks until send returns. int bytesSent = sock.Send(buffer); Console.WriteLine("Sent {0} bytes.", bytesSent); //get the first 4 bytes, should be the lenngth of the rest of the response. byte[] response = new byte[4]; int bytesRec = sock.Receive(response); int totalBytesRec = 0; if (4 == bytesRec) { int len = BitConverter.ToInt32(response, 0); response = new byte[len]; Console.WriteLine("Trying to get {0} bytes.", len); bytesRec = 0; do { bytesRec = sock.Receive(response); totalBytesRec += bytesRec; forecast += Encoding.ASCII.GetString(response, 0, bytesRec); } while (totalBytesRec < len && bytesRec > 0); if (totalBytesRec!= len) throw new Exception("The total bytes recieved from manager did not equal the expected bytes"); } else throw new Exception("Unable to get the response size from the manager"); Console.WriteLine("Received {0} bytes.", totalBytesRec); } } catch (SocketException ex) { Console.WriteLine("{0} Error code: {1}.", ex.Message, ex.ErrorCode); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { sock.Shutdown(SocketShutdown.Both); sock.Close(); } }
Your best bet is probably TcpClient. There's a great sample that does exactly what you're doing right in the.NET Documentation here: http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx Good luck to you!
Reading from a socket in C# I am trying to read ASCII text response from a tcp open streaming socket This is what I have come up with so far. I want to know what is the best way to do this that includes error handling. Should I also be checking the SocketError after the Receive call in the do loop? IPEndPoint ep = new IPEndPoint(IPAddress.Parse("192.168.1.1"), 9000); Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sock.SendTimeout = 5000; sock.ReceiveTimeout = 5000; if (null!= sock) { try { sock.Connect(ep); if (sock.Connected) { // Blocks until send returns. int bytesSent = sock.Send(buffer); Console.WriteLine("Sent {0} bytes.", bytesSent); //get the first 4 bytes, should be the lenngth of the rest of the response. byte[] response = new byte[4]; int bytesRec = sock.Receive(response); int totalBytesRec = 0; if (4 == bytesRec) { int len = BitConverter.ToInt32(response, 0); response = new byte[len]; Console.WriteLine("Trying to get {0} bytes.", len); bytesRec = 0; do { bytesRec = sock.Receive(response); totalBytesRec += bytesRec; forecast += Encoding.ASCII.GetString(response, 0, bytesRec); } while (totalBytesRec < len && bytesRec > 0); if (totalBytesRec!= len) throw new Exception("The total bytes recieved from manager did not equal the expected bytes"); } else throw new Exception("Unable to get the response size from the manager"); Console.WriteLine("Received {0} bytes.", totalBytesRec); } } catch (SocketException ex) { Console.WriteLine("{0} Error code: {1}.", ex.Message, ex.ErrorCode); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { sock.Shutdown(SocketShutdown.Both); sock.Close(); } }
TITLE: Reading from a socket in C# QUESTION: I am trying to read ASCII text response from a tcp open streaming socket This is what I have come up with so far. I want to know what is the best way to do this that includes error handling. Should I also be checking the SocketError after the Receive call in the do loop? IPEndPoint ep = new IPEndPoint(IPAddress.Parse("192.168.1.1"), 9000); Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sock.SendTimeout = 5000; sock.ReceiveTimeout = 5000; if (null!= sock) { try { sock.Connect(ep); if (sock.Connected) { // Blocks until send returns. int bytesSent = sock.Send(buffer); Console.WriteLine("Sent {0} bytes.", bytesSent); //get the first 4 bytes, should be the lenngth of the rest of the response. byte[] response = new byte[4]; int bytesRec = sock.Receive(response); int totalBytesRec = 0; if (4 == bytesRec) { int len = BitConverter.ToInt32(response, 0); response = new byte[len]; Console.WriteLine("Trying to get {0} bytes.", len); bytesRec = 0; do { bytesRec = sock.Receive(response); totalBytesRec += bytesRec; forecast += Encoding.ASCII.GetString(response, 0, bytesRec); } while (totalBytesRec < len && bytesRec > 0); if (totalBytesRec!= len) throw new Exception("The total bytes recieved from manager did not equal the expected bytes"); } else throw new Exception("Unable to get the response size from the manager"); Console.WriteLine("Received {0} bytes.", totalBytesRec); } } catch (SocketException ex) { Console.WriteLine("{0} Error code: {1}.", ex.Message, ex.ErrorCode); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { sock.Shutdown(SocketShutdown.Both); sock.Close(); } } ANSWER: Your best bet is probably TcpClient. There's a great sample that does exactly what you're doing right in the.NET Documentation here: http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx Good luck to you!
[ "c#", "sockets" ]
2
5
48,178
1
0
2008-09-06T15:07:36.243000
2008-09-06T15:46:40.517000
47,535
47,552
SQL to add column with default value - Access 2003
Updating an old ASP/Access site for a client - I need SQL to add a column to an existing table and set a default value. Doesn't work - any ideas? This works fine ALTER TABLE documents ADD COLUMN membersOnly NUMBER I want this to work: ALTER TABLE documents ADD COLUMN membersOnly NUMBER DEFAULT 0 Have googled and seen instructions for default values work for other field types but I want to add number. Thanks!
Tools -> Options -> Tables/Queries -> (At the bottom right:) Sql Server Compatible Syntax - turn option on for this database. then you can execute your query: ALTER TABLE documents ADD COLUMN membersOnly NUMBER DEFAULT 0
SQL to add column with default value - Access 2003 Updating an old ASP/Access site for a client - I need SQL to add a column to an existing table and set a default value. Doesn't work - any ideas? This works fine ALTER TABLE documents ADD COLUMN membersOnly NUMBER I want this to work: ALTER TABLE documents ADD COLUMN membersOnly NUMBER DEFAULT 0 Have googled and seen instructions for default values work for other field types but I want to add number. Thanks!
TITLE: SQL to add column with default value - Access 2003 QUESTION: Updating an old ASP/Access site for a client - I need SQL to add a column to an existing table and set a default value. Doesn't work - any ideas? This works fine ALTER TABLE documents ADD COLUMN membersOnly NUMBER I want this to work: ALTER TABLE documents ADD COLUMN membersOnly NUMBER DEFAULT 0 Have googled and seen instructions for default values work for other field types but I want to add number. Thanks! ANSWER: Tools -> Options -> Tables/Queries -> (At the bottom right:) Sql Server Compatible Syntax - turn option on for this database. then you can execute your query: ALTER TABLE documents ADD COLUMN membersOnly NUMBER DEFAULT 0
[ "sql", "ms-access" ]
6
8
54,243
5
0
2008-09-06T15:08:35.677000
2008-09-06T15:22:06.940000
47,537
47,548
C# Console?
Does anyone know if there is a c# Console app, similar to the Python or Ruby console? I know the whole "Compiled versus Interpreted" difference, but with C#'s reflection power I think it could be done. UPDATE Well, it only took about 200 lines, but I wrote a simple one...It works a lot like osql. You enter commands and then run them with go. SharpConsole http://www.gfilter.net/junk/sharpconsole.jpg If anyone wants it, let me know.
Given your mention of "C#'s reflection power", I am unsure whether you're looking for an interactive C# console for small code snippets of your own (à la Ruby's irb ), or a means of interacting with an existing, compiled application currently running as a process. In the former case: Windows PowerShell might be your friend Another candidate would be the C# shell Finally, CSI, a Simple C# Interpreter
C# Console? Does anyone know if there is a c# Console app, similar to the Python or Ruby console? I know the whole "Compiled versus Interpreted" difference, but with C#'s reflection power I think it could be done. UPDATE Well, it only took about 200 lines, but I wrote a simple one...It works a lot like osql. You enter commands and then run them with go. SharpConsole http://www.gfilter.net/junk/sharpconsole.jpg If anyone wants it, let me know.
TITLE: C# Console? QUESTION: Does anyone know if there is a c# Console app, similar to the Python or Ruby console? I know the whole "Compiled versus Interpreted" difference, but with C#'s reflection power I think it could be done. UPDATE Well, it only took about 200 lines, but I wrote a simple one...It works a lot like osql. You enter commands and then run them with go. SharpConsole http://www.gfilter.net/junk/sharpconsole.jpg If anyone wants it, let me know. ANSWER: Given your mention of "C#'s reflection power", I am unsure whether you're looking for an interactive C# console for small code snippets of your own (à la Ruby's irb ), or a means of interacting with an existing, compiled application currently running as a process. In the former case: Windows PowerShell might be your friend Another candidate would be the C# shell Finally, CSI, a Simple C# Interpreter
[ "c#", ".net", "console", "interactive" ]
28
19
11,018
7
0
2008-09-06T15:08:57.097000
2008-09-06T15:19:39.317000
47,538
47,554
Where's the Win32 resource for the mouse cursor for dragging splitters?
I am building a custom win32 control/widget and would like to change the cursor to a horizontal "splitter" symbol when hovering over a particular vertical line in the control. IE: I want to drag this vertical line (splitter bar) left and right (WEST and EAST). Of the the system cursors (OCR_*), the only cursor that makes sense is the OCR_SIZEWE. Unfortunately, that is the big, awkward cursor the system uses when resizing a window. Instead, I am looking for the cursor that is about 20 pixels tall and around 3 or 4 pixel wide with two small arrows pointing left and right. I can easily draw this and include it as a resource in my application but the cursor itself is so prevalent that I wanted to be sure it wasn't missing something. For example: when you use the COM drag and drop mechanism (CLSID_DragDropHelper, IDropTarget, etc) you implicitly have access to the "drag" icon (little box under the pointer). I didn't see an explicit OCR_* constant for this guy... so likewise, if I can't find this splitter cursor outright, I am wondering if it is part of a COM object or something else in the win32 lib.
There are all sorts of icons, cursors, and images in use throughout the Windows UI which are not publicly available to 3rd-party software. Of course, you could still load up the module in which they reside and use them, but there's really no guarantee your program will keep working after a system update / upgrade. Include your own. The last thing you want is adding an extra dependency over a tiny little cursor.
Where's the Win32 resource for the mouse cursor for dragging splitters? I am building a custom win32 control/widget and would like to change the cursor to a horizontal "splitter" symbol when hovering over a particular vertical line in the control. IE: I want to drag this vertical line (splitter bar) left and right (WEST and EAST). Of the the system cursors (OCR_*), the only cursor that makes sense is the OCR_SIZEWE. Unfortunately, that is the big, awkward cursor the system uses when resizing a window. Instead, I am looking for the cursor that is about 20 pixels tall and around 3 or 4 pixel wide with two small arrows pointing left and right. I can easily draw this and include it as a resource in my application but the cursor itself is so prevalent that I wanted to be sure it wasn't missing something. For example: when you use the COM drag and drop mechanism (CLSID_DragDropHelper, IDropTarget, etc) you implicitly have access to the "drag" icon (little box under the pointer). I didn't see an explicit OCR_* constant for this guy... so likewise, if I can't find this splitter cursor outright, I am wondering if it is part of a COM object or something else in the win32 lib.
TITLE: Where's the Win32 resource for the mouse cursor for dragging splitters? QUESTION: I am building a custom win32 control/widget and would like to change the cursor to a horizontal "splitter" symbol when hovering over a particular vertical line in the control. IE: I want to drag this vertical line (splitter bar) left and right (WEST and EAST). Of the the system cursors (OCR_*), the only cursor that makes sense is the OCR_SIZEWE. Unfortunately, that is the big, awkward cursor the system uses when resizing a window. Instead, I am looking for the cursor that is about 20 pixels tall and around 3 or 4 pixel wide with two small arrows pointing left and right. I can easily draw this and include it as a resource in my application but the cursor itself is so prevalent that I wanted to be sure it wasn't missing something. For example: when you use the COM drag and drop mechanism (CLSID_DragDropHelper, IDropTarget, etc) you implicitly have access to the "drag" icon (little box under the pointer). I didn't see an explicit OCR_* constant for this guy... so likewise, if I can't find this splitter cursor outright, I am wondering if it is part of a COM object or something else in the win32 lib. ANSWER: There are all sorts of icons, cursors, and images in use throughout the Windows UI which are not publicly available to 3rd-party software. Of course, you could still load up the module in which they reside and use them, but there's really no guarantee your program will keep working after a system update / upgrade. Include your own. The last thing you want is adding an extra dependency over a tiny little cursor.
[ "c++", "winapi", "native" ]
2
5
1,998
2
0
2008-09-06T15:09:10.217000
2008-09-06T15:22:46.127000
47,555
5,212,707
Practical Experience using Stripes?
I am coming from an Enterprise Java background which involves a fairly heavyweight software stack, and have recently discovered the Stripes framework; my initial impression is that this seems to do a good job of minimising the unpleasant parts of building a web application in Java. Has anyone used Stripes for a project that has gone live? And can you share your experiences from the project? Also, did you consider any other technologies and (if so) why did you chose Stripes?
We've been using Stripes for about 4 years now. Our stack is Stripes/EJB3/JPA. Many use Stripes plus Stripernate as a single, full stack solution. We don't because we want our business logic within the EJB tier, so we simply rely on JPA Entities as combined Model and DTO. Stripes does the binding to our Entities/DTO and we shove them back in to the EJB tier for work. For most of our CRUD stuff this is very thing and straightforward, making our 80% use case trivial to work with. Yet we have the flexibility to do whatever we want for the edge cases that always come up with complicate applications. We have a very large base Action Bean which encapsulates the bulk of our CRUD operations that makes call backs in to the individual subclasses specific to the entities and forms. We also have a large internal tag file library to manage our pages, security, navigation, tasks, etc. A simple CRUD edit form is little more than a list of field names, and we get all of the chrome and menus and access controls "for free". The beauty of this is that we get to keep the HTTP request based metaphor that we like and we get to choose the individual parts of the system rather than use one fat stack. The Stripes layer is lean and mean, and never gets in our way. We have a bunch of Ajax integrating YUI and JQuery, all working against our Stripes and EJB stack painlessly. I also ported a lighter version of the stack to GAE for a sample project, basically having to do minor work to our EJB tier. So, the entire stack is very nimble and amicable to change. Stripes is a big factor of that since we let it do the few things that it does, and does very well. Then delegate the rest to other parts of the stack. As always there are parts folks would rather have different at times, but Stripes would be the last part to go in our stack, frankly. It could be better at supporting the full HTTP verb set, but I'd rather fix Stripes to do that better than switch over to something else.
Practical Experience using Stripes? I am coming from an Enterprise Java background which involves a fairly heavyweight software stack, and have recently discovered the Stripes framework; my initial impression is that this seems to do a good job of minimising the unpleasant parts of building a web application in Java. Has anyone used Stripes for a project that has gone live? And can you share your experiences from the project? Also, did you consider any other technologies and (if so) why did you chose Stripes?
TITLE: Practical Experience using Stripes? QUESTION: I am coming from an Enterprise Java background which involves a fairly heavyweight software stack, and have recently discovered the Stripes framework; my initial impression is that this seems to do a good job of minimising the unpleasant parts of building a web application in Java. Has anyone used Stripes for a project that has gone live? And can you share your experiences from the project? Also, did you consider any other technologies and (if so) why did you chose Stripes? ANSWER: We've been using Stripes for about 4 years now. Our stack is Stripes/EJB3/JPA. Many use Stripes plus Stripernate as a single, full stack solution. We don't because we want our business logic within the EJB tier, so we simply rely on JPA Entities as combined Model and DTO. Stripes does the binding to our Entities/DTO and we shove them back in to the EJB tier for work. For most of our CRUD stuff this is very thing and straightforward, making our 80% use case trivial to work with. Yet we have the flexibility to do whatever we want for the edge cases that always come up with complicate applications. We have a very large base Action Bean which encapsulates the bulk of our CRUD operations that makes call backs in to the individual subclasses specific to the entities and forms. We also have a large internal tag file library to manage our pages, security, navigation, tasks, etc. A simple CRUD edit form is little more than a list of field names, and we get all of the chrome and menus and access controls "for free". The beauty of this is that we get to keep the HTTP request based metaphor that we like and we get to choose the individual parts of the system rather than use one fat stack. The Stripes layer is lean and mean, and never gets in our way. We have a bunch of Ajax integrating YUI and JQuery, all working against our Stripes and EJB stack painlessly. I also ported a lighter version of the stack to GAE for a sample project, basically having to do minor work to our EJB tier. So, the entire stack is very nimble and amicable to change. Stripes is a big factor of that since we let it do the few things that it does, and does very well. Then delegate the rest to other parts of the stack. As always there are parts folks would rather have different at times, but Stripes would be the last part to go in our stack, frankly. It could be better at supporting the full HTTP verb set, but I'd rather fix Stripes to do that better than switch over to something else.
[ "java", "stripes" ]
19
9
3,586
6
0
2008-09-06T15:24:24.360000
2011-03-06T19:03:41.173000
47,589
47,662
Can I detect and handle MySQL Warnings with PHP?
I'm dealing with a MySQL table that defines the JobName column as UNIQUE. If somebody tries to save a new Job to the database using a JobName that is already in the database, MySQL throws a warning. I would like to be able to detect this warning, just like an error, in my PHP script and deal with it appropriately. Ideally I would like to know what kind of warning MySQL has thrown so that I can branch the code to handle it. Is this possible? If not, is it because MySQL doesn't have this ability, PHP doesn't have this ability, or both?
For warnings to be "flagged" to PHP natively would require changes to the mysql/mysqli driver, which is obviously beyond the scope of this question. Instead you're going to have to basically check every query you make on the database for warnings: $warningCountResult = mysql_query("SELECT @@warning_count"); if ($warningCountResult) { $warningCount = mysql_fetch_row($warningCountResult ); if ($warningCount[0] > 0) { //Have warnings $warningDetailResult = mysql_query("SHOW WARNINGS"); if ($warningDetailResult ) { while ($warning = mysql_fetch_assoc($warningDetailResult) { //Process it } } }//Else no warnings } Obviously this is going to be hideously expensive to apply en-mass, so you might need to carefully think about when and how warnings may arise (which may lead you to refactor to eliminate them). For reference, MySQL SHOW WARNINGS Of course, you could dispense with the initial query for the SELECT @@warning_count, which would save you a query per execution, but I included it for pedantic completeness.
Can I detect and handle MySQL Warnings with PHP? I'm dealing with a MySQL table that defines the JobName column as UNIQUE. If somebody tries to save a new Job to the database using a JobName that is already in the database, MySQL throws a warning. I would like to be able to detect this warning, just like an error, in my PHP script and deal with it appropriately. Ideally I would like to know what kind of warning MySQL has thrown so that I can branch the code to handle it. Is this possible? If not, is it because MySQL doesn't have this ability, PHP doesn't have this ability, or both?
TITLE: Can I detect and handle MySQL Warnings with PHP? QUESTION: I'm dealing with a MySQL table that defines the JobName column as UNIQUE. If somebody tries to save a new Job to the database using a JobName that is already in the database, MySQL throws a warning. I would like to be able to detect this warning, just like an error, in my PHP script and deal with it appropriately. Ideally I would like to know what kind of warning MySQL has thrown so that I can branch the code to handle it. Is this possible? If not, is it because MySQL doesn't have this ability, PHP doesn't have this ability, or both? ANSWER: For warnings to be "flagged" to PHP natively would require changes to the mysql/mysqli driver, which is obviously beyond the scope of this question. Instead you're going to have to basically check every query you make on the database for warnings: $warningCountResult = mysql_query("SELECT @@warning_count"); if ($warningCountResult) { $warningCount = mysql_fetch_row($warningCountResult ); if ($warningCount[0] > 0) { //Have warnings $warningDetailResult = mysql_query("SHOW WARNINGS"); if ($warningDetailResult ) { while ($warning = mysql_fetch_assoc($warningDetailResult) { //Process it } } }//Else no warnings } Obviously this is going to be hideously expensive to apply en-mass, so you might need to carefully think about when and how warnings may arise (which may lead you to refactor to eliminate them). For reference, MySQL SHOW WARNINGS Of course, you could dispense with the initial query for the SELECT @@warning_count, which would save you a query per execution, but I included it for pedantic completeness.
[ "php", "mysql", "error-handling", "warnings" ]
15
13
17,298
8
0
2008-09-06T15:51:51.643000
2008-09-06T17:00:05.270000
47,605
47,628
String concatenation: concat() vs "+" operator
Assuming String a and b: a += b a = a.concat(b) Under the hood, are they the same thing? Here is concat decompiled as reference. I'd like to be able to decompile the + operator as well to see what that does. public String concat(String s) { int i = s.length(); if (i == 0) { return this; } else { char ac[] = new char[count + i]; getChars(0, count, ac, 0); s.getChars(0, i, ac, count); return new String(0, count + i, ac); } }
No, not quite. Firstly, there's a slight difference in semantics. If a is null, then a.concat(b) throws a NullPointerException but a+=b will treat the original value of a as if it were null. Furthermore, the concat() method only accepts String values while the + operator will silently convert the argument to a String (using the toString() method for objects). So the concat() method is more strict in what it accepts. To look under the hood, write a simple class with a += b; public class Concat { String cat(String a, String b) { a += b; return a; } } Now disassemble with javap -c (included in the Sun JDK). You should see a listing including: java.lang.String cat(java.lang.String, java.lang.String); Code: 0: new #2; //class java/lang/StringBuilder 3: dup 4: invokespecial #3; //Method java/lang/StringBuilder." ":()V 7: aload_1 8: invokevirtual #4; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 11: aload_2 12: invokevirtual #4; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 15: invokevirtual #5; //Method java/lang/StringBuilder.toString:()Ljava/lang/ String; 18: astore_1 19: aload_1 20: areturn So, a += b is the equivalent of a = new StringBuilder().append(a).append(b).toString(); The concat method should be faster. However, with more strings the StringBuilder method wins, at least in terms of performance. The source code of String and StringBuilder (and its package-private base class) is available in src.zip of the Sun JDK. You can see that you are building up a char array (resizing as necessary) and then throwing it away when you create the final String. In practice memory allocation is surprisingly fast. Update: As Pawel Adamski notes, performance has changed in more recent HotSpot. javac still produces exactly the same code, but the bytecode compiler cheats. Simple testing entirely fails because the entire body of code is thrown away. Summing System.identityHashCode (not String.hashCode ) shows the StringBuffer code has a slight advantage. Subject to change when the next update is released, or if you use a different JVM. From @lukaseder, a list of HotSpot JVM intrinsics.
String concatenation: concat() vs "+" operator Assuming String a and b: a += b a = a.concat(b) Under the hood, are they the same thing? Here is concat decompiled as reference. I'd like to be able to decompile the + operator as well to see what that does. public String concat(String s) { int i = s.length(); if (i == 0) { return this; } else { char ac[] = new char[count + i]; getChars(0, count, ac, 0); s.getChars(0, i, ac, count); return new String(0, count + i, ac); } }
TITLE: String concatenation: concat() vs "+" operator QUESTION: Assuming String a and b: a += b a = a.concat(b) Under the hood, are they the same thing? Here is concat decompiled as reference. I'd like to be able to decompile the + operator as well to see what that does. public String concat(String s) { int i = s.length(); if (i == 0) { return this; } else { char ac[] = new char[count + i]; getChars(0, count, ac, 0); s.getChars(0, i, ac, count); return new String(0, count + i, ac); } } ANSWER: No, not quite. Firstly, there's a slight difference in semantics. If a is null, then a.concat(b) throws a NullPointerException but a+=b will treat the original value of a as if it were null. Furthermore, the concat() method only accepts String values while the + operator will silently convert the argument to a String (using the toString() method for objects). So the concat() method is more strict in what it accepts. To look under the hood, write a simple class with a += b; public class Concat { String cat(String a, String b) { a += b; return a; } } Now disassemble with javap -c (included in the Sun JDK). You should see a listing including: java.lang.String cat(java.lang.String, java.lang.String); Code: 0: new #2; //class java/lang/StringBuilder 3: dup 4: invokespecial #3; //Method java/lang/StringBuilder." ":()V 7: aload_1 8: invokevirtual #4; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 11: aload_2 12: invokevirtual #4; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 15: invokevirtual #5; //Method java/lang/StringBuilder.toString:()Ljava/lang/ String; 18: astore_1 19: aload_1 20: areturn So, a += b is the equivalent of a = new StringBuilder().append(a).append(b).toString(); The concat method should be faster. However, with more strings the StringBuilder method wins, at least in terms of performance. The source code of String and StringBuilder (and its package-private base class) is available in src.zip of the Sun JDK. You can see that you are building up a char array (resizing as necessary) and then throwing it away when you create the final String. In practice memory allocation is surprisingly fast. Update: As Pawel Adamski notes, performance has changed in more recent HotSpot. javac still produces exactly the same code, but the bytecode compiler cheats. Simple testing entirely fails because the entire body of code is thrown away. Summing System.identityHashCode (not String.hashCode ) shows the StringBuffer code has a slight advantage. Subject to change when the next update is released, or if you use a different JVM. From @lukaseder, a list of HotSpot JVM intrinsics.
[ "java", "string", "concatenation" ]
592
649
1,089,762
12
0
2008-09-06T16:08:54.940000
2008-09-06T16:25:37.163000
47,612
47,618
How to do C++ style destructors in C#?
I've got a C# class with a Dispose function via IDisposable. It's intended to be used inside a using block so the expensive resource it handles can be released right away. The problem is that a bug occurred when an exception was thrown before Dispose was called, and the programmer neglected to use using or finally. In C++, I never had to worry about this. The call to a class's destructor would be automatically inserted at the end of the object's scope. The only way to avoid that happening would be to use the new operator and hold the object behind a pointer, but that required extra work for the programmer isn't something they would do by accident, like forgetting to use using. Is there any way to for a using block to be automatically used in C#? Many thanks. UPDATE: I'd like to explain why I'm not accepting the finalizer answers. Those answers are technically correct in themselves, but they are not C++ style destructors. Here's the bug I found, reduced to the essentials... try { PleaseDisposeMe a = new PleaseDisposeMe(); throw new Exception(); a.Dispose(); } catch (Exception ex) { Log(ex); } // This next call will throw a time-out exception unless the GC // runs a.Dispose in time. PleaseDisposeMe b = new PleaseDisposeMe(); Using FXCop is an excellent suggestion, but if that's my only answer, my question would have to become a plea to the C# people, or use C++. Twenty nested using statements anyone?
Unfortunately there isn't any way to do this directly in the code. If this is an issue in house, there are various code analysis solutions that could catch these sort of problems. Have you looked into FxCop? I think that this will catch these situations and in all cases where IDisposable objects might be left hanging. If it is a component that people are using outside of your organization and you can't require FxCop, then documentation is really your only recourse:). Edit: In the case of finalizers, this doesn't really guarantee when the finalization will happen. So this may be a solution for you but it depends on the situation.
How to do C++ style destructors in C#? I've got a C# class with a Dispose function via IDisposable. It's intended to be used inside a using block so the expensive resource it handles can be released right away. The problem is that a bug occurred when an exception was thrown before Dispose was called, and the programmer neglected to use using or finally. In C++, I never had to worry about this. The call to a class's destructor would be automatically inserted at the end of the object's scope. The only way to avoid that happening would be to use the new operator and hold the object behind a pointer, but that required extra work for the programmer isn't something they would do by accident, like forgetting to use using. Is there any way to for a using block to be automatically used in C#? Many thanks. UPDATE: I'd like to explain why I'm not accepting the finalizer answers. Those answers are technically correct in themselves, but they are not C++ style destructors. Here's the bug I found, reduced to the essentials... try { PleaseDisposeMe a = new PleaseDisposeMe(); throw new Exception(); a.Dispose(); } catch (Exception ex) { Log(ex); } // This next call will throw a time-out exception unless the GC // runs a.Dispose in time. PleaseDisposeMe b = new PleaseDisposeMe(); Using FXCop is an excellent suggestion, but if that's my only answer, my question would have to become a plea to the C# people, or use C++. Twenty nested using statements anyone?
TITLE: How to do C++ style destructors in C#? QUESTION: I've got a C# class with a Dispose function via IDisposable. It's intended to be used inside a using block so the expensive resource it handles can be released right away. The problem is that a bug occurred when an exception was thrown before Dispose was called, and the programmer neglected to use using or finally. In C++, I never had to worry about this. The call to a class's destructor would be automatically inserted at the end of the object's scope. The only way to avoid that happening would be to use the new operator and hold the object behind a pointer, but that required extra work for the programmer isn't something they would do by accident, like forgetting to use using. Is there any way to for a using block to be automatically used in C#? Many thanks. UPDATE: I'd like to explain why I'm not accepting the finalizer answers. Those answers are technically correct in themselves, but they are not C++ style destructors. Here's the bug I found, reduced to the essentials... try { PleaseDisposeMe a = new PleaseDisposeMe(); throw new Exception(); a.Dispose(); } catch (Exception ex) { Log(ex); } // This next call will throw a time-out exception unless the GC // runs a.Dispose in time. PleaseDisposeMe b = new PleaseDisposeMe(); Using FXCop is an excellent suggestion, but if that's my only answer, my question would have to become a plea to the C# people, or use C++. Twenty nested using statements anyone? ANSWER: Unfortunately there isn't any way to do this directly in the code. If this is an issue in house, there are various code analysis solutions that could catch these sort of problems. Have you looked into FxCop? I think that this will catch these situations and in all cases where IDisposable objects might be left hanging. If it is a component that people are using outside of your organization and you can't require FxCop, then documentation is really your only recourse:). Edit: In the case of finalizers, this doesn't really guarantee when the finalization will happen. So this may be a solution for you but it depends on the situation.
[ "c#", "dispose", "idisposable", "using" ]
2
3
2,124
7
0
2008-09-06T16:12:48.020000
2008-09-06T16:17:36.433000
47,639
47,649
What are the advantages of installing programs in AppData like Google Chrome?
I just noticed that Chromium was installed in AppData in both Vista and XP. If Google does that and if other applications does this, than is that becuase there is some form of protection? Should we write installers that does the same thing as Google?
Windows still lacks a convention for per-user installation. When an installer asks whether to install for the current user or all users, it really only refers to shortcut placement (Start Menu; Desktop). The actual application files still go in the system-wide %PROGRAMFILES%. Microsoft's own ClickOnce works around this by creating a completely non-standard %USERPROFILE%\Local Settings\Apps ( %USERPROFILE%\AppData\Roaming on Vista / Server 2008) directory, with both program files and configuration data in there. (I'm at a loss why Microsoft couldn't add a per-user Program Files directory in Vista. For example, in OS X, you can create a ~/Applications, and the Finder will give it an appropriate icon. Apps like CrossOver and Adobe AIR automatically use that, defaulting to per-user apps. Thus, no permissions issues.) What you probably should do: if the user is not an admin, install in the user directory; if they do, give them both options.
What are the advantages of installing programs in AppData like Google Chrome? I just noticed that Chromium was installed in AppData in both Vista and XP. If Google does that and if other applications does this, than is that becuase there is some form of protection? Should we write installers that does the same thing as Google?
TITLE: What are the advantages of installing programs in AppData like Google Chrome? QUESTION: I just noticed that Chromium was installed in AppData in both Vista and XP. If Google does that and if other applications does this, than is that becuase there is some form of protection? Should we write installers that does the same thing as Google? ANSWER: Windows still lacks a convention for per-user installation. When an installer asks whether to install for the current user or all users, it really only refers to shortcut placement (Start Menu; Desktop). The actual application files still go in the system-wide %PROGRAMFILES%. Microsoft's own ClickOnce works around this by creating a completely non-standard %USERPROFILE%\Local Settings\Apps ( %USERPROFILE%\AppData\Roaming on Vista / Server 2008) directory, with both program files and configuration data in there. (I'm at a loss why Microsoft couldn't add a per-user Program Files directory in Vista. For example, in OS X, you can create a ~/Applications, and the Finder will give it an appropriate icon. Apps like CrossOver and Adobe AIR automatically use that, defaulting to per-user apps. Thus, no permissions issues.) What you probably should do: if the user is not an admin, install in the user directory; if they do, give them both options.
[ "windows", "google-chrome", "windows-installer" ]
18
21
8,126
8
0
2008-09-06T16:37:23.513000
2008-09-06T16:47:16.487000
47,656
47,680
How do I do full-text searching in Ruby on Rails?
I would like to do full-text searching of data in my Ruby on Rails application. What options exist?
There are several options available and each have different strengths and weaknesses. If you would like to add full-text searching, it would be prudent to investigate each a little bit and try them out to see how well it works for you in your environment. MySQL has built-in support for full-text searching. It has online support meaning that when new records are added to the database, they are automatically indexed and will be available in the search results. The documentation has more details. acts_as_tsearch offers a wrapper for similar built-in functionality for recent versions of PostgreSQL For other databases you will have to use other software. Lucene is a popular search provider written in Java. You can use Lucene through its search server Solr with Rails using acts_as_solr. If you don't want to use Java, there is a port of Lucene to Ruby called Ferret. Support for Rails is added using the acts_as_ferret plugin. Xapian is another good option and is supported in Rails using the acts_as_xapian plugin. Finally, my preferred choice is Sphinx using the Ultrasphinx plugin. It is extremely fast and has many options on how to index and search your databases, but is no longer being actively maintained. Another plugin for Sphinx is Thinking Sphinx which has a lot of positive feedback. It is a little easier to get started using Thinking Sphinx than Ultrasphinx. I would suggest investigating both plugins to determine which fits better with your project.
How do I do full-text searching in Ruby on Rails? I would like to do full-text searching of data in my Ruby on Rails application. What options exist?
TITLE: How do I do full-text searching in Ruby on Rails? QUESTION: I would like to do full-text searching of data in my Ruby on Rails application. What options exist? ANSWER: There are several options available and each have different strengths and weaknesses. If you would like to add full-text searching, it would be prudent to investigate each a little bit and try them out to see how well it works for you in your environment. MySQL has built-in support for full-text searching. It has online support meaning that when new records are added to the database, they are automatically indexed and will be available in the search results. The documentation has more details. acts_as_tsearch offers a wrapper for similar built-in functionality for recent versions of PostgreSQL For other databases you will have to use other software. Lucene is a popular search provider written in Java. You can use Lucene through its search server Solr with Rails using acts_as_solr. If you don't want to use Java, there is a port of Lucene to Ruby called Ferret. Support for Rails is added using the acts_as_ferret plugin. Xapian is another good option and is supported in Rails using the acts_as_xapian plugin. Finally, my preferred choice is Sphinx using the Ultrasphinx plugin. It is extremely fast and has many options on how to index and search your databases, but is no longer being actively maintained. Another plugin for Sphinx is Thinking Sphinx which has a lot of positive feedback. It is a little easier to get started using Thinking Sphinx than Ultrasphinx. I would suggest investigating both plugins to determine which fits better with your project.
[ "ruby-on-rails", "full-text-search" ]
12
20
10,461
8
0
2008-09-06T16:51:21.280000
2008-09-06T17:18:19.703000
47,658
48,107
Standards Document
I am writing a coding standards document for a team of about 15 developers with a project load of between 10 and 15 projects a year. Amongst other sections (which I may post here as I get to them) I am writing a section on code formatting. So to start with, I think it is wise that, for whatever reason, we establish some basic, consistent code formatting/naming standards. I've looked at roughly 10 projects written over the last 3 years from this team and I'm, obviously, finding a pretty wide range of styles. Contractors come in and out and at times, and sometimes even double the team size. I am looking for a few suggestions for code formatting and naming standards that have really paid off... but that can also really be justified. I think consistency and shared-patterns go a long way to making the code more maintainable... but, are there other things I ought to consider when defining said standards? How do you lineup parenthesis? Do you follow the same parenthesis guidelines when dealing with classes, methods, try catch blocks, switch statements, if else blocks, etc. Do you line up fields on a column? Do you notate/prefix private variables with an underscore? Do you follow any naming conventions to make it easier to find particulars in a file? How do you order the members of your class? What about suggestions for namespaces, packaging or source code folder/organization standards? I tend to start with something like:.....ClassName I'm curious to see if there are other, more accepted, practices than what I am accustomed to -- before I venture off dictating these standards. Links to standards already published online would be great too -- even though I've done a bit of that already.
First find a automated code-formatter that works with your language. Reason: Whatever the document says, people will inevitably break the rules. It's much easier to run code through a formatter than to nit-pick in a code review. If you're using a language with an existing standard (e.g. Java, C#), it's easiest to use it, or at least start with it as a first draft. Sun put a lot of thought into their formatting rules; you might as well take advantage of it. In any case, remember that much research has shown that varying things like brace position and whitespace use has no measurable effect on productivity or understandability or prevalence of bugs. Just having any standard is the key.
Standards Document I am writing a coding standards document for a team of about 15 developers with a project load of between 10 and 15 projects a year. Amongst other sections (which I may post here as I get to them) I am writing a section on code formatting. So to start with, I think it is wise that, for whatever reason, we establish some basic, consistent code formatting/naming standards. I've looked at roughly 10 projects written over the last 3 years from this team and I'm, obviously, finding a pretty wide range of styles. Contractors come in and out and at times, and sometimes even double the team size. I am looking for a few suggestions for code formatting and naming standards that have really paid off... but that can also really be justified. I think consistency and shared-patterns go a long way to making the code more maintainable... but, are there other things I ought to consider when defining said standards? How do you lineup parenthesis? Do you follow the same parenthesis guidelines when dealing with classes, methods, try catch blocks, switch statements, if else blocks, etc. Do you line up fields on a column? Do you notate/prefix private variables with an underscore? Do you follow any naming conventions to make it easier to find particulars in a file? How do you order the members of your class? What about suggestions for namespaces, packaging or source code folder/organization standards? I tend to start with something like:.....ClassName I'm curious to see if there are other, more accepted, practices than what I am accustomed to -- before I venture off dictating these standards. Links to standards already published online would be great too -- even though I've done a bit of that already.
TITLE: Standards Document QUESTION: I am writing a coding standards document for a team of about 15 developers with a project load of between 10 and 15 projects a year. Amongst other sections (which I may post here as I get to them) I am writing a section on code formatting. So to start with, I think it is wise that, for whatever reason, we establish some basic, consistent code formatting/naming standards. I've looked at roughly 10 projects written over the last 3 years from this team and I'm, obviously, finding a pretty wide range of styles. Contractors come in and out and at times, and sometimes even double the team size. I am looking for a few suggestions for code formatting and naming standards that have really paid off... but that can also really be justified. I think consistency and shared-patterns go a long way to making the code more maintainable... but, are there other things I ought to consider when defining said standards? How do you lineup parenthesis? Do you follow the same parenthesis guidelines when dealing with classes, methods, try catch blocks, switch statements, if else blocks, etc. Do you line up fields on a column? Do you notate/prefix private variables with an underscore? Do you follow any naming conventions to make it easier to find particulars in a file? How do you order the members of your class? What about suggestions for namespaces, packaging or source code folder/organization standards? I tend to start with something like:.....ClassName I'm curious to see if there are other, more accepted, practices than what I am accustomed to -- before I venture off dictating these standards. Links to standards already published online would be great too -- even though I've done a bit of that already. ANSWER: First find a automated code-formatter that works with your language. Reason: Whatever the document says, people will inevitably break the rules. It's much easier to run code through a formatter than to nit-pick in a code review. If you're using a language with an existing standard (e.g. Java, C#), it's easiest to use it, or at least start with it as a first draft. Sun put a lot of thought into their formatting rules; you might as well take advantage of it. In any case, remember that much research has shown that varying things like brace position and whitespace use has no measurable effect on productivity or understandability or prevalence of bugs. Just having any standard is the key.
[ "coding-style" ]
5
3
424
4
0
2008-09-06T16:52:32.807000
2008-09-07T03:34:30.563000
47,676
444,367
Tomcat vs Weblogic JNDI Lookup
The Weblogic servers we are using have been configured to allow JNDI datasource names like "appds". For development (localhost), we might be running Tomcat and when declared in the section of server.xml, Tomcat will hang JNDI datasources on "java:comp/env/jdbc/*" in the JNDI tree. Problem: in Weblogic, the JNDI lookup is "appds" whilst in Tomcat, it seems that that I must provide the formal "java:comp/env/jdbc/appds". I'm afraid the Tomcat version is an implicit standard but unfortunately, I can't change Weblogic's config... so that means we end up with two different spring config files (we're using spring 2.5) to facilitate the different environments. Is there an elegant way to address this. Can I look JNDI names up directly in Tomcat? Can Spring take a name and look in both places? Google searches or suggestions would be great.
JndiLocatorSupport has a property resourceRef. When setting this true, "java:comp/env/" prefix will be prepended automatically. So I believe it would be correct to differentiate this parameter when moving from Tomcat to Weblogic.
Tomcat vs Weblogic JNDI Lookup The Weblogic servers we are using have been configured to allow JNDI datasource names like "appds". For development (localhost), we might be running Tomcat and when declared in the section of server.xml, Tomcat will hang JNDI datasources on "java:comp/env/jdbc/*" in the JNDI tree. Problem: in Weblogic, the JNDI lookup is "appds" whilst in Tomcat, it seems that that I must provide the formal "java:comp/env/jdbc/appds". I'm afraid the Tomcat version is an implicit standard but unfortunately, I can't change Weblogic's config... so that means we end up with two different spring config files (we're using spring 2.5) to facilitate the different environments. Is there an elegant way to address this. Can I look JNDI names up directly in Tomcat? Can Spring take a name and look in both places? Google searches or suggestions would be great.
TITLE: Tomcat vs Weblogic JNDI Lookup QUESTION: The Weblogic servers we are using have been configured to allow JNDI datasource names like "appds". For development (localhost), we might be running Tomcat and when declared in the section of server.xml, Tomcat will hang JNDI datasources on "java:comp/env/jdbc/*" in the JNDI tree. Problem: in Weblogic, the JNDI lookup is "appds" whilst in Tomcat, it seems that that I must provide the formal "java:comp/env/jdbc/appds". I'm afraid the Tomcat version is an implicit standard but unfortunately, I can't change Weblogic's config... so that means we end up with two different spring config files (we're using spring 2.5) to facilitate the different environments. Is there an elegant way to address this. Can I look JNDI names up directly in Tomcat? Can Spring take a name and look in both places? Google searches or suggestions would be great. ANSWER: JndiLocatorSupport has a property resourceRef. When setting this true, "java:comp/env/" prefix will be prepended automatically. So I believe it would be correct to differentiate this parameter when moving from Tomcat to Weblogic.
[ "java", "tomcat", "jakarta-ee", "weblogic", "jndi" ]
25
12
48,913
8
0
2008-09-06T17:13:14.053000
2009-01-14T19:37:29.273000
47,683
47,963
Reconnecting JMS listener to JBossMQ
We have a Java listener that reads text messages off of a queue in JBossMQ. If we have to reboot JBoss, the listener will not reconnect and start reading messages again. We just get messages in the listener's log file every 2 minutes saying it can't connect. Is there something we're not setting in our code or in JBossMQ? I'm new to JMS so any help will be greatly appreciated. Thanks.
You should implement in your client code javax.jms.ExceptionListener. You will need a method called onException. When the client's connection is lost, you should get a JMSException, and this method will be called automatically. The only thing you have to look out for is if you are intentionally disconnecting from JBossMQ-- that will also throw an exception. Some code might look like this: public void onException (JMSException jsme) { if (!closeRequested) { this.disconnect(); this.establishConnection(connectionProps, queueName, uname, pword, clientID, messageSelector); } else { //Client requested close so do not try to reconnect } } In your "establishConnection" code, you would then implement a while(!initialized) construct that contains a try/catch inside of it. Until you are sure you have connected and subscribed properly, stay inside the while loop catching all JMS/Naming/etc. exceptions. We've used this method for years with JBossMQ and it works great. We have never had a problem with our JMS clients not reconnecting after bouncing JBossMQ or losing our network connection.
Reconnecting JMS listener to JBossMQ We have a Java listener that reads text messages off of a queue in JBossMQ. If we have to reboot JBoss, the listener will not reconnect and start reading messages again. We just get messages in the listener's log file every 2 minutes saying it can't connect. Is there something we're not setting in our code or in JBossMQ? I'm new to JMS so any help will be greatly appreciated. Thanks.
TITLE: Reconnecting JMS listener to JBossMQ QUESTION: We have a Java listener that reads text messages off of a queue in JBossMQ. If we have to reboot JBoss, the listener will not reconnect and start reading messages again. We just get messages in the listener's log file every 2 minutes saying it can't connect. Is there something we're not setting in our code or in JBossMQ? I'm new to JMS so any help will be greatly appreciated. Thanks. ANSWER: You should implement in your client code javax.jms.ExceptionListener. You will need a method called onException. When the client's connection is lost, you should get a JMSException, and this method will be called automatically. The only thing you have to look out for is if you are intentionally disconnecting from JBossMQ-- that will also throw an exception. Some code might look like this: public void onException (JMSException jsme) { if (!closeRequested) { this.disconnect(); this.establishConnection(connectionProps, queueName, uname, pword, clientID, messageSelector); } else { //Client requested close so do not try to reconnect } } In your "establishConnection" code, you would then implement a while(!initialized) construct that contains a try/catch inside of it. Until you are sure you have connected and subscribed properly, stay inside the while loop catching all JMS/Naming/etc. exceptions. We've used this method for years with JBossMQ and it works great. We have never had a problem with our JMS clients not reconnecting after bouncing JBossMQ or losing our network connection.
[ "java", "jboss", "jms", "jbossmq" ]
13
10
10,172
4
0
2008-09-06T17:33:00.247000
2008-09-07T00:05:10.490000
47,685
68,212
How can I reformat XAML nicely in VS 2008?
Visual Studio 2008's XAML editor (SP1) cannot reformat the XML into a consistent style. Which tools can I use to get a nicely formatted XAML file? Studio integration preferred.
Here's a link that is specific to VS2008 XAML formatting but the good news is you can do it directly inside VS. Link
How can I reformat XAML nicely in VS 2008? Visual Studio 2008's XAML editor (SP1) cannot reformat the XML into a consistent style. Which tools can I use to get a nicely formatted XAML file? Studio integration preferred.
TITLE: How can I reformat XAML nicely in VS 2008? QUESTION: Visual Studio 2008's XAML editor (SP1) cannot reformat the XML into a consistent style. Which tools can I use to get a nicely formatted XAML file? Studio integration preferred. ANSWER: Here's a link that is specific to VS2008 XAML formatting but the good news is you can do it directly inside VS. Link
[ ".net", "wpf", "xaml", "formatting" ]
4
4
4,116
8
0
2008-09-06T17:33:38.310000
2008-09-16T00:23:03.727000
47,692
47,729
How do I become "test infected" with TDD?
I keep reading about people who are "test infected", meaning that they don't just "get" TDD but also can't live without it. They've "had the makeover" as it were. The question is, how do I get like that?
Part of the point of being "test infected" is that you've used TDD enough and seen the successes enough that you don't want to code without it. Once you've gone through a cycle of writing tests first, then coding and refactoring and seeing your bug counts go down and your code get better as a result, not only does it become second nature like Zxaos said, you have a hard time going back to Code First. This is being test infected.
How do I become "test infected" with TDD? I keep reading about people who are "test infected", meaning that they don't just "get" TDD but also can't live without it. They've "had the makeover" as it were. The question is, how do I get like that?
TITLE: How do I become "test infected" with TDD? QUESTION: I keep reading about people who are "test infected", meaning that they don't just "get" TDD but also can't live without it. They've "had the makeover" as it were. The question is, how do I get like that? ANSWER: Part of the point of being "test infected" is that you've used TDD enough and seen the successes enough that you don't want to code without it. Once you've gone through a cycle of writing tests first, then coding and refactoring and seeing your bug counts go down and your code get better as a result, not only does it become second nature like Zxaos said, you have a hard time going back to Code First. This is being test infected.
[ "unit-testing", "testing", "tdd" ]
10
16
2,264
4
0
2008-09-06T17:57:51.620000
2008-09-06T18:47:46.323000