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
21,560
21,967
How to enable multisampling for a wxWidgets OpenGL program?
Multisampling is a way of applying full screen anti-aliasing (FSAA) in 3D applications. I need to use multisampling in my OpenGL program, which is currently embedded in a wxWidgets GUI. Is there a way to do this? Please respond only if you know the detailed steps to achieve this. I'm aware of enabling multisampling using WGL (Win32 extensions to OpenGL). However, since my OpenGL program isn't written in MFC (and I want the code to be multi-platform portable), that's not an option for me.
I finally got Multisampling working with my wxWidgets OpenGL program. It's a bit messy right now, but here's how: wxWidgets doesn't have Multisampling support in their stable releases right now (latest version at this time is 2.8.8 ). But, it's available as a patch and also through their daily snapshot. (The latter is heartening, since it means that the patch has been accepted and should appear in later stable releases if there are no issues.) So, there are 2 options: Download and build from their daily snapshot. Get the patch for your working wxWidgets installation. I found the 2nd option to be less cumbersome, since I don't want to disturb my working installation as much as possible. If you don't know how to patch on Windows, see this. At the very least, for Windows, the patch will modify the following files: $(WX_WIDGETS_ROOT)/include/wx/glcanvas.h $(WX_WIDGETS_ROOT)/include/wx/msw/glcanvas.h $(WX_WIDGETS_ROOT)/src/msw/glcanvas.cpp After patching, recompile the wxWidgets libraries. To enable multisampling in your wxWidgets OpenGL program, minor changes to the code are required. An attribute list needs to be passed to the wxGLCanvas constructor: int attribList[] = {WX_GL_RGBA, WX_GL_DOUBLEBUFFER, WX_GL_SAMPLE_BUFFERS, GL_TRUE, // Multi-sampling WX_GL_DEPTH_SIZE, 16, 0, 0}; If you were already using an attribute list, then add the line with GL_SAMPLE_BUFFERS, GL_TRUE to it. Else, add this attribute list definition to your code. Then modify your wxGLCanvas constructor to take this attribute list as a parameter: myGLFrame::myGLFrame // Derived from wxGLCanvas ( wxWindow *parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style, const wxString& name ): wxGLCanvas(parent, (wxGLCanvas*) NULL, id, pos, size, style, name, attribList) { //... } After the wxGLCanvas element is created, multisampling is turned on by default. To disable or enable it at will, use the related OpenGL calls: glEnable(GL_MULTISAMPLE); glDisable(GL_MULTISAMPLE); Multisampling should now work with the wxWidgets OpenGL program. Hopefully, it should be supported in the stable release of wxWidgets soon, making this information irrelevant:-)
How to enable multisampling for a wxWidgets OpenGL program? Multisampling is a way of applying full screen anti-aliasing (FSAA) in 3D applications. I need to use multisampling in my OpenGL program, which is currently embedded in a wxWidgets GUI. Is there a way to do this? Please respond only if you know the detailed steps to achieve this. I'm aware of enabling multisampling using WGL (Win32 extensions to OpenGL). However, since my OpenGL program isn't written in MFC (and I want the code to be multi-platform portable), that's not an option for me.
TITLE: How to enable multisampling for a wxWidgets OpenGL program? QUESTION: Multisampling is a way of applying full screen anti-aliasing (FSAA) in 3D applications. I need to use multisampling in my OpenGL program, which is currently embedded in a wxWidgets GUI. Is there a way to do this? Please respond only if you know the detailed steps to achieve this. I'm aware of enabling multisampling using WGL (Win32 extensions to OpenGL). However, since my OpenGL program isn't written in MFC (and I want the code to be multi-platform portable), that's not an option for me. ANSWER: I finally got Multisampling working with my wxWidgets OpenGL program. It's a bit messy right now, but here's how: wxWidgets doesn't have Multisampling support in their stable releases right now (latest version at this time is 2.8.8 ). But, it's available as a patch and also through their daily snapshot. (The latter is heartening, since it means that the patch has been accepted and should appear in later stable releases if there are no issues.) So, there are 2 options: Download and build from their daily snapshot. Get the patch for your working wxWidgets installation. I found the 2nd option to be less cumbersome, since I don't want to disturb my working installation as much as possible. If you don't know how to patch on Windows, see this. At the very least, for Windows, the patch will modify the following files: $(WX_WIDGETS_ROOT)/include/wx/glcanvas.h $(WX_WIDGETS_ROOT)/include/wx/msw/glcanvas.h $(WX_WIDGETS_ROOT)/src/msw/glcanvas.cpp After patching, recompile the wxWidgets libraries. To enable multisampling in your wxWidgets OpenGL program, minor changes to the code are required. An attribute list needs to be passed to the wxGLCanvas constructor: int attribList[] = {WX_GL_RGBA, WX_GL_DOUBLEBUFFER, WX_GL_SAMPLE_BUFFERS, GL_TRUE, // Multi-sampling WX_GL_DEPTH_SIZE, 16, 0, 0}; If you were already using an attribute list, then add the line with GL_SAMPLE_BUFFERS, GL_TRUE to it. Else, add this attribute list definition to your code. Then modify your wxGLCanvas constructor to take this attribute list as a parameter: myGLFrame::myGLFrame // Derived from wxGLCanvas ( wxWindow *parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style, const wxString& name ): wxGLCanvas(parent, (wxGLCanvas*) NULL, id, pos, size, style, name, attribList) { //... } After the wxGLCanvas element is created, multisampling is turned on by default. To disable or enable it at will, use the related OpenGL calls: glEnable(GL_MULTISAMPLE); glDisable(GL_MULTISAMPLE); Multisampling should now work with the wxWidgets OpenGL program. Hopefully, it should be supported in the stable release of wxWidgets soon, making this information irrelevant:-)
[ "opengl", "wxwidgets", "multisampling" ]
3
4
3,804
1
0
2008-08-22T01:16:26.817000
2008-08-22T09:13:56.527000
21,564
21,620
Is there a Unix utility to prepend timestamps to stdin?
I ended up writing a quick little script for this in Python, but I was wondering if there was a utility you could feed text into which would prepend each line with some text -- in my specific case, a timestamp. Ideally, the use would be something like: cat somefile.txt | prepend-timestamp (Before you answer sed, I tried this: cat somefile.txt | sed "s/^/`date`/" But that only evaluates the date command once when sed is executed, so the same timestamp is incorrectly prepended to each line.)
Could try using awk: | awk '{ print strftime("%Y-%m-%d %H:%M:%S"), $0; fflush(); }' You may need to make sure that produces line buffered output, i.e. it flushes its output stream after each line; the timestamp awk adds will be the time that the end of the line appeared on its input pipe. If awk shows errors, then try gawk instead.
Is there a Unix utility to prepend timestamps to stdin? I ended up writing a quick little script for this in Python, but I was wondering if there was a utility you could feed text into which would prepend each line with some text -- in my specific case, a timestamp. Ideally, the use would be something like: cat somefile.txt | prepend-timestamp (Before you answer sed, I tried this: cat somefile.txt | sed "s/^/`date`/" But that only evaluates the date command once when sed is executed, so the same timestamp is incorrectly prepended to each line.)
TITLE: Is there a Unix utility to prepend timestamps to stdin? QUESTION: I ended up writing a quick little script for this in Python, but I was wondering if there was a utility you could feed text into which would prepend each line with some text -- in my specific case, a timestamp. Ideally, the use would be something like: cat somefile.txt | prepend-timestamp (Before you answer sed, I tried this: cat somefile.txt | sed "s/^/`date`/" But that only evaluates the date command once when sed is executed, so the same timestamp is incorrectly prepended to each line.) ANSWER: Could try using awk: | awk '{ print strftime("%Y-%m-%d %H:%M:%S"), $0; fflush(); }' You may need to make sure that produces line buffered output, i.e. it flushes its output stream after each line; the timestamp awk adds will be the time that the end of the line appeared on its input pipe. If awk shows errors, then try gawk instead.
[ "unix", "shell", "awk" ]
186
195
78,927
19
0
2008-08-22T01:24:34.817000
2008-08-22T01:53:25.837000
21,574
21,621
What is the difference between Ruby 1.8 and Ruby 1.9
I'm not clear on the differences between the "current" version of Ruby (1.8) and the "new" version (1.9). Is there an "easy" or a "simple" explanation of the differences and why it is so different?
Sam Ruby has a cool slideshow that outline the differences. In the interest of bringing this information inline for easier reference, and in case the link goes dead in the abstract future, here's an overview of Sam's slides. The slideshow is less overwhelming to review, but having it all laid out in a list like this is also helpful. Ruby 1.9 - Major Features Performance Threads/Fibers Encoding/Unicode gems is (mostly) built-in now if statements do not introduce scope in Ruby. What's changed? Single character strings. Ruby 1.9 irb(main):001:0>?c => "c" Ruby 1.8.6 irb(main):001:0>?c => 99 String index. Ruby 1.9 irb(main):001:0> "cat"[1] => "a" Ruby 1.8.6 irb(main):001:0> "cat"[1] => 97 {"a","b"} No Longer Supported Ruby 1.9 irb(main):002:0> {1,2} SyntaxError: (irb):2: syntax error, unexpected ',', expecting tASSOC Ruby 1.8.6 irb(main):001:0> {1,2} => {1=>2} Action: Convert to {1 => 2} Array.to_s Now Contains Punctuation Ruby 1.9 irb(main):001:0> [1,2,3].to_s => "[1, 2, 3]" Ruby 1.8.6 irb(main):001:0> [1,2,3].to_s => "123" Action: Use.join instead Colon No Longer Valid In When Statements Ruby 1.9 irb(main):001:0> case 'a'; when /\w/: puts 'word'; end SyntaxError: (irb):1: syntax error, unexpected ':', expecting keyword_then or ',' or ';' or '\n' Ruby 1.8.6 irb(main):001:0> case 'a'; when /\w/: puts 'word'; end word Action: Use semicolon, then, or newline Block Variables Now Shadow Local Variables Ruby 1.9 irb(main):001:0> i=0; [1,2,3].each {|i|}; i => 0 irb(main):002:0> i=0; for i in [1,2,3]; end; i => 3 Ruby 1.8.6 irb(main):001:0> i=0; [1,2,3].each {|i|}; i => 3 Hash.index Deprecated Ruby 1.9 irb(main):001:0> {1=>2}.index(2) (irb):18: warning: Hash#index is deprecated; use Hash#key => 1 irb(main):002:0> {1=>2}.key(2) => 1 Ruby 1.8.6 irb(main):001:0> {1=>2}.index(2) => 1 Action: Use Hash.key Fixnum.to_sym Now Gone Ruby 1.9 irb(main):001:0> 5.to_sym NoMethodError: undefined method 'to_sym' for 5:Fixnum Ruby 1.8.6 irb(main):001:0> 5.to_sym => nil (Cont'd) Ruby 1.9 # Find an argument value by name or index. def [](index) lookup(index.to_sym) end svn.ruby-lang.org/repos/ruby/trunk/lib/rake.rb Hash Keys Now Unordered Ruby 1.9 irb(main):001:0> {:a=>"a",:c=>"c",:b=>"b"} => {:a=>"a",:c=>"c",:b=>"b"} Ruby 1.8.6 irb(main):001:0> {:a=>"a",:c=>"c",:b=>"b"} => {:a=>"a",:b=>"b",:c=>"c"} Order is insertion order Stricter Unicode Regular Expressions Ruby 1.9 irb(main):001:0> /\x80/u SyntaxError: (irb):2: invalid multibyte escape: /\x80/ Ruby 1.8.6 irb(main):001:0> /\x80/u => /\x80/u tr and Regexp Now Understand Unicode Ruby 1.9 unicode(string).tr(CP1252_DIFFERENCES, UNICODE_EQUIVALENT). gsub(INVALID_XML_CHAR, REPLACEMENT_CHAR). gsub(XML_PREDEFINED) {|c| PREDEFINED[c.ord]} pack and unpack Ruby 1.8.6 def xchr(escape=true) n = XChar::CP1252[self] || self case n when *XChar::VALID XChar::PREDEFINED[n] or (n>128? n.chr: (escape? "&##{n};": [n].pack('U*'))) else Builder::XChar::REPLACEMENT_CHAR end end unpack('U*').map {|n| n.xchr(escape)}.join BasicObject More Brutal Than BlankSlate Ruby 1.9 irb(main):001:0> class C < BasicObject; def f; Math::PI; end; end; C.new.f NameError: uninitialized constant C::Math Ruby 1.8.6 irb(main):001:0> require 'blankslate' => true irb(main):002:0> class C < BlankSlate; def f; Math::PI; end; end; C.new.f => 3.14159265358979 Action: Use::Math::PI Delegation Changes Ruby 1.9 irb(main):002:0> class C < SimpleDelegator; end => nil irb(main):003:0> C.new('').class => String Ruby 1.8.6 irb(main):002:0> class C < SimpleDelegator; end => nil irb(main):003:0> C.new('').class => C irb(main):004:0> Defect 17700 Use of $KCODE Produces Warnings Ruby 1.9 irb(main):004:1> $KCODE = 'UTF8' (irb):4: warning: variable $KCODE is no longer effective; ignored => "UTF8" Ruby 1.8.6 irb(main):001:0> $KCODE = 'UTF8' => "UTF8" instance_methods Now an Array of Symbols Ruby 1.9 irb(main):001:0> {}.methods.sort.last =>:zip Ruby 1.8.6 irb(main):001:0> {}.methods.sort.last => "zip" Action: Replace instance_methods.include? with method_defined? Source File Encoding Basic # coding: utf-8 Emacs # -*- encoding: utf-8 -*- Shebang #!/usr/local/rubybook/bin/ruby # encoding: utf-8 Real Threading Race Conditions Implicit Ordering Assumptions Test Code What's New? Alternate Syntax for Symbol as Hash Keys Ruby 1.9 {a: b} redirect_to action: show Ruby 1.8.6 {:a => b} redirect_to:action => show Block Local Variables Ruby 1.9 [1,2].each {|value; t| t=value*value} Inject Methods Ruby 1.9 [1,2].inject(:+) Ruby 1.8.6 [1,2].inject {|a,b| a+b} to_enum Ruby 1.9 short_enum = [1, 2, 3].to_enum long_enum = ('a'..'z').to_enum loop do puts "#{short_enum.next} #{long_enum.next}" end No block? Enum! Ruby 1.9 e = [1,2,3].each Lambda Shorthand Ruby 1.9 p = -> a,b,c {a+b+c} puts p.(1,2,3) puts p[1,2,3] Ruby 1.8.6 p = lambda {|a,b,c| a+b+c} puts p.call(1,2,3) Complex Numbers Ruby 1.9 Complex(3,4) == 3 + 4.im Decimal Is Still Not The Default Ruby 1.9 irb(main):001:0> 1.2-1.1 => 0.0999999999999999 Regex “Properties” Ruby 1.9 /\p{Space}/ Ruby 1.8.6 /[:space:]/ Splat in Middle Ruby 1.9 def foo(first, *middle, last) (->a, *b, c {p a-c}).(*5.downto(1)) Fibers Ruby 1.9 f = Fiber.new do a,b = 0,1 Fiber.yield a Fiber.yield b loop do a,b = b,a+b Fiber.yield b end end 10.times {puts f.resume} Break Values Ruby 1.9 match = while line = gets next if line =~ /^#/ break line if line.find('ruby') end “Nested” Methods Ruby 1.9 def toggle def toggle "subsequent times" end "first time" end HTH!
What is the difference between Ruby 1.8 and Ruby 1.9 I'm not clear on the differences between the "current" version of Ruby (1.8) and the "new" version (1.9). Is there an "easy" or a "simple" explanation of the differences and why it is so different?
TITLE: What is the difference between Ruby 1.8 and Ruby 1.9 QUESTION: I'm not clear on the differences between the "current" version of Ruby (1.8) and the "new" version (1.9). Is there an "easy" or a "simple" explanation of the differences and why it is so different? ANSWER: Sam Ruby has a cool slideshow that outline the differences. In the interest of bringing this information inline for easier reference, and in case the link goes dead in the abstract future, here's an overview of Sam's slides. The slideshow is less overwhelming to review, but having it all laid out in a list like this is also helpful. Ruby 1.9 - Major Features Performance Threads/Fibers Encoding/Unicode gems is (mostly) built-in now if statements do not introduce scope in Ruby. What's changed? Single character strings. Ruby 1.9 irb(main):001:0>?c => "c" Ruby 1.8.6 irb(main):001:0>?c => 99 String index. Ruby 1.9 irb(main):001:0> "cat"[1] => "a" Ruby 1.8.6 irb(main):001:0> "cat"[1] => 97 {"a","b"} No Longer Supported Ruby 1.9 irb(main):002:0> {1,2} SyntaxError: (irb):2: syntax error, unexpected ',', expecting tASSOC Ruby 1.8.6 irb(main):001:0> {1,2} => {1=>2} Action: Convert to {1 => 2} Array.to_s Now Contains Punctuation Ruby 1.9 irb(main):001:0> [1,2,3].to_s => "[1, 2, 3]" Ruby 1.8.6 irb(main):001:0> [1,2,3].to_s => "123" Action: Use.join instead Colon No Longer Valid In When Statements Ruby 1.9 irb(main):001:0> case 'a'; when /\w/: puts 'word'; end SyntaxError: (irb):1: syntax error, unexpected ':', expecting keyword_then or ',' or ';' or '\n' Ruby 1.8.6 irb(main):001:0> case 'a'; when /\w/: puts 'word'; end word Action: Use semicolon, then, or newline Block Variables Now Shadow Local Variables Ruby 1.9 irb(main):001:0> i=0; [1,2,3].each {|i|}; i => 0 irb(main):002:0> i=0; for i in [1,2,3]; end; i => 3 Ruby 1.8.6 irb(main):001:0> i=0; [1,2,3].each {|i|}; i => 3 Hash.index Deprecated Ruby 1.9 irb(main):001:0> {1=>2}.index(2) (irb):18: warning: Hash#index is deprecated; use Hash#key => 1 irb(main):002:0> {1=>2}.key(2) => 1 Ruby 1.8.6 irb(main):001:0> {1=>2}.index(2) => 1 Action: Use Hash.key Fixnum.to_sym Now Gone Ruby 1.9 irb(main):001:0> 5.to_sym NoMethodError: undefined method 'to_sym' for 5:Fixnum Ruby 1.8.6 irb(main):001:0> 5.to_sym => nil (Cont'd) Ruby 1.9 # Find an argument value by name or index. def [](index) lookup(index.to_sym) end svn.ruby-lang.org/repos/ruby/trunk/lib/rake.rb Hash Keys Now Unordered Ruby 1.9 irb(main):001:0> {:a=>"a",:c=>"c",:b=>"b"} => {:a=>"a",:c=>"c",:b=>"b"} Ruby 1.8.6 irb(main):001:0> {:a=>"a",:c=>"c",:b=>"b"} => {:a=>"a",:b=>"b",:c=>"c"} Order is insertion order Stricter Unicode Regular Expressions Ruby 1.9 irb(main):001:0> /\x80/u SyntaxError: (irb):2: invalid multibyte escape: /\x80/ Ruby 1.8.6 irb(main):001:0> /\x80/u => /\x80/u tr and Regexp Now Understand Unicode Ruby 1.9 unicode(string).tr(CP1252_DIFFERENCES, UNICODE_EQUIVALENT). gsub(INVALID_XML_CHAR, REPLACEMENT_CHAR). gsub(XML_PREDEFINED) {|c| PREDEFINED[c.ord]} pack and unpack Ruby 1.8.6 def xchr(escape=true) n = XChar::CP1252[self] || self case n when *XChar::VALID XChar::PREDEFINED[n] or (n>128? n.chr: (escape? "&##{n};": [n].pack('U*'))) else Builder::XChar::REPLACEMENT_CHAR end end unpack('U*').map {|n| n.xchr(escape)}.join BasicObject More Brutal Than BlankSlate Ruby 1.9 irb(main):001:0> class C < BasicObject; def f; Math::PI; end; end; C.new.f NameError: uninitialized constant C::Math Ruby 1.8.6 irb(main):001:0> require 'blankslate' => true irb(main):002:0> class C < BlankSlate; def f; Math::PI; end; end; C.new.f => 3.14159265358979 Action: Use::Math::PI Delegation Changes Ruby 1.9 irb(main):002:0> class C < SimpleDelegator; end => nil irb(main):003:0> C.new('').class => String Ruby 1.8.6 irb(main):002:0> class C < SimpleDelegator; end => nil irb(main):003:0> C.new('').class => C irb(main):004:0> Defect 17700 Use of $KCODE Produces Warnings Ruby 1.9 irb(main):004:1> $KCODE = 'UTF8' (irb):4: warning: variable $KCODE is no longer effective; ignored => "UTF8" Ruby 1.8.6 irb(main):001:0> $KCODE = 'UTF8' => "UTF8" instance_methods Now an Array of Symbols Ruby 1.9 irb(main):001:0> {}.methods.sort.last =>:zip Ruby 1.8.6 irb(main):001:0> {}.methods.sort.last => "zip" Action: Replace instance_methods.include? with method_defined? Source File Encoding Basic # coding: utf-8 Emacs # -*- encoding: utf-8 -*- Shebang #!/usr/local/rubybook/bin/ruby # encoding: utf-8 Real Threading Race Conditions Implicit Ordering Assumptions Test Code What's New? Alternate Syntax for Symbol as Hash Keys Ruby 1.9 {a: b} redirect_to action: show Ruby 1.8.6 {:a => b} redirect_to:action => show Block Local Variables Ruby 1.9 [1,2].each {|value; t| t=value*value} Inject Methods Ruby 1.9 [1,2].inject(:+) Ruby 1.8.6 [1,2].inject {|a,b| a+b} to_enum Ruby 1.9 short_enum = [1, 2, 3].to_enum long_enum = ('a'..'z').to_enum loop do puts "#{short_enum.next} #{long_enum.next}" end No block? Enum! Ruby 1.9 e = [1,2,3].each Lambda Shorthand Ruby 1.9 p = -> a,b,c {a+b+c} puts p.(1,2,3) puts p[1,2,3] Ruby 1.8.6 p = lambda {|a,b,c| a+b+c} puts p.call(1,2,3) Complex Numbers Ruby 1.9 Complex(3,4) == 3 + 4.im Decimal Is Still Not The Default Ruby 1.9 irb(main):001:0> 1.2-1.1 => 0.0999999999999999 Regex “Properties” Ruby 1.9 /\p{Space}/ Ruby 1.8.6 /[:space:]/ Splat in Middle Ruby 1.9 def foo(first, *middle, last) (->a, *b, c {p a-c}).(*5.downto(1)) Fibers Ruby 1.9 f = Fiber.new do a,b = 0,1 Fiber.yield a Fiber.yield b loop do a,b = b,a+b Fiber.yield b end end 10.times {puts f.resume} Break Values Ruby 1.9 match = while line = gets next if line =~ /^#/ break line if line.find('ruby') end “Nested” Methods Ruby 1.9 def toggle def toggle "subsequent times" end "first time" end HTH!
[ "ruby", "ruby-1.9", "ruby-1.8" ]
103
169
42,465
4
0
2008-08-22T01:32:54.937000
2008-08-22T01:53:44.310000
21,583
21,603
Unit-Testing Databases
This past summer I was developing a basic ASP.NET/SQL Server CRUD app, and unit testing was one of the requirements. I ran into some trouble when I tried to test against the database. To my understanding, unit tests should be: stateless independent from each other repeatable with the same results i.e. no persisting changes These requirements seem to be at odds with each other when developing for a database. For example, I can't test Insert() without making sure the rows to be inserted aren't there yet, thus I need to call the Delete() first. But, what if they aren't already there? Then I would need to call the Exists() function first. My eventual solution involved very large setup functions (yuck!) and an empty test case which would run first and indicate that the setup ran without problems. This is sacrificing on the independence of the tests while maintaining their statelessness. Another solution I found is to wrap the function calls in a transaction which can be easily rolled back, like Roy Osherove's XtUnit. This work, but it involves another library, another dependency, and it seems a little too heavy of a solution for the problem at hand. So, what has the SO community done when confronted with this situation? tgmdbm said: You typically use your favourite automated unit testing framework to perform integration tests, which is why some people get confused, but they don't follow the same rules. You are allowed to involve the concrete implementation of many of your classes (because they've been unit tested). You are testing how your concrete classes interact with each other and with the database. So if I read this correctly, there is really no way to effectively unit-test a Data Access Layer. Or, would a "unit test" of a Data Access Layer involve testing, say, the SQL/commands generated by the classes, independent of actual interaction with the database?
There's no real way to unit test a database other than asserting that the tables exist, contain the expected columns, and have the appropriate constraints. But that's usually not really worth doing. You don't typically unit test the database. You usually involve the database in integration tests. You typically use your favourite automated unit testing framework to perform integration tests, which is why some people get confused, but they don't follow the same rules. You are allowed to involve the concrete implementation of many of your classes (because they've been unit tested). You are testing how your concrete classes interact with each other and with the database.
Unit-Testing Databases This past summer I was developing a basic ASP.NET/SQL Server CRUD app, and unit testing was one of the requirements. I ran into some trouble when I tried to test against the database. To my understanding, unit tests should be: stateless independent from each other repeatable with the same results i.e. no persisting changes These requirements seem to be at odds with each other when developing for a database. For example, I can't test Insert() without making sure the rows to be inserted aren't there yet, thus I need to call the Delete() first. But, what if they aren't already there? Then I would need to call the Exists() function first. My eventual solution involved very large setup functions (yuck!) and an empty test case which would run first and indicate that the setup ran without problems. This is sacrificing on the independence of the tests while maintaining their statelessness. Another solution I found is to wrap the function calls in a transaction which can be easily rolled back, like Roy Osherove's XtUnit. This work, but it involves another library, another dependency, and it seems a little too heavy of a solution for the problem at hand. So, what has the SO community done when confronted with this situation? tgmdbm said: You typically use your favourite automated unit testing framework to perform integration tests, which is why some people get confused, but they don't follow the same rules. You are allowed to involve the concrete implementation of many of your classes (because they've been unit tested). You are testing how your concrete classes interact with each other and with the database. So if I read this correctly, there is really no way to effectively unit-test a Data Access Layer. Or, would a "unit test" of a Data Access Layer involve testing, say, the SQL/commands generated by the classes, independent of actual interaction with the database?
TITLE: Unit-Testing Databases QUESTION: This past summer I was developing a basic ASP.NET/SQL Server CRUD app, and unit testing was one of the requirements. I ran into some trouble when I tried to test against the database. To my understanding, unit tests should be: stateless independent from each other repeatable with the same results i.e. no persisting changes These requirements seem to be at odds with each other when developing for a database. For example, I can't test Insert() without making sure the rows to be inserted aren't there yet, thus I need to call the Delete() first. But, what if they aren't already there? Then I would need to call the Exists() function first. My eventual solution involved very large setup functions (yuck!) and an empty test case which would run first and indicate that the setup ran without problems. This is sacrificing on the independence of the tests while maintaining their statelessness. Another solution I found is to wrap the function calls in a transaction which can be easily rolled back, like Roy Osherove's XtUnit. This work, but it involves another library, another dependency, and it seems a little too heavy of a solution for the problem at hand. So, what has the SO community done when confronted with this situation? tgmdbm said: You typically use your favourite automated unit testing framework to perform integration tests, which is why some people get confused, but they don't follow the same rules. You are allowed to involve the concrete implementation of many of your classes (because they've been unit tested). You are testing how your concrete classes interact with each other and with the database. So if I read this correctly, there is really no way to effectively unit-test a Data Access Layer. Or, would a "unit test" of a Data Access Layer involve testing, say, the SQL/commands generated by the classes, independent of actual interaction with the database? ANSWER: There's no real way to unit test a database other than asserting that the tables exist, contain the expected columns, and have the appropriate constraints. But that's usually not really worth doing. You don't typically unit test the database. You usually involve the database in integration tests. You typically use your favourite automated unit testing framework to perform integration tests, which is why some people get confused, but they don't follow the same rules. You are allowed to involve the concrete implementation of many of your classes (because they've been unit tested). You are testing how your concrete classes interact with each other and with the database.
[ "database", "unit-testing", "transactions", "xtunit" ]
32
26
8,495
9
0
2008-08-22T01:35:33.773000
2008-08-22T01:43:32.523000
21,589
66,513
Is it possible to share a transaction between a .Net application and a COM+ object?
I did some tests a while ago and never figured out how to make this work. The ingredients: COM+ transactional object (developed in VB6).Net web application (with transaction) in IIS that... makes a call to the COM+ component updates a row in a SQL database Testing: Run the.Net application and force an exception. Result: The update made from the.Net application rolls back. The update made by the COM+ object does not roll back. If I call the COM+ object from an old ASP page the rollback works. I know some people may be thinking "what?! COM+ and.Net you must be out of your mind!", but there are some places in this world where there still are a lot of COM+ components. I was just curious if someone ever faced this and if you figured out how to make this work.
Because VB and.NET will use different SQL connections (and there is no way to make ADO and ADO.NET share the same connection), your only possibility is to enlist the DTC (Distributed Transaction Coordinator). The DTC will coordinates the two independent transactions so they commit or are rolled-back together. From.NET, EnterpriseServices manages COM+ functionality, such as the DTC. In.NET 2.0 and forward, you can use the System.Transactions namespace, which makes things a little nicer. I think something like this should work (untested code): void SomeMethod() { EnterpriseServicesInteropOption e = EnterpriseServicesInteropOption.Full; using (TransactionScope s = new TransactionScope(e)) { MyComPlusClass o = new MyComPlusClass(); o.SomeTransactionalMethod(); } } I am not familiar enough with this to give you more advice at this point. On the COM+ side, your object needs to be configured to use (most likely "require") a distributed transaction. You can do that from COM+ Explorer, by going to your object's Properties, selecting the Transaction tab, and clicking on " Required ". I don't remember if you can do this from code as well; VB6 was created before COM+ was released, so it doesn't fully support everything COM+ does (its transactional support was meant for COM+'s predecessor, called MS Transaction Server). If everything works correctly, your COM+ object should be enlisting in the existing Context created by your.NET code. You can use the "Distributed Transaction Coordinator\Transaction List" node in "Component Services" to check and see the distributed transaction being created during the call. Be aware that you cannot see the changes from the COM+ component reflected on data queries from the.NET side until the Transaction is committed! In fact, it is possible to deadlock! Remember that DTC will make sure that the two transactions are paired, but they are still separate database transactions.
Is it possible to share a transaction between a .Net application and a COM+ object? I did some tests a while ago and never figured out how to make this work. The ingredients: COM+ transactional object (developed in VB6).Net web application (with transaction) in IIS that... makes a call to the COM+ component updates a row in a SQL database Testing: Run the.Net application and force an exception. Result: The update made from the.Net application rolls back. The update made by the COM+ object does not roll back. If I call the COM+ object from an old ASP page the rollback works. I know some people may be thinking "what?! COM+ and.Net you must be out of your mind!", but there are some places in this world where there still are a lot of COM+ components. I was just curious if someone ever faced this and if you figured out how to make this work.
TITLE: Is it possible to share a transaction between a .Net application and a COM+ object? QUESTION: I did some tests a while ago and never figured out how to make this work. The ingredients: COM+ transactional object (developed in VB6).Net web application (with transaction) in IIS that... makes a call to the COM+ component updates a row in a SQL database Testing: Run the.Net application and force an exception. Result: The update made from the.Net application rolls back. The update made by the COM+ object does not roll back. If I call the COM+ object from an old ASP page the rollback works. I know some people may be thinking "what?! COM+ and.Net you must be out of your mind!", but there are some places in this world where there still are a lot of COM+ components. I was just curious if someone ever faced this and if you figured out how to make this work. ANSWER: Because VB and.NET will use different SQL connections (and there is no way to make ADO and ADO.NET share the same connection), your only possibility is to enlist the DTC (Distributed Transaction Coordinator). The DTC will coordinates the two independent transactions so they commit or are rolled-back together. From.NET, EnterpriseServices manages COM+ functionality, such as the DTC. In.NET 2.0 and forward, you can use the System.Transactions namespace, which makes things a little nicer. I think something like this should work (untested code): void SomeMethod() { EnterpriseServicesInteropOption e = EnterpriseServicesInteropOption.Full; using (TransactionScope s = new TransactionScope(e)) { MyComPlusClass o = new MyComPlusClass(); o.SomeTransactionalMethod(); } } I am not familiar enough with this to give you more advice at this point. On the COM+ side, your object needs to be configured to use (most likely "require") a distributed transaction. You can do that from COM+ Explorer, by going to your object's Properties, selecting the Transaction tab, and clicking on " Required ". I don't remember if you can do this from code as well; VB6 was created before COM+ was released, so it doesn't fully support everything COM+ does (its transactional support was meant for COM+'s predecessor, called MS Transaction Server). If everything works correctly, your COM+ object should be enlisting in the existing Context created by your.NET code. You can use the "Distributed Transaction Coordinator\Transaction List" node in "Component Services" to check and see the distributed transaction being created during the call. Be aware that you cannot see the changes from the COM+ component reflected on data queries from the.NET side until the Transaction is committed! In fact, it is possible to deadlock! Remember that DTC will make sure that the two transactions are paired, but they are still separate database transactions.
[ ".net", "database", "transactions", "com+" ]
4
2
1,462
2
0
2008-08-22T01:39:05.920000
2008-09-15T20:17:25.580000
21,635
21,726
Pushing out MSI files
I have a product which has been traditionally shipped as an MSI file. It is deployed through some sort of SMS push to thousands of desktops by our various clients. The software we use to create these installers is getting long in the tooth and we are looking to replace it. We have already standardized on InstallAnywhere for most of our products as we support many operating systems. Unfortunately InstallAnywhere cannot produce MSI files. I am wondering if it is required that SMS use MSI files or if it can handle other installer types (.exe). If not, are there any open source programmes for creating MSI files?
If your clients are using SMS then you're in the clear... SMS supports EXE. You enter a command line when creating 'Programs' and clients are probably already calling msiexec to launch the MSI. Also I'm pretty sure SMS predates the MSI file format:) However if they're using Active Directory / Group Policy Objects.. then you're SOL as that does depend on MSI format for deployment. If you do want to stick with InstallAnywhere, there are a number of "MSI repackaging" tools available. Assuming you're looking at a basic application (device drivers might be an issue) then repackaging should be a fairly painless process.
Pushing out MSI files I have a product which has been traditionally shipped as an MSI file. It is deployed through some sort of SMS push to thousands of desktops by our various clients. The software we use to create these installers is getting long in the tooth and we are looking to replace it. We have already standardized on InstallAnywhere for most of our products as we support many operating systems. Unfortunately InstallAnywhere cannot produce MSI files. I am wondering if it is required that SMS use MSI files or if it can handle other installer types (.exe). If not, are there any open source programmes for creating MSI files?
TITLE: Pushing out MSI files QUESTION: I have a product which has been traditionally shipped as an MSI file. It is deployed through some sort of SMS push to thousands of desktops by our various clients. The software we use to create these installers is getting long in the tooth and we are looking to replace it. We have already standardized on InstallAnywhere for most of our products as we support many operating systems. Unfortunately InstallAnywhere cannot produce MSI files. I am wondering if it is required that SMS use MSI files or if it can handle other installer types (.exe). If not, are there any open source programmes for creating MSI files? ANSWER: If your clients are using SMS then you're in the clear... SMS supports EXE. You enter a command line when creating 'Programs' and clients are probably already calling msiexec to launch the MSI. Also I'm pretty sure SMS predates the MSI file format:) However if they're using Active Directory / Group Policy Objects.. then you're SOL as that does depend on MSI format for deployment. If you do want to stick with InstallAnywhere, there are a number of "MSI repackaging" tools available. Assuming you're looking at a basic application (device drivers might be an issue) then repackaging should be a fairly painless process.
[ "deployment", "installation", "windows-installer" ]
3
4
1,084
3
0
2008-08-22T02:13:38.363000
2008-08-22T03:32:01.077000
21,640
22,361
.NET - Get protocol, host, and port
Is there a simple way in.NET to quickly get the current protocol, host, and port? For example, if I'm on the following URL: http://www.mywebsite.com:80/pages/page1.aspx I need to return: http://www.mywebsite.com:80 I know I can use Request.Url.AbsoluteUri to get the complete URL, and I know I can use Request.Url.Authority to get the host and port, but I'm not sure of the best way to get the protocol without parsing out the URL string. Any suggestions?
The following (C#) code should do the trick Uri uri = new Uri("http://www.mywebsite.com:80/pages/page1.aspx"); string requested = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port;
.NET - Get protocol, host, and port Is there a simple way in.NET to quickly get the current protocol, host, and port? For example, if I'm on the following URL: http://www.mywebsite.com:80/pages/page1.aspx I need to return: http://www.mywebsite.com:80 I know I can use Request.Url.AbsoluteUri to get the complete URL, and I know I can use Request.Url.Authority to get the host and port, but I'm not sure of the best way to get the protocol without parsing out the URL string. Any suggestions?
TITLE: .NET - Get protocol, host, and port QUESTION: Is there a simple way in.NET to quickly get the current protocol, host, and port? For example, if I'm on the following URL: http://www.mywebsite.com:80/pages/page1.aspx I need to return: http://www.mywebsite.com:80 I know I can use Request.Url.AbsoluteUri to get the complete URL, and I know I can use Request.Url.Authority to get the host and port, but I'm not sure of the best way to get the protocol without parsing out the URL string. Any suggestions? ANSWER: The following (C#) code should do the trick Uri uri = new Uri("http://www.mywebsite.com:80/pages/page1.aspx"); string requested = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port;
[ ".net", "asp.net", "url", "uri", "authority" ]
281
191
200,299
11
0
2008-08-22T02:18:28.307000
2008-08-22T13:35:39.863000
21,647
21,656
Reading from text file until EOF repeats last line
The following C++ code uses a ifstream object to read integers from a text file (which has one number per line) until it hits EOF. Why does it read the integer on the last line twice? How to fix this? Code: #include #include using namespace std; int main() { ifstream iFile("input.txt"); // input.txt has integers, one per line while (!iFile.eof()) { int x; iFile >> x; cerr << x << endl; } return 0; } input.txt: 10 20 30 Output: 10 20 30 30 Note: I've skipped all error checking code to keep the code snippet small. The above behaviour is seen on Windows (Visual C++), cygwin (gcc) and Linux (gcc).
Just follow closely the chain of events. Grab 10 Grab 20 Grab 30 Grab EOF Look at the second-to-last iteration. You grabbed 30, then carried on to check for EOF. You haven't reached EOF because the EOF mark hasn't been read yet ("binarically" speaking, its conceptual location is just after the 30 line). Therefore you carry on to the next iteration. x is still 30 from previous iteration. Now you read from the stream and you get EOF. x remains 30 and the ios::eofbit is raised. You output to stderr x (which is 30, just like in the previous iteration). Next you check for EOF in the loop condition, and this time you're out of the loop. Try this: while (true) { int x; iFile >> x; if( iFile.eof() ) break; cerr << x << endl; } By the way, there is another bug in your code. Did you ever try to run it on an empty file? The behaviour you get is for the exact same reason.
Reading from text file until EOF repeats last line The following C++ code uses a ifstream object to read integers from a text file (which has one number per line) until it hits EOF. Why does it read the integer on the last line twice? How to fix this? Code: #include #include using namespace std; int main() { ifstream iFile("input.txt"); // input.txt has integers, one per line while (!iFile.eof()) { int x; iFile >> x; cerr << x << endl; } return 0; } input.txt: 10 20 30 Output: 10 20 30 30 Note: I've skipped all error checking code to keep the code snippet small. The above behaviour is seen on Windows (Visual C++), cygwin (gcc) and Linux (gcc).
TITLE: Reading from text file until EOF repeats last line QUESTION: The following C++ code uses a ifstream object to read integers from a text file (which has one number per line) until it hits EOF. Why does it read the integer on the last line twice? How to fix this? Code: #include #include using namespace std; int main() { ifstream iFile("input.txt"); // input.txt has integers, one per line while (!iFile.eof()) { int x; iFile >> x; cerr << x << endl; } return 0; } input.txt: 10 20 30 Output: 10 20 30 30 Note: I've skipped all error checking code to keep the code snippet small. The above behaviour is seen on Windows (Visual C++), cygwin (gcc) and Linux (gcc). ANSWER: Just follow closely the chain of events. Grab 10 Grab 20 Grab 30 Grab EOF Look at the second-to-last iteration. You grabbed 30, then carried on to check for EOF. You haven't reached EOF because the EOF mark hasn't been read yet ("binarically" speaking, its conceptual location is just after the 30 line). Therefore you carry on to the next iteration. x is still 30 from previous iteration. Now you read from the stream and you get EOF. x remains 30 and the ios::eofbit is raised. You output to stderr x (which is 30, just like in the previous iteration). Next you check for EOF in the loop condition, and this time you're out of the loop. Try this: while (true) { int x; iFile >> x; if( iFile.eof() ) break; cerr << x << endl; } By the way, there is another bug in your code. Did you ever try to run it on an empty file? The behaviour you get is for the exact same reason.
[ "c++", "iostream", "fstream" ]
132
135
376,118
7
0
2008-08-22T02:21:07.440000
2008-08-22T02:50:56.403000
21,651
24,919
Adobe AIR: Handling JSON objects from server
I have a script that retrieves objects from a remote server through an Ajax call. The server returns objects in JSON notation.­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­ However, in Adobe AIR, there is a restriction on using eval() for security reasons. So I'm able to get replies from the remote server, but can't turn them back into JavaScript objects. Is there any workaround for this issue? I would like to use JSON for my JavaScript objects, since it can be used almost immediately. Side-note: I do understand the security implications for forcing the issue, but I will be doing some rapid application development for a competition, so the program would only be a quick prototype, and not used for production purposes. Nevertheless, it would be great if there's a better alternative to what I'm trying to do now Update: Thanks to Theo and jsight for their answers; One important thing I learnt today is that I can actually make use of ActionScript libraries by using the tag extended by Adobe AIR. Check out Theo's link for more details!
You can find a JSON parser written in JavaScript here ( source code here ). You can also use the as3corelib JSON parser from JavaScript, there's a description of how to access ActionScript libraries from JavaScript here.
Adobe AIR: Handling JSON objects from server I have a script that retrieves objects from a remote server through an Ajax call. The server returns objects in JSON notation.­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­ However, in Adobe AIR, there is a restriction on using eval() for security reasons. So I'm able to get replies from the remote server, but can't turn them back into JavaScript objects. Is there any workaround for this issue? I would like to use JSON for my JavaScript objects, since it can be used almost immediately. Side-note: I do understand the security implications for forcing the issue, but I will be doing some rapid application development for a competition, so the program would only be a quick prototype, and not used for production purposes. Nevertheless, it would be great if there's a better alternative to what I'm trying to do now Update: Thanks to Theo and jsight for their answers; One important thing I learnt today is that I can actually make use of ActionScript libraries by using the tag extended by Adobe AIR. Check out Theo's link for more details!
TITLE: Adobe AIR: Handling JSON objects from server QUESTION: I have a script that retrieves objects from a remote server through an Ajax call. The server returns objects in JSON notation.­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­ However, in Adobe AIR, there is a restriction on using eval() for security reasons. So I'm able to get replies from the remote server, but can't turn them back into JavaScript objects. Is there any workaround for this issue? I would like to use JSON for my JavaScript objects, since it can be used almost immediately. Side-note: I do understand the security implications for forcing the issue, but I will be doing some rapid application development for a competition, so the program would only be a quick prototype, and not used for production purposes. Nevertheless, it would be great if there's a better alternative to what I'm trying to do now Update: Thanks to Theo and jsight for their answers; One important thing I learnt today is that I can actually make use of ActionScript libraries by using the tag extended by Adobe AIR. Check out Theo's link for more details! ANSWER: You can find a JSON parser written in JavaScript here ( source code here ). You can also use the as3corelib JSON parser from JavaScript, there's a description of how to access ActionScript libraries from JavaScript here.
[ "javascript", "ajax", "json", "air" ]
8
7
4,988
5
0
2008-08-22T02:26:26.117000
2008-08-24T08:11:29.673000
21,652
138,532
Do you write exceptions for specific issues or general exceptions?
I have some code that gives a user id to a utility that then send email to that user. emailUtil.sendEmail(userId, "foo"); public void sendEmail(String userId, String message) throws MailException { /*... logic that could throw a MailException */ } MailException could be thrown for a number of reasons, problems with the email address, problems with the mail template etc. My question is this: do you create a new Exception type for every one of these exceptions and then deal with them individually or do you create one MailException and then store something in the exception (something computer-readable, not the description text) that allows us to do different things based on what actually happened. Edit: As a clarification, the exceptions aren't for logs and what-not, this relates to how code reacts to them. To keep going with the mail example, let's say that when we send mail it could fail because you don't have an email address, or it could because you don't have a valid email address, or it could fail.. etc. My code would want to react differently to each of these issues (mostly by changing the message returned to the client, but actual logic as well). Would it be best to have an exception implementation for each one of these issues or one umbrella exception that had something internal to it (an enum say) that let the code distinguish what kind of issue it was.
I usually start with a general exception and subclass it as needed. I always can catch the general exception (and with it all subclassed exceptions) if needed, but also the specific. An example from the Java-API is IOException, that has subclasses like FileNotFoundException or EOFException (and much more). This way you get the advantages of both, you don't have throw-clauses like: throws SpecificException1, SpecificException2, SpecificException3... a general throws GeneralException is enough. But if you want to have a special reaction to special circumstances you can always catch the specific exception.
Do you write exceptions for specific issues or general exceptions? I have some code that gives a user id to a utility that then send email to that user. emailUtil.sendEmail(userId, "foo"); public void sendEmail(String userId, String message) throws MailException { /*... logic that could throw a MailException */ } MailException could be thrown for a number of reasons, problems with the email address, problems with the mail template etc. My question is this: do you create a new Exception type for every one of these exceptions and then deal with them individually or do you create one MailException and then store something in the exception (something computer-readable, not the description text) that allows us to do different things based on what actually happened. Edit: As a clarification, the exceptions aren't for logs and what-not, this relates to how code reacts to them. To keep going with the mail example, let's say that when we send mail it could fail because you don't have an email address, or it could because you don't have a valid email address, or it could fail.. etc. My code would want to react differently to each of these issues (mostly by changing the message returned to the client, but actual logic as well). Would it be best to have an exception implementation for each one of these issues or one umbrella exception that had something internal to it (an enum say) that let the code distinguish what kind of issue it was.
TITLE: Do you write exceptions for specific issues or general exceptions? QUESTION: I have some code that gives a user id to a utility that then send email to that user. emailUtil.sendEmail(userId, "foo"); public void sendEmail(String userId, String message) throws MailException { /*... logic that could throw a MailException */ } MailException could be thrown for a number of reasons, problems with the email address, problems with the mail template etc. My question is this: do you create a new Exception type for every one of these exceptions and then deal with them individually or do you create one MailException and then store something in the exception (something computer-readable, not the description text) that allows us to do different things based on what actually happened. Edit: As a clarification, the exceptions aren't for logs and what-not, this relates to how code reacts to them. To keep going with the mail example, let's say that when we send mail it could fail because you don't have an email address, or it could because you don't have a valid email address, or it could fail.. etc. My code would want to react differently to each of these issues (mostly by changing the message returned to the client, but actual logic as well). Would it be best to have an exception implementation for each one of these issues or one umbrella exception that had something internal to it (an enum say) that let the code distinguish what kind of issue it was. ANSWER: I usually start with a general exception and subclass it as needed. I always can catch the general exception (and with it all subclassed exceptions) if needed, but also the specific. An example from the Java-API is IOException, that has subclasses like FileNotFoundException or EOFException (and much more). This way you get the advantages of both, you don't have throw-clauses like: throws SpecificException1, SpecificException2, SpecificException3... a general throws GeneralException is enough. But if you want to have a special reaction to special circumstances you can always catch the specific exception.
[ "c#", "java", "exception" ]
10
8
1,378
11
0
2008-08-22T02:47:44.333000
2008-09-26T09:55:04.287000
21,669
21,702
Complexity of Regex substitution
I didn't get the answer to this anywhere. What is the runtime complexity of a Regex match and substitution? Edit: I work in python. But would like to know in general about most popular languages/tools (java, perl, sed).
From a purely theoretical stance: The implementation I am familiar with would be to build a Deterministic Finite Automaton to recognize the regex. This is done in O(2^m), m being the size of the regex, using a standard algorithm. Once this is built, running a string through it is linear in the length of the string - O(n), n being string length. A replacement on a match found in the string should be constant time. So overall, I suppose O(2^m + n).
Complexity of Regex substitution I didn't get the answer to this anywhere. What is the runtime complexity of a Regex match and substitution? Edit: I work in python. But would like to know in general about most popular languages/tools (java, perl, sed).
TITLE: Complexity of Regex substitution QUESTION: I didn't get the answer to this anywhere. What is the runtime complexity of a Regex match and substitution? Edit: I work in python. But would like to know in general about most popular languages/tools (java, perl, sed). ANSWER: From a purely theoretical stance: The implementation I am familiar with would be to build a Deterministic Finite Automaton to recognize the regex. This is done in O(2^m), m being the size of the regex, using a standard algorithm. Once this is built, running a string through it is linear in the length of the string - O(n), n being string length. A replacement on a match found in the string should be constant time. So overall, I suppose O(2^m + n).
[ "regex", "complexity-theory" ]
14
15
9,424
8
0
2008-08-22T03:02:34.550000
2008-08-22T03:15:13.690000
21,697
22,043
How Do You Communicate Service Layer Messages/Errors to Higher Layers Using MVP?
I'm currently writing an ASP.Net app from the UI down. I'm implementing an MVP architecture because I'm sick of Winforms and wanted something that had a better separation of concerns. So with MVP, the Presenter handles events raised by the View. Here's some code that I have in place to deal with the creation of users: public class CreateMemberPresenter { private ICreateMemberView view; private IMemberTasks tasks; public CreateMemberPresenter(ICreateMemberView view): this(view, new StubMemberTasks()) { } public CreateMemberPresenter(ICreateMemberView view, IMemberTasks tasks) { this.view = view; this.tasks = tasks; HookupEventHandlersTo(view); } private void HookupEventHandlersTo(ICreateMemberView view) { view.CreateMember += delegate { CreateMember(); }; } private void CreateMember() { if (!view.IsValid) return; try { int newUserId; tasks.CreateMember(view.NewMember, out newUserId); view.NewUserCode = newUserId; view.Notify(new NotificationDTO() { Type = NotificationType.Success }); } catch(Exception e) { this.LogA().Message(string.Format("Error Creating User: {0}", e.Message)); view.Notify(new NotificationDTO() { Type = NotificationType.Failure, Message = "There was an error creating a new member" }); } } } I have my main form validation done using the built in.Net Validation Controls, but now I need to verify that the data sufficiently satisfies the criteria for the Service Layer. Let's say the following Service Layer messages can show up: E-mail account already exists (failure) Refering user entered does not exist (failure) Password length exceeds datastore allowed length (failure) Member created successfully (success) Let's also say that more rules will be in the service layer that the UI cannot anticipate. Currently I'm having the service layer throw an exception if things didn't go as planned. Is that a sufficent strategy? Does this code smell to you guys? If I wrote a service layer like this would you be annoyed at having to write Presenters that use it in this way? Return codes seem too old school and a bool is just not informative enough. Edit not by OP: merging in follow-up comments that were posted as answers by the OP Cheekysoft, I like the concept of a ServiceLayerException. I already have a global exception module for the exceptions that I don't anticipate. Do you find making all these custom exceptions tedious? I was thinking that catching base Exception class was a bit smelly but wasn't exactly sure how progress from there. tgmdbm, I like the clever use of the lambda expression there! Thanks Cheekysoft for the follow-up. So I'm guessing that would be the strategy if you don't mind the user being displayed a separate page (I'm primarily a web developer) if the Exception is not handled. However, if I want to return the error message in the same view where the user submitted the data that caused the error, I would then have to catch the Exception in the Presenter? Here's what the CreateUserView looks like when the Presenter has handled the ServiceLayerException: For this kind of error, it's nice to report it to the same view. Anyways, I think we're going beyond the scope of my original question now. I'll play around with what you've posted and if I need further details I'll post a new question.
That sounds just right to me. Exceptions are preferable as they can be thrown up to the top of the service layer from anywhere inside the service layer, no matter how deeply nested inside the service method implementation it is. This keeps the service code clean as you know the calling presenter will always get notification of the problem. Don't catch Exception However, don't catch Exception in the presenter, I know its tempting because it keeps the code shorter, but you need to catch specific exceptions to avoid catching the system-level exceptions. Plan a Simple Exception Hierarchy If you are going to use exceptions in this way, you should design an exception hierarchy for your own exception classes. At a minumum create a ServiceLayerException class and throw one of these in your service methods when a problem occurs. Then if you need to throw an exception that should/could be handled differently by the presenter, you can throw a specific subclass of ServiceLayerException: say, AccountAlreadyExistsException. Your presenter then has the option of doing try { // call service etc. // handle success to view } catch (AccountAlreadyExistsException) { // set the message and some other unique data in the view } catch (ServiceLayerException) { // set the message in the view } // system exceptions, and unrecoverable exceptions are allowed to bubble // up the call stack so a general error can be shown to the user, rather // than showing the form again. Using inheritance in your own exception classes means you are not required to catch multipile exceptions in your presenter -- you can if there's a need to -- and you don't end up accidentally catching exceptions you can't handle. If your presenter is already at the top of the call stack, add a catch( Exception ) block to handle the system errors with a different view. I always try and think of my service layer as a seperate distributable library, and throw as specific an exception as makes sense. It is then up to the presenter/controller/remote-service implementation to decide if it needs to worry about the specific details or just to treat problems as a generic error.
How Do You Communicate Service Layer Messages/Errors to Higher Layers Using MVP? I'm currently writing an ASP.Net app from the UI down. I'm implementing an MVP architecture because I'm sick of Winforms and wanted something that had a better separation of concerns. So with MVP, the Presenter handles events raised by the View. Here's some code that I have in place to deal with the creation of users: public class CreateMemberPresenter { private ICreateMemberView view; private IMemberTasks tasks; public CreateMemberPresenter(ICreateMemberView view): this(view, new StubMemberTasks()) { } public CreateMemberPresenter(ICreateMemberView view, IMemberTasks tasks) { this.view = view; this.tasks = tasks; HookupEventHandlersTo(view); } private void HookupEventHandlersTo(ICreateMemberView view) { view.CreateMember += delegate { CreateMember(); }; } private void CreateMember() { if (!view.IsValid) return; try { int newUserId; tasks.CreateMember(view.NewMember, out newUserId); view.NewUserCode = newUserId; view.Notify(new NotificationDTO() { Type = NotificationType.Success }); } catch(Exception e) { this.LogA().Message(string.Format("Error Creating User: {0}", e.Message)); view.Notify(new NotificationDTO() { Type = NotificationType.Failure, Message = "There was an error creating a new member" }); } } } I have my main form validation done using the built in.Net Validation Controls, but now I need to verify that the data sufficiently satisfies the criteria for the Service Layer. Let's say the following Service Layer messages can show up: E-mail account already exists (failure) Refering user entered does not exist (failure) Password length exceeds datastore allowed length (failure) Member created successfully (success) Let's also say that more rules will be in the service layer that the UI cannot anticipate. Currently I'm having the service layer throw an exception if things didn't go as planned. Is that a sufficent strategy? Does this code smell to you guys? If I wrote a service layer like this would you be annoyed at having to write Presenters that use it in this way? Return codes seem too old school and a bool is just not informative enough. Edit not by OP: merging in follow-up comments that were posted as answers by the OP Cheekysoft, I like the concept of a ServiceLayerException. I already have a global exception module for the exceptions that I don't anticipate. Do you find making all these custom exceptions tedious? I was thinking that catching base Exception class was a bit smelly but wasn't exactly sure how progress from there. tgmdbm, I like the clever use of the lambda expression there! Thanks Cheekysoft for the follow-up. So I'm guessing that would be the strategy if you don't mind the user being displayed a separate page (I'm primarily a web developer) if the Exception is not handled. However, if I want to return the error message in the same view where the user submitted the data that caused the error, I would then have to catch the Exception in the Presenter? Here's what the CreateUserView looks like when the Presenter has handled the ServiceLayerException: For this kind of error, it's nice to report it to the same view. Anyways, I think we're going beyond the scope of my original question now. I'll play around with what you've posted and if I need further details I'll post a new question.
TITLE: How Do You Communicate Service Layer Messages/Errors to Higher Layers Using MVP? QUESTION: I'm currently writing an ASP.Net app from the UI down. I'm implementing an MVP architecture because I'm sick of Winforms and wanted something that had a better separation of concerns. So with MVP, the Presenter handles events raised by the View. Here's some code that I have in place to deal with the creation of users: public class CreateMemberPresenter { private ICreateMemberView view; private IMemberTasks tasks; public CreateMemberPresenter(ICreateMemberView view): this(view, new StubMemberTasks()) { } public CreateMemberPresenter(ICreateMemberView view, IMemberTasks tasks) { this.view = view; this.tasks = tasks; HookupEventHandlersTo(view); } private void HookupEventHandlersTo(ICreateMemberView view) { view.CreateMember += delegate { CreateMember(); }; } private void CreateMember() { if (!view.IsValid) return; try { int newUserId; tasks.CreateMember(view.NewMember, out newUserId); view.NewUserCode = newUserId; view.Notify(new NotificationDTO() { Type = NotificationType.Success }); } catch(Exception e) { this.LogA().Message(string.Format("Error Creating User: {0}", e.Message)); view.Notify(new NotificationDTO() { Type = NotificationType.Failure, Message = "There was an error creating a new member" }); } } } I have my main form validation done using the built in.Net Validation Controls, but now I need to verify that the data sufficiently satisfies the criteria for the Service Layer. Let's say the following Service Layer messages can show up: E-mail account already exists (failure) Refering user entered does not exist (failure) Password length exceeds datastore allowed length (failure) Member created successfully (success) Let's also say that more rules will be in the service layer that the UI cannot anticipate. Currently I'm having the service layer throw an exception if things didn't go as planned. Is that a sufficent strategy? Does this code smell to you guys? If I wrote a service layer like this would you be annoyed at having to write Presenters that use it in this way? Return codes seem too old school and a bool is just not informative enough. Edit not by OP: merging in follow-up comments that were posted as answers by the OP Cheekysoft, I like the concept of a ServiceLayerException. I already have a global exception module for the exceptions that I don't anticipate. Do you find making all these custom exceptions tedious? I was thinking that catching base Exception class was a bit smelly but wasn't exactly sure how progress from there. tgmdbm, I like the clever use of the lambda expression there! Thanks Cheekysoft for the follow-up. So I'm guessing that would be the strategy if you don't mind the user being displayed a separate page (I'm primarily a web developer) if the Exception is not handled. However, if I want to return the error message in the same view where the user submitted the data that caused the error, I would then have to catch the Exception in the Presenter? Here's what the CreateUserView looks like when the Presenter has handled the ServiceLayerException: For this kind of error, it's nice to report it to the same view. Anyways, I think we're going beyond the scope of my original question now. I'll play around with what you've posted and if I need further details I'll post a new question. ANSWER: That sounds just right to me. Exceptions are preferable as they can be thrown up to the top of the service layer from anywhere inside the service layer, no matter how deeply nested inside the service method implementation it is. This keeps the service code clean as you know the calling presenter will always get notification of the problem. Don't catch Exception However, don't catch Exception in the presenter, I know its tempting because it keeps the code shorter, but you need to catch specific exceptions to avoid catching the system-level exceptions. Plan a Simple Exception Hierarchy If you are going to use exceptions in this way, you should design an exception hierarchy for your own exception classes. At a minumum create a ServiceLayerException class and throw one of these in your service methods when a problem occurs. Then if you need to throw an exception that should/could be handled differently by the presenter, you can throw a specific subclass of ServiceLayerException: say, AccountAlreadyExistsException. Your presenter then has the option of doing try { // call service etc. // handle success to view } catch (AccountAlreadyExistsException) { // set the message and some other unique data in the view } catch (ServiceLayerException) { // set the message in the view } // system exceptions, and unrecoverable exceptions are allowed to bubble // up the call stack so a general error can be shown to the user, rather // than showing the form again. Using inheritance in your own exception classes means you are not required to catch multipile exceptions in your presenter -- you can if there's a need to -- and you don't end up accidentally catching exceptions you can't handle. If your presenter is already at the top of the call stack, add a catch( Exception ) block to handle the system errors with a different view. I always try and think of my service layer as a seperate distributable library, and throw as specific an exception as makes sense. It is then up to the presenter/controller/remote-service implementation to decide if it needs to worry about the specific details or just to treat problems as a generic error.
[ "c#", "asp.net", "exception", "mvp", "n-tier-architecture" ]
18
16
6,021
3
0
2008-08-22T03:12:59.517000
2008-08-22T10:33:43.903000
21,715
21,786
List<BusinessObject> or BusinessObjectCollection?
Prior to C# generics, everyone would code collections for their business objects by creating a collection base that implemented IEnumerable IE: public class CollectionBase: IEnumerable and then would derive their Business Object collections from that. public class BusinessObjectCollection: CollectionBase Now with the generic list class, does anyone just use that instead? I've found that I use a compromise of the two techniques: public class BusinessObjectCollection: List I do this because I like to have strongly typed names instead of just passing Lists around. What is your approach?
I am generally in the camp of just using a List directly, unless for some reason I need to encapsulate the data structure and provide a limited subset of its functionality. This is mainly because if I don't have a specific need for encapsulation then doing it is just a waste of time. However, with the aggregate initializes feature in C# 3.0, there are some new situations where I would advocate using customized collection classes. Basically, C# 3.0 allows any class that implements IEnumerable and has an Add method to use the new aggregate initializer syntax. For example, because Dictionary defines a method Add(K key, V value) it is possible to initialize a dictionary using this syntax: var d = new Dictionary { {"hello", 0}, {"the answer to life the universe and everything is:", 42} }; The great thing about the feature is that it works for add methods with any number of arguments. For example, given this collection: class c1: IEnumerable { void Add(int x1, int x2, int x3) { //... } //... } it would be possible to initialize it like so: var x = new c1 { {1,2,3}, {4,5,6} } This can be really useful if you need to create static tables of complex objects. For example, if you were just using List and you wanted to create a static list of customer objects you would have to create it like so: var x = new List { new Customer("Scott Wisniewski", "555-555-5555", "Seattle", "WA"), new Customer("John Doe", "555-555-1234", "Los Angeles", "CA"), new Customer("Michael Scott", "555-555-8769", "Scranton PA"), new Customer("Ali G", "", "Staines", "UK") } However, if you use a customized collection, like this one: class CustomerList: List { public void Add(string name, string phoneNumber, string city, string stateOrCountry) { Add(new Customer(name, phoneNumber, city, stateOrCounter)); } } You could then initialize the collection using this syntax: var customers = new CustomerList { {"Scott Wisniewski", "555-555-5555", "Seattle", "WA"}, {"John Doe", "555-555-1234", "Los Angeles", "CA"}, {"Michael Scott", "555-555-8769", "Scranton PA"}, {"Ali G", "", "Staines", "UK"} } This has the advantage of being both easier to type and easier to read because their is no need to retype the element type name for each element. The advantage can be particularly strong if the element type is long or complex. That being said, this is only useful if you need static collections of data defined in your app. Some types of apps, like compilers, use them all the time. Others, like typical database apps don't because they load all their data from a database. My advice would be that if you either need to define a static collection of objects, or need to encapsulate away the collection interface, then create a custom collection class. Otherwise I would just use List directly.
List<BusinessObject> or BusinessObjectCollection? Prior to C# generics, everyone would code collections for their business objects by creating a collection base that implemented IEnumerable IE: public class CollectionBase: IEnumerable and then would derive their Business Object collections from that. public class BusinessObjectCollection: CollectionBase Now with the generic list class, does anyone just use that instead? I've found that I use a compromise of the two techniques: public class BusinessObjectCollection: List I do this because I like to have strongly typed names instead of just passing Lists around. What is your approach?
TITLE: List<BusinessObject> or BusinessObjectCollection? QUESTION: Prior to C# generics, everyone would code collections for their business objects by creating a collection base that implemented IEnumerable IE: public class CollectionBase: IEnumerable and then would derive their Business Object collections from that. public class BusinessObjectCollection: CollectionBase Now with the generic list class, does anyone just use that instead? I've found that I use a compromise of the two techniques: public class BusinessObjectCollection: List I do this because I like to have strongly typed names instead of just passing Lists around. What is your approach? ANSWER: I am generally in the camp of just using a List directly, unless for some reason I need to encapsulate the data structure and provide a limited subset of its functionality. This is mainly because if I don't have a specific need for encapsulation then doing it is just a waste of time. However, with the aggregate initializes feature in C# 3.0, there are some new situations where I would advocate using customized collection classes. Basically, C# 3.0 allows any class that implements IEnumerable and has an Add method to use the new aggregate initializer syntax. For example, because Dictionary defines a method Add(K key, V value) it is possible to initialize a dictionary using this syntax: var d = new Dictionary { {"hello", 0}, {"the answer to life the universe and everything is:", 42} }; The great thing about the feature is that it works for add methods with any number of arguments. For example, given this collection: class c1: IEnumerable { void Add(int x1, int x2, int x3) { //... } //... } it would be possible to initialize it like so: var x = new c1 { {1,2,3}, {4,5,6} } This can be really useful if you need to create static tables of complex objects. For example, if you were just using List and you wanted to create a static list of customer objects you would have to create it like so: var x = new List { new Customer("Scott Wisniewski", "555-555-5555", "Seattle", "WA"), new Customer("John Doe", "555-555-1234", "Los Angeles", "CA"), new Customer("Michael Scott", "555-555-8769", "Scranton PA"), new Customer("Ali G", "", "Staines", "UK") } However, if you use a customized collection, like this one: class CustomerList: List { public void Add(string name, string phoneNumber, string city, string stateOrCountry) { Add(new Customer(name, phoneNumber, city, stateOrCounter)); } } You could then initialize the collection using this syntax: var customers = new CustomerList { {"Scott Wisniewski", "555-555-5555", "Seattle", "WA"}, {"John Doe", "555-555-1234", "Los Angeles", "CA"}, {"Michael Scott", "555-555-8769", "Scranton PA"}, {"Ali G", "", "Staines", "UK"} } This has the advantage of being both easier to type and easier to read because their is no need to retype the element type name for each element. The advantage can be particularly strong if the element type is long or complex. That being said, this is only useful if you need static collections of data defined in your app. Some types of apps, like compilers, use them all the time. Others, like typical database apps don't because they load all their data from a database. My advice would be that if you either need to define a static collection of objects, or need to encapsulate away the collection interface, then create a custom collection class. Otherwise I would just use List directly.
[ "c#", ".net", "generics", "collections", "class-design" ]
46
50
4,891
18
0
2008-08-22T03:25:09.487000
2008-08-22T04:46:28.433000
21,725
30,699
Favorite (G)Vim plugins/scripts?
What are your favorite (G)Vim plugins/scripts?
Nerdtree The NERD tree allows you to explore your filesystem and to open files and directories. It presents the filesystem to you in the form of a tree which you manipulate with the keyboard and/or mouse. It also allows you to perform simple filesystem operations. The tree can be toggled easily with:NERDTreeToggle which can be mapped to a more suitable key. The keyboard shortcuts in the NERD tree are also easy and intuitive. Edit: Added synopsis
Favorite (G)Vim plugins/scripts? What are your favorite (G)Vim plugins/scripts?
TITLE: Favorite (G)Vim plugins/scripts? QUESTION: What are your favorite (G)Vim plugins/scripts? ANSWER: Nerdtree The NERD tree allows you to explore your filesystem and to open files and directories. It presents the filesystem to you in the form of a tree which you manipulate with the keyboard and/or mouse. It also allows you to perform simple filesystem operations. The tree can be toggled easily with:NERDTreeToggle which can be mapped to a more suitable key. The keyboard shortcuts in the NERD tree are also easy and intuitive. Edit: Added synopsis
[ "vim", "editor" ]
165
97
56,653
38
0
2008-08-22T03:31:48.940000
2008-08-27T17:40:51.730000
21,738
201,513
Problems running Swing application with IDEA 8M1
Is anyone else having trouble running Swing applications from IntelliJ IDEA 8 Milestone 1? Even the simplest application of showing an empty JFrame seems to crash the JVM. I don't get a stack trace or anything, it looks like the JVM itself crashes and Windows shows me a pop-up that says the usual "This process is no longer responding" message. Console applications work fine, and my Swing code works fine when launching from Netbeans or from the command line. I'm running Windows Vista x64 with the JDK 1.6 Update 10 beta, which may be a configuration the Jetbrains guys haven't run into yet.
I have actually experienced problems from using the JDK 6u10 beta myself and had to downgrade to JDK 6u7 for the time being. This solved some of my problems with among other things swing. Also, i have been running IJ8M1 since the 'release' and I am very satisfied with it, especially if you regard the "beta" tag. It feels snappier and also supports multiple cores which makes my development machine rejoice.;p Anyway, i use WinXP32 and IJ8M1 with JDK 6u7 and that is afaik very stable indeed.
Problems running Swing application with IDEA 8M1 Is anyone else having trouble running Swing applications from IntelliJ IDEA 8 Milestone 1? Even the simplest application of showing an empty JFrame seems to crash the JVM. I don't get a stack trace or anything, it looks like the JVM itself crashes and Windows shows me a pop-up that says the usual "This process is no longer responding" message. Console applications work fine, and my Swing code works fine when launching from Netbeans or from the command line. I'm running Windows Vista x64 with the JDK 1.6 Update 10 beta, which may be a configuration the Jetbrains guys haven't run into yet.
TITLE: Problems running Swing application with IDEA 8M1 QUESTION: Is anyone else having trouble running Swing applications from IntelliJ IDEA 8 Milestone 1? Even the simplest application of showing an empty JFrame seems to crash the JVM. I don't get a stack trace or anything, it looks like the JVM itself crashes and Windows shows me a pop-up that says the usual "This process is no longer responding" message. Console applications work fine, and my Swing code works fine when launching from Netbeans or from the command line. I'm running Windows Vista x64 with the JDK 1.6 Update 10 beta, which may be a configuration the Jetbrains guys haven't run into yet. ANSWER: I have actually experienced problems from using the JDK 6u10 beta myself and had to downgrade to JDK 6u7 for the time being. This solved some of my problems with among other things swing. Also, i have been running IJ8M1 since the 'release' and I am very satisfied with it, especially if you regard the "beta" tag. It feels snappier and also supports multiple cores which makes my development machine rejoice.;p Anyway, i use WinXP32 and IJ8M1 with JDK 6u7 and that is afaik very stable indeed.
[ "java", "swing", "ide", "jvm", "intellij-idea" ]
1
1
394
3
0
2008-08-22T03:43:41.690000
2008-10-14T14:57:36.673000
21,749
21,978
Multiple form Delphi applications and dialogs
I have a Delphi 7 application that has two views of a document (e.g. a WYSIWYG HTML edit might have a WYSIWYG view and a source view - not my real application). They can be opened in separate windows, or docked into tabs in the main window. If I open a modal dialog from one of the separate forms, the main form is brought to the front, and is shown as the selected window in the windows taskbar. Say the main form is the WYSIWYG view, and the source view is poped out. You go to a particular point in the source view and insert an image tag. A dialog appears to allow you to select and enter the properties you want for the image. If the WYSIWYG view and the source view overlap, the WYSIWYG view will be brought to the front and the source view is hidden. Once the dialog is dismissed, the source view comes back into sight. I've tried setting the owner and the ParentWindow properties to the form it is related to: dialog:= TDialogForm.Create( parentForm ); dialog.ParentWindow:= parentForm.Handle; How can I fix this problem? What else should I be trying? Given that people seem to be stumbling on my example, perhaps I can try with a better example: a text editor that allows you to have more than one file open at the same time. The files you have open are either in tabs (like in the Delphi IDE) or in its own window. Suppose the user brings up the spell check dialog or the find dialog. What happens, is that if the file is being editing in its own window, that window is sent to below the main form in the z-order when the modal dialog is shown; once the dialog is closed, it is returned to its original z-order. Note: If you are using Delphi 7 and looking for a solution to this problem, see my answer lower down on the page to see what I ended up doing.
I'd use this code... (Basically what Lars said) dialog:= TDialogForm.Create( parentForm ); dialog.PopupParent:= parentForm; dialog.PopupMode:= pmExplicit; dialog.ShowModal();
Multiple form Delphi applications and dialogs I have a Delphi 7 application that has two views of a document (e.g. a WYSIWYG HTML edit might have a WYSIWYG view and a source view - not my real application). They can be opened in separate windows, or docked into tabs in the main window. If I open a modal dialog from one of the separate forms, the main form is brought to the front, and is shown as the selected window in the windows taskbar. Say the main form is the WYSIWYG view, and the source view is poped out. You go to a particular point in the source view and insert an image tag. A dialog appears to allow you to select and enter the properties you want for the image. If the WYSIWYG view and the source view overlap, the WYSIWYG view will be brought to the front and the source view is hidden. Once the dialog is dismissed, the source view comes back into sight. I've tried setting the owner and the ParentWindow properties to the form it is related to: dialog:= TDialogForm.Create( parentForm ); dialog.ParentWindow:= parentForm.Handle; How can I fix this problem? What else should I be trying? Given that people seem to be stumbling on my example, perhaps I can try with a better example: a text editor that allows you to have more than one file open at the same time. The files you have open are either in tabs (like in the Delphi IDE) or in its own window. Suppose the user brings up the spell check dialog or the find dialog. What happens, is that if the file is being editing in its own window, that window is sent to below the main form in the z-order when the modal dialog is shown; once the dialog is closed, it is returned to its original z-order. Note: If you are using Delphi 7 and looking for a solution to this problem, see my answer lower down on the page to see what I ended up doing.
TITLE: Multiple form Delphi applications and dialogs QUESTION: I have a Delphi 7 application that has two views of a document (e.g. a WYSIWYG HTML edit might have a WYSIWYG view and a source view - not my real application). They can be opened in separate windows, or docked into tabs in the main window. If I open a modal dialog from one of the separate forms, the main form is brought to the front, and is shown as the selected window in the windows taskbar. Say the main form is the WYSIWYG view, and the source view is poped out. You go to a particular point in the source view and insert an image tag. A dialog appears to allow you to select and enter the properties you want for the image. If the WYSIWYG view and the source view overlap, the WYSIWYG view will be brought to the front and the source view is hidden. Once the dialog is dismissed, the source view comes back into sight. I've tried setting the owner and the ParentWindow properties to the form it is related to: dialog:= TDialogForm.Create( parentForm ); dialog.ParentWindow:= parentForm.Handle; How can I fix this problem? What else should I be trying? Given that people seem to be stumbling on my example, perhaps I can try with a better example: a text editor that allows you to have more than one file open at the same time. The files you have open are either in tabs (like in the Delphi IDE) or in its own window. Suppose the user brings up the spell check dialog or the find dialog. What happens, is that if the file is being editing in its own window, that window is sent to below the main form in the z-order when the modal dialog is shown; once the dialog is closed, it is returned to its original z-order. Note: If you are using Delphi 7 and looking for a solution to this problem, see my answer lower down on the page to see what I ended up doing. ANSWER: I'd use this code... (Basically what Lars said) dialog:= TDialogForm.Create( parentForm ); dialog.PopupParent:= parentForm; dialog.PopupMode:= pmExplicit; dialog.ShowModal();
[ "delphi", "delphi-7" ]
4
5
7,644
5
0
2008-08-22T03:51:42.980000
2008-08-22T09:28:14.480000
21,753
22,073
How to use BITS to download from a UNC path?
What is the best way to distribute files to users in remote offices, using BITS with a UNC path or BITS with HTTP? I have a VB.NET project which currently downloads from a HTTP path, but there is added complexity involved (e.g. having a web server). Or is there a better way to do this? Low bandwith usage is more important than speed of synching.
Maybe consider not using BITS at all and use the old favourite Robocopy. Robocopy is a standalone command-line executable which is part of the Windows Server 2003 ResKit tools and now standard on Vista/2008. Robocopy has the /IPG:ms (Inter-Packet Gap) switch to "dribble" the download, which is designed specifically to not saturate slow links.
How to use BITS to download from a UNC path? What is the best way to distribute files to users in remote offices, using BITS with a UNC path or BITS with HTTP? I have a VB.NET project which currently downloads from a HTTP path, but there is added complexity involved (e.g. having a web server). Or is there a better way to do this? Low bandwith usage is more important than speed of synching.
TITLE: How to use BITS to download from a UNC path? QUESTION: What is the best way to distribute files to users in remote offices, using BITS with a UNC path or BITS with HTTP? I have a VB.NET project which currently downloads from a HTTP path, but there is added complexity involved (e.g. having a web server). Or is there a better way to do this? Low bandwith usage is more important than speed of synching. ANSWER: Maybe consider not using BITS at all and use the old favourite Robocopy. Robocopy is a standalone command-line executable which is part of the Windows Server 2003 ResKit tools and now standard on Vista/2008. Robocopy has the /IPG:ms (Inter-Packet Gap) switch to "dribble" the download, which is designed specifically to not saturate slow links.
[ "vb.net", "bit" ]
0
1
707
1
0
2008-08-22T03:58:10.530000
2008-08-22T11:11:08.743000
21,766
21,818
Open source rules engine with decent interface for writing rules
I'm trying to locate an open source business rules engine that has a decent interface for building the rules. OR at least one that works well on the.Net platform and has been updated sometime in the past 12 months. Thanks,
NxBRE is one option. http://sourceforge.net/projects/nxbre/#item3rd-5
Open source rules engine with decent interface for writing rules I'm trying to locate an open source business rules engine that has a decent interface for building the rules. OR at least one that works well on the.Net platform and has been updated sometime in the past 12 months. Thanks,
TITLE: Open source rules engine with decent interface for writing rules QUESTION: I'm trying to locate an open source business rules engine that has a decent interface for building the rules. OR at least one that works well on the.Net platform and has been updated sometime in the past 12 months. Thanks, ANSWER: NxBRE is one option. http://sourceforge.net/projects/nxbre/#item3rd-5
[ ".net", "rule-engine" ]
12
8
8,563
5
0
2008-08-22T04:20:07.280000
2008-08-22T05:18:12.397000
21,817
22,497
Why can't I declare static methods in an interface?
The topic says the most of it - what is the reason for the fact that static methods can't be declared in an interface? public interface ITest { public static String test(); } The code above gives me the following error (in Eclipse, at least): "Illegal modifier for the interface method ITest.test(); only public & abstract are permitted".
There are a few issues at play here. The first is the issue of declaring a static method without defining it. This is the difference between public interface Foo { public static int bar(); } and public interface Foo { public static int bar() {... } } The first is impossible for the reasons that Espo mentions: you don't know which implementing class is the correct definition. Java could allow the latter; and in fact, starting in Java 8, it does!
Why can't I declare static methods in an interface? The topic says the most of it - what is the reason for the fact that static methods can't be declared in an interface? public interface ITest { public static String test(); } The code above gives me the following error (in Eclipse, at least): "Illegal modifier for the interface method ITest.test(); only public & abstract are permitted".
TITLE: Why can't I declare static methods in an interface? QUESTION: The topic says the most of it - what is the reason for the fact that static methods can't be declared in an interface? public interface ITest { public static String test(); } The code above gives me the following error (in Eclipse, at least): "Illegal modifier for the interface method ITest.test(); only public & abstract are permitted". ANSWER: There are a few issues at play here. The first is the issue of declaring a static method without defining it. This is the difference between public interface Foo { public static int bar(); } and public interface Foo { public static int bar() {... } } The first is impossible for the reasons that Espo mentions: you don't know which implementing class is the correct definition. Java could allow the latter; and in fact, starting in Java 8, it does!
[ "java", "interface", "methods", "static" ]
154
86
107,804
14
0
2008-08-22T05:16:43.837000
2008-08-22T14:29:02.467000
21,830
26,398
PostgreSQL: GIN or GiST indexes?
From what information I could find, they both solve the same problems - more esoteric operations like array containment and intersection (&&, @>, <@, etc). However I would be interested in advice about when to use one or the other (or neither possibly). The PostgreSQL documentation has some information about this: GIN index lookups are about three times faster than GiST GIN indexes take about three times longer to build than GiST GIN indexes are about ten times slower to update than GiST GIN indexes are two-to-three times larger than GiST However I would be particularly interested to know if there is a performance impact when the memory to index size ration starts getting small (ie. the index size becomes much bigger than the available memory)? I've been told on the #postgresql IRC channel that GIN needs to keep all the index in memory, otherwise it won't be effective, because, unlike B-Tree, it doesn't know which part to read in from disk for a particular query? The question would be: is this true (because I've also been told the opposite of this)? Does GiST have the same restrictions? Are there other restrictions I should be aware of while using one of these indexing algorithms?
First of all, do you need to use them for text search indexing? GIN and GiST are index specialized for some data types. If you need to index simple char or integer values then the normal B-Tree index is the best. Anyway, PostgreSQL documentation has a chapter on GIST and one on GIN, where you can find more info. And, last but not least, the best way to find which is best is to generate sample data (as much as you need to be a real scenario) and then create a GIST index, measuring how much time is needed to create the index, insert a new value, execute a sample query. Then drop the index and do the same with a GIN index. Compare the values and you will have the answer you need, based on your data.
PostgreSQL: GIN or GiST indexes? From what information I could find, they both solve the same problems - more esoteric operations like array containment and intersection (&&, @>, <@, etc). However I would be interested in advice about when to use one or the other (or neither possibly). The PostgreSQL documentation has some information about this: GIN index lookups are about three times faster than GiST GIN indexes take about three times longer to build than GiST GIN indexes are about ten times slower to update than GiST GIN indexes are two-to-three times larger than GiST However I would be particularly interested to know if there is a performance impact when the memory to index size ration starts getting small (ie. the index size becomes much bigger than the available memory)? I've been told on the #postgresql IRC channel that GIN needs to keep all the index in memory, otherwise it won't be effective, because, unlike B-Tree, it doesn't know which part to read in from disk for a particular query? The question would be: is this true (because I've also been told the opposite of this)? Does GiST have the same restrictions? Are there other restrictions I should be aware of while using one of these indexing algorithms?
TITLE: PostgreSQL: GIN or GiST indexes? QUESTION: From what information I could find, they both solve the same problems - more esoteric operations like array containment and intersection (&&, @>, <@, etc). However I would be interested in advice about when to use one or the other (or neither possibly). The PostgreSQL documentation has some information about this: GIN index lookups are about three times faster than GiST GIN indexes take about three times longer to build than GiST GIN indexes are about ten times slower to update than GiST GIN indexes are two-to-three times larger than GiST However I would be particularly interested to know if there is a performance impact when the memory to index size ration starts getting small (ie. the index size becomes much bigger than the available memory)? I've been told on the #postgresql IRC channel that GIN needs to keep all the index in memory, otherwise it won't be effective, because, unlike B-Tree, it doesn't know which part to read in from disk for a particular query? The question would be: is this true (because I've also been told the opposite of this)? Does GiST have the same restrictions? Are there other restrictions I should be aware of while using one of these indexing algorithms? ANSWER: First of all, do you need to use them for text search indexing? GIN and GiST are index specialized for some data types. If you need to index simple char or integer values then the normal B-Tree index is the best. Anyway, PostgreSQL documentation has a chapter on GIST and one on GIN, where you can find more info. And, last but not least, the best way to find which is best is to generate sample data (as much as you need to be a real scenario) and then create a GIST index, measuring how much time is needed to create the index, insert a new value, execute a sample query. Then drop the index and do the same with a GIN index. Compare the values and you will have the answer you need, based on your data.
[ "postgresql", "indexing", "gwt-gin", "gist-index" ]
39
18
20,002
1
0
2008-08-22T05:22:39.610000
2008-08-25T17:00:24.947000
21,848
21,932
Switch branch names in git
There may be more than one way to ask this question, so here's a desciption of the problem. I was working on master and committed some stuff and then decided I wanted to put that work on hold. I backed up a few commits and then branched from before I started my crap work. Practically this works fine, I just now have a different branch as my main development branch. I'm wondering how I could change things around so I'm working on master again but it doesn't have my junk work and said work is on a different branch. Some ways this could be asked/solved: How do I rename my master branch to something else and then rename something else to master? How do I back up master and then cause all commits I've backed up past to be on a different branch? Thanks for all the (quick) answers! They're all good.
In addition to the other comments, you may find the -m (move) switch to git-branch helpful. You could rename your old master to something else, then rename your new branch to master: git branch -m master crap_work git branch -m previous_master master
Switch branch names in git There may be more than one way to ask this question, so here's a desciption of the problem. I was working on master and committed some stuff and then decided I wanted to put that work on hold. I backed up a few commits and then branched from before I started my crap work. Practically this works fine, I just now have a different branch as my main development branch. I'm wondering how I could change things around so I'm working on master again but it doesn't have my junk work and said work is on a different branch. Some ways this could be asked/solved: How do I rename my master branch to something else and then rename something else to master? How do I back up master and then cause all commits I've backed up past to be on a different branch? Thanks for all the (quick) answers! They're all good.
TITLE: Switch branch names in git QUESTION: There may be more than one way to ask this question, so here's a desciption of the problem. I was working on master and committed some stuff and then decided I wanted to put that work on hold. I backed up a few commits and then branched from before I started my crap work. Practically this works fine, I just now have a different branch as my main development branch. I'm wondering how I could change things around so I'm working on master again but it doesn't have my junk work and said work is on a different branch. Some ways this could be asked/solved: How do I rename my master branch to something else and then rename something else to master? How do I back up master and then cause all commits I've backed up past to be on a different branch? Thanks for all the (quick) answers! They're all good. ANSWER: In addition to the other comments, you may find the -m (move) switch to git-branch helpful. You could rename your old master to something else, then rename your new branch to master: git branch -m master crap_work git branch -m previous_master master
[ "git", "branch" ]
108
148
48,458
5
0
2008-08-22T05:39:54.843000
2008-08-22T07:33:28.983000
21,870
984,076
System.Web.Caching vs. Enterprise Library Caching Block
For a.NET component that will be used in both web applications and rich client applications, there seem to be two obvious options for caching: System.Web.Caching or the Ent. Lib. Caching Block. What do you use? Why? System.Web.Caching Is this safe to use outside of web apps? I've seen mixed information, but I think the answer is maybe-kind-of-not-really. a KB article warning against 1.0 and 1.1 non web app use The 2.0 page has a comment that indicates it's OK: http://msdn.microsoft.com/en-us/library/system.web.caching.cache(VS.80).aspx Scott Hanselman is creeped out by the notion The 3.5 page includes a warning against such use Rob Howard encouraged use outside of web apps I don't expect to use one of its highlights, SqlCacheDependency, but the addition of CacheItemUpdateCallback in.NET 3.5 seems like a Really Good Thing. Enterprise Library Caching Application Block other blocks are already in use so the dependency already exists cache persistence isn't necessary; regenerating the cache on restart is OK Some cache items should always be available, but be refreshed periodically. For these items, getting a callback after an item has been removed is not very convenient. It looks like a client will have to just sleep and poll until the cache item is repopulated. Memcached for Win32 +.NET client What are the pros and cons when you don't need a distributed cache?
These are the items that I consider for the topic of Caching: MemCached Win32 Velocity.net Cache Enterprise Library Caching Application Block MemCached Win32: Up until recently I have used MemCached Win32. This is a akin to a web farm (many servers serving the same content for high availability) but it is a cache farm. This means that you can install it locally on your web server initially if you don't have the resources to go bigger. Then as you go down the road you can scale horizontally (more servers) or vertically (more hardware). This is a product that was ported from the original MemCached to work on Windows. This product has been used extensively in very high traffic sites. http://lineofthought.com/tools/memcached Velocity: This is Microsofts answer to products such as MemCached. MemCached has been out for quite some time, Velocity is in CTP mode. I must say that from what I have read so far this product will certainly turn my head once it is out. But I can't bring myself to run big production projects on a CTP product with zero track record. I have started playing with it though as once it gains momentum MemCached won't even compare for those locked in the windows world! http://blogs.msdn.com/velocity/.NET Cache: There is no reason to discount the standard.NET Cache. It is built in and ready to use for free and with no (major) set up required. It offers flexibility by way of offering mechanisms for storing items in local memory, a SINGLE state server, or a centralized database. Where Velocity steps in is when you need more than a single state server (cache in memory) and don't want to use a slow database for holding your cache. Enterprise Application Block: I stay away from all of the Enterprise Application Blocks. They are heavy frameworks that give more than I generally require! As long as you remember to wrap everything that touches code that is not your own and follow simple rules for coding, stick to any of the other methods over this one! (just my opinion of course - MySpace leverages as much as they can out of Enterprise Application Blocks!) You don't have to choose up front! I generally create a cache wrapper that I communicate with in my code for methods such as Get, Set, Exists, Remove, ListKeys, etc. This then points to an underlying level of cache abstraction that can point to MemCached, Velocity, or.NET cache. I use StructureMap (or choose another IoC container) to inject which form of cache I want to use for a given environment. In my local dev box I might use.NET cache in the session. In production I generally use MemCached Win 32. But regardless of how it is set up you can easily swap things around to try each system out to see what works best for you. You just need to make sure that you application knows as little as possible about how things are cached! Once this layer of abstraction is in place you can then do things such as run a compression algorithm (gzip) for all the data that is going in and out of cache which would allow you to store 10 times the amount of data in cache. - transparently. I cover.NET Cache, MemCached Win32, StructureMap, and the appropriate abstractions in my book if you are interested! ASP.NET 3.5 Social Networking ( http://www.amazon.com/ASP-NET-3-5-Social-Networking-Enterprise-ready/dp/1847194788/ref=sr_1_1?ie=UTF8&s=books&qid=1225408005&sr=8-1 ) Andrew Siemer www.andrewsiemer.com blog.andrewsiemer.com www.socialnetworkingin.net Update Changed the link that lists sites using memcached. Thank you David for noticing that it was broken!
System.Web.Caching vs. Enterprise Library Caching Block For a.NET component that will be used in both web applications and rich client applications, there seem to be two obvious options for caching: System.Web.Caching or the Ent. Lib. Caching Block. What do you use? Why? System.Web.Caching Is this safe to use outside of web apps? I've seen mixed information, but I think the answer is maybe-kind-of-not-really. a KB article warning against 1.0 and 1.1 non web app use The 2.0 page has a comment that indicates it's OK: http://msdn.microsoft.com/en-us/library/system.web.caching.cache(VS.80).aspx Scott Hanselman is creeped out by the notion The 3.5 page includes a warning against such use Rob Howard encouraged use outside of web apps I don't expect to use one of its highlights, SqlCacheDependency, but the addition of CacheItemUpdateCallback in.NET 3.5 seems like a Really Good Thing. Enterprise Library Caching Application Block other blocks are already in use so the dependency already exists cache persistence isn't necessary; regenerating the cache on restart is OK Some cache items should always be available, but be refreshed periodically. For these items, getting a callback after an item has been removed is not very convenient. It looks like a client will have to just sleep and poll until the cache item is repopulated. Memcached for Win32 +.NET client What are the pros and cons when you don't need a distributed cache?
TITLE: System.Web.Caching vs. Enterprise Library Caching Block QUESTION: For a.NET component that will be used in both web applications and rich client applications, there seem to be two obvious options for caching: System.Web.Caching or the Ent. Lib. Caching Block. What do you use? Why? System.Web.Caching Is this safe to use outside of web apps? I've seen mixed information, but I think the answer is maybe-kind-of-not-really. a KB article warning against 1.0 and 1.1 non web app use The 2.0 page has a comment that indicates it's OK: http://msdn.microsoft.com/en-us/library/system.web.caching.cache(VS.80).aspx Scott Hanselman is creeped out by the notion The 3.5 page includes a warning against such use Rob Howard encouraged use outside of web apps I don't expect to use one of its highlights, SqlCacheDependency, but the addition of CacheItemUpdateCallback in.NET 3.5 seems like a Really Good Thing. Enterprise Library Caching Application Block other blocks are already in use so the dependency already exists cache persistence isn't necessary; regenerating the cache on restart is OK Some cache items should always be available, but be refreshed periodically. For these items, getting a callback after an item has been removed is not very convenient. It looks like a client will have to just sleep and poll until the cache item is repopulated. Memcached for Win32 +.NET client What are the pros and cons when you don't need a distributed cache? ANSWER: These are the items that I consider for the topic of Caching: MemCached Win32 Velocity.net Cache Enterprise Library Caching Application Block MemCached Win32: Up until recently I have used MemCached Win32. This is a akin to a web farm (many servers serving the same content for high availability) but it is a cache farm. This means that you can install it locally on your web server initially if you don't have the resources to go bigger. Then as you go down the road you can scale horizontally (more servers) or vertically (more hardware). This is a product that was ported from the original MemCached to work on Windows. This product has been used extensively in very high traffic sites. http://lineofthought.com/tools/memcached Velocity: This is Microsofts answer to products such as MemCached. MemCached has been out for quite some time, Velocity is in CTP mode. I must say that from what I have read so far this product will certainly turn my head once it is out. But I can't bring myself to run big production projects on a CTP product with zero track record. I have started playing with it though as once it gains momentum MemCached won't even compare for those locked in the windows world! http://blogs.msdn.com/velocity/.NET Cache: There is no reason to discount the standard.NET Cache. It is built in and ready to use for free and with no (major) set up required. It offers flexibility by way of offering mechanisms for storing items in local memory, a SINGLE state server, or a centralized database. Where Velocity steps in is when you need more than a single state server (cache in memory) and don't want to use a slow database for holding your cache. Enterprise Application Block: I stay away from all of the Enterprise Application Blocks. They are heavy frameworks that give more than I generally require! As long as you remember to wrap everything that touches code that is not your own and follow simple rules for coding, stick to any of the other methods over this one! (just my opinion of course - MySpace leverages as much as they can out of Enterprise Application Blocks!) You don't have to choose up front! I generally create a cache wrapper that I communicate with in my code for methods such as Get, Set, Exists, Remove, ListKeys, etc. This then points to an underlying level of cache abstraction that can point to MemCached, Velocity, or.NET cache. I use StructureMap (or choose another IoC container) to inject which form of cache I want to use for a given environment. In my local dev box I might use.NET cache in the session. In production I generally use MemCached Win 32. But regardless of how it is set up you can easily swap things around to try each system out to see what works best for you. You just need to make sure that you application knows as little as possible about how things are cached! Once this layer of abstraction is in place you can then do things such as run a compression algorithm (gzip) for all the data that is going in and out of cache which would allow you to store 10 times the amount of data in cache. - transparently. I cover.NET Cache, MemCached Win32, StructureMap, and the appropriate abstractions in my book if you are interested! ASP.NET 3.5 Social Networking ( http://www.amazon.com/ASP-NET-3-5-Social-Networking-Enterprise-ready/dp/1847194788/ref=sr_1_1?ie=UTF8&s=books&qid=1225408005&sr=8-1 ) Andrew Siemer www.andrewsiemer.com blog.andrewsiemer.com www.socialnetworkingin.net Update Changed the link that lists sites using memcached. Thank you David for noticing that it was broken!
[ "caching", ".net-2.0", "memcached", "enterprise-library" ]
29
18
13,489
4
0
2008-08-22T06:07:29.487000
2009-06-11T22:21:21.470000
21,877
21,887
Dynamically Rendering asp:Image from BLOB entry in ASP.NET
What I want to achieve is this. I want to give the user the ability to upload an image file, store the image in BLOB in SQL Server, and then use this image as a logo in other pages of the site. I have done this by using Response.Clear(); Response.ContentType = "image/pjpeg"; Response.BinaryWrite(imageConents); Response.End(); but to do this, I use a User control in the place where I want to show the image. I want to do it if possible using an asp:Image control, or even a pure old html image control. Is this possible?
Add a 'Generic Handler' to your web project, name it something like Image.ashx. Implement it like this: public class ImageHandler: IHttpHandler { public void ProcessRequest(HttpContext context) { using(Image image = GetImage(context.Request.QueryString["ID"])) { context.Response.ContentType = "image/jpeg"; image.Save(context.Response.OutputStream, ImageFormat.Jpeg); } } public bool IsReusable { get { return true; } } } Now just implement the GetImage method to load the image with the given ID, and you can use to display it. You might want to think about implementing some form of caching in the handler too. And remember if you want to change the image format to PNG, you need to use an intermediate MemoryStream (because PNGs require a seekable stream to be saved).
Dynamically Rendering asp:Image from BLOB entry in ASP.NET What I want to achieve is this. I want to give the user the ability to upload an image file, store the image in BLOB in SQL Server, and then use this image as a logo in other pages of the site. I have done this by using Response.Clear(); Response.ContentType = "image/pjpeg"; Response.BinaryWrite(imageConents); Response.End(); but to do this, I use a User control in the place where I want to show the image. I want to do it if possible using an asp:Image control, or even a pure old html image control. Is this possible?
TITLE: Dynamically Rendering asp:Image from BLOB entry in ASP.NET QUESTION: What I want to achieve is this. I want to give the user the ability to upload an image file, store the image in BLOB in SQL Server, and then use this image as a logo in other pages of the site. I have done this by using Response.Clear(); Response.ContentType = "image/pjpeg"; Response.BinaryWrite(imageConents); Response.End(); but to do this, I use a User control in the place where I want to show the image. I want to do it if possible using an asp:Image control, or even a pure old html image control. Is this possible? ANSWER: Add a 'Generic Handler' to your web project, name it something like Image.ashx. Implement it like this: public class ImageHandler: IHttpHandler { public void ProcessRequest(HttpContext context) { using(Image image = GetImage(context.Request.QueryString["ID"])) { context.Response.ContentType = "image/jpeg"; image.Save(context.Response.OutputStream, ImageFormat.Jpeg); } } public bool IsReusable { get { return true; } } } Now just implement the GetImage method to load the image with the given ID, and you can use to display it. You might want to think about implementing some form of caching in the handler too. And remember if you want to change the image format to PNG, you need to use an intermediate MemoryStream (because PNGs require a seekable stream to be saved).
[ "asp.net" ]
13
18
32,129
6
0
2008-08-22T06:14:06.600000
2008-08-22T06:25:31.317000
21,879
21,962
Where can I find a "Math topic dependency tree" to assist my self-guided refresher on the subject?
I'm trying to reteach myself some long forgotten math skills. This is part of a much larger project to effectively "teach myself software development" from the ground up (the details are here if you're interested in helping out). My biggest stumbling block so far has been math - how can I learn about algorithms and asymptotic notation without it?? What I'm looking for is some sort of "dependency tree" showing what I need to know. Is calculus required before discrete? What do I need to know before calculus (read: components to the general "pre-calculus" topic)? What can I cut out to fast track the project ("what can I go back for later")? Thank!
Here's how my school did it: base: algebra trigonometry analytic geometry track 1 track 2 track 3 calc 1 linear algebra statistics calc 2 discrete math 1 calc 3 (multivariable) discrete math 2 differential equations The base courses were a prerequisite for everything, the tracks were independent and taken in order. So to answer your specific question, only algebra is needed for discrete. If you want to fast track, do one of these: algebra, discrete algebra, linear algebra, discrete (if you want to cover matrices first) HTH... It about killed me when I returned to school and took these, but I'm a much better programmer for it. Good Luck!
Where can I find a "Math topic dependency tree" to assist my self-guided refresher on the subject? I'm trying to reteach myself some long forgotten math skills. This is part of a much larger project to effectively "teach myself software development" from the ground up (the details are here if you're interested in helping out). My biggest stumbling block so far has been math - how can I learn about algorithms and asymptotic notation without it?? What I'm looking for is some sort of "dependency tree" showing what I need to know. Is calculus required before discrete? What do I need to know before calculus (read: components to the general "pre-calculus" topic)? What can I cut out to fast track the project ("what can I go back for later")? Thank!
TITLE: Where can I find a "Math topic dependency tree" to assist my self-guided refresher on the subject? QUESTION: I'm trying to reteach myself some long forgotten math skills. This is part of a much larger project to effectively "teach myself software development" from the ground up (the details are here if you're interested in helping out). My biggest stumbling block so far has been math - how can I learn about algorithms and asymptotic notation without it?? What I'm looking for is some sort of "dependency tree" showing what I need to know. Is calculus required before discrete? What do I need to know before calculus (read: components to the general "pre-calculus" topic)? What can I cut out to fast track the project ("what can I go back for later")? Thank! ANSWER: Here's how my school did it: base: algebra trigonometry analytic geometry track 1 track 2 track 3 calc 1 linear algebra statistics calc 2 discrete math 1 calc 3 (multivariable) discrete math 2 differential equations The base courses were a prerequisite for everything, the tracks were independent and taken in order. So to answer your specific question, only algebra is needed for discrete. If you want to fast track, do one of these: algebra, discrete algebra, linear algebra, discrete (if you want to cover matrices first) HTH... It about killed me when I returned to school and took these, but I'm a much better programmer for it. Good Luck!
[ "math" ]
12
6
5,130
5
0
2008-08-22T06:15:39.717000
2008-08-22T09:07:14.673000
21,912
21,921
IntelliSense for XElement objects with XML schema
Reading an article called "Increase LINQ Query Performance" in July's MSDN magazine, the author states that using an Imports in VB providing a path to schema in the current project will turn IntelliSense on for XElement. In the code provided, he uses statements like xelement.@name to retreive attributes values and so on. I did not try this out myself in VB but I would like to use that in C#. This really looks like LINQ to XSD. Is there any equivalent in C#? It seems that it is not possible to use a namespace inside C# code, there is no using equivalent to this Import statement.
This post claims to have a link to a video that shows how to use VB9's XML Literals in C#. However, it only really discusses them and from what I can gather, you cannot use them in C#. http://blogs.msdn.com/bethmassi/archive/2008/07/03/teched-panel-vb-xml-literals-for-c-developers.aspx
IntelliSense for XElement objects with XML schema Reading an article called "Increase LINQ Query Performance" in July's MSDN magazine, the author states that using an Imports in VB providing a path to schema in the current project will turn IntelliSense on for XElement. In the code provided, he uses statements like xelement.@name to retreive attributes values and so on. I did not try this out myself in VB but I would like to use that in C#. This really looks like LINQ to XSD. Is there any equivalent in C#? It seems that it is not possible to use a namespace inside C# code, there is no using equivalent to this Import statement.
TITLE: IntelliSense for XElement objects with XML schema QUESTION: Reading an article called "Increase LINQ Query Performance" in July's MSDN magazine, the author states that using an Imports in VB providing a path to schema in the current project will turn IntelliSense on for XElement. In the code provided, he uses statements like xelement.@name to retreive attributes values and so on. I did not try this out myself in VB but I would like to use that in C#. This really looks like LINQ to XSD. Is there any equivalent in C#? It seems that it is not possible to use a namespace inside C# code, there is no using equivalent to this Import statement. ANSWER: This post claims to have a link to a video that shows how to use VB9's XML Literals in C#. However, it only really discusses them and from what I can gather, you cannot use them in C#. http://blogs.msdn.com/bethmassi/archive/2008/07/03/teched-panel-vb-xml-literals-for-c-developers.aspx
[ "c#", "linq", "xsd", "linq-to-xml", "vb.net-to-c#" ]
2
4
1,649
1
0
2008-08-22T07:07:17.643000
2008-08-22T07:14:46.360000
21,934
21,964
Why Java and Python garbage collection methods are different?
Python uses the reference count method to handle object life time. So an object that has no more use will be immediately destroyed. But, in Java, the GC(garbage collector) destroys objects which are no longer used at a specific time. Why does Java choose this strategy and what is the benefit from this? Is this better than the Python approach?
There are drawbacks of using reference counting. One of the most mentioned is circular references: Suppose A references B, B references C and C references B. If A were to drop its reference to B, both B and C will still have a reference count of 1 and won't be deleted with traditional reference counting. CPython (reference counting is not part of python itself, but part of the C implementation thereof) catches circular references with a separate garbage collection routine that it runs periodically... Another drawback: Reference counting can make execution slower. Each time an object is referenced and dereferenced, the interpreter/VM must check to see if the count has gone down to 0 (and then deallocate if it did). Garbage Collection does not need to do this. Also, Garbage Collection can be done in a separate thread (though it can be a bit tricky). On machines with lots of RAM and for processes that use memory only slowly, you might not want to be doing GC at all! Reference counting would be a bit of a drawback there in terms of performance...
Why Java and Python garbage collection methods are different? Python uses the reference count method to handle object life time. So an object that has no more use will be immediately destroyed. But, in Java, the GC(garbage collector) destroys objects which are no longer used at a specific time. Why does Java choose this strategy and what is the benefit from this? Is this better than the Python approach?
TITLE: Why Java and Python garbage collection methods are different? QUESTION: Python uses the reference count method to handle object life time. So an object that has no more use will be immediately destroyed. But, in Java, the GC(garbage collector) destroys objects which are no longer used at a specific time. Why does Java choose this strategy and what is the benefit from this? Is this better than the Python approach? ANSWER: There are drawbacks of using reference counting. One of the most mentioned is circular references: Suppose A references B, B references C and C references B. If A were to drop its reference to B, both B and C will still have a reference count of 1 and won't be deleted with traditional reference counting. CPython (reference counting is not part of python itself, but part of the C implementation thereof) catches circular references with a separate garbage collection routine that it runs periodically... Another drawback: Reference counting can make execution slower. Each time an object is referenced and dereferenced, the interpreter/VM must check to see if the count has gone down to 0 (and then deallocate if it did). Garbage Collection does not need to do this. Also, Garbage Collection can be done in a separate thread (though it can be a bit tricky). On machines with lots of RAM and for processes that use memory only slowly, you might not want to be doing GC at all! Reference counting would be a bit of a drawback there in terms of performance...
[ "java", "python", "garbage-collection" ]
66
54
22,254
9
0
2008-08-22T07:35:26.703000
2008-08-22T09:10:06.943000
21,938
21,950
Is it really that bad to catch a general exception?
Whilst analysing some legacy code with FXCop, it occurred to me is it really that bad to catch a general exception error within a try block or should you be looking for a specific exception. Thoughts on a postcard please.
Obviously this is one of those questions where the only real answer is "it depends." The main thing it depends on is where your are catching the exception. In general libraries should be more conservative with catching exceptions whereas at the top level of your program (e.g. in your main method or in the top of the action method in a controller, etc) you can be more liberal with what you catch. The reason for this is that e.g. you don't want to catch all exceptions in a library because you may mask problems that have nothing to do with your library, like "OutOfMemoryException" which you really would prefer bubbles up so that the user can be notified, etc. On the other hand, if you are talking about catching exceptions inside your main() method which catches the exception, displays it and then exits... well, it's probably safe to catch just about any exception here. The most important rule about catching all exceptions is that you should never just swallow all exceptions silently... e.g. something like this in Java: try { something(); } catch (Exception ex) {} or this in Python: try: something() except: pass Because these can be some of the hardest issues to track down. A good rule of thumb is that you should only catch exceptions that you can properly deal with yourself. If you cannot handle the exception completely then you should let it bubble up to someone who can.
Is it really that bad to catch a general exception? Whilst analysing some legacy code with FXCop, it occurred to me is it really that bad to catch a general exception error within a try block or should you be looking for a specific exception. Thoughts on a postcard please.
TITLE: Is it really that bad to catch a general exception? QUESTION: Whilst analysing some legacy code with FXCop, it occurred to me is it really that bad to catch a general exception error within a try block or should you be looking for a specific exception. Thoughts on a postcard please. ANSWER: Obviously this is one of those questions where the only real answer is "it depends." The main thing it depends on is where your are catching the exception. In general libraries should be more conservative with catching exceptions whereas at the top level of your program (e.g. in your main method or in the top of the action method in a controller, etc) you can be more liberal with what you catch. The reason for this is that e.g. you don't want to catch all exceptions in a library because you may mask problems that have nothing to do with your library, like "OutOfMemoryException" which you really would prefer bubbles up so that the user can be notified, etc. On the other hand, if you are talking about catching exceptions inside your main() method which catches the exception, displays it and then exits... well, it's probably safe to catch just about any exception here. The most important rule about catching all exceptions is that you should never just swallow all exceptions silently... e.g. something like this in Java: try { something(); } catch (Exception ex) {} or this in Python: try: something() except: pass Because these can be some of the hardest issues to track down. A good rule of thumb is that you should only catch exceptions that you can properly deal with yourself. If you cannot handle the exception completely then you should let it bubble up to someone who can.
[ "exception" ]
76
119
65,949
16
0
2008-08-22T07:41:13.223000
2008-08-22T08:53:55.470000
21,956
22,256
How do I compare two arrays of DataRow objects in PowerShell?
I have two arrays of System.Data.DataRow objects which I want to compare. The rows have two columns A and B. Column A is a key and I want to find out which rows have had their B column changed and which rows have been added or deleted. How do I do this in PowerShell?
I wrote a script to do this a little while back. The script (Compare-QueryResults.ps1) is available here and you will also need my Run-SQLQuery script (available here ) or you can replace that with a script or function of your own. Basically, what the script does is take the results of each of your queries and break the datarows apart so that each field is its own object. It then uses Compare-Object to check for any differences between the data in those rows. It returns a comparison object that shows you all the differences between the data returned. The results are an object, so you can save them to a variable and use Sort-Object or the Format-* cmdlets with them. Good luck. If you have any problems with the scripts, let me know, I'd be happy to walk you through them. I've been using them for application testing, seeing what rows are being modified by different actions in a program.
How do I compare two arrays of DataRow objects in PowerShell? I have two arrays of System.Data.DataRow objects which I want to compare. The rows have two columns A and B. Column A is a key and I want to find out which rows have had their B column changed and which rows have been added or deleted. How do I do this in PowerShell?
TITLE: How do I compare two arrays of DataRow objects in PowerShell? QUESTION: I have two arrays of System.Data.DataRow objects which I want to compare. The rows have two columns A and B. Column A is a key and I want to find out which rows have had their B column changed and which rows have been added or deleted. How do I do this in PowerShell? ANSWER: I wrote a script to do this a little while back. The script (Compare-QueryResults.ps1) is available here and you will also need my Run-SQLQuery script (available here ) or you can replace that with a script or function of your own. Basically, what the script does is take the results of each of your queries and break the datarows apart so that each field is its own object. It then uses Compare-Object to check for any differences between the data in those rows. It returns a comparison object that shows you all the differences between the data returned. The results are an object, so you can save them to a variable and use Sort-Object or the Format-* cmdlets with them. Good luck. If you have any problems with the scripts, let me know, I'd be happy to walk you through them. I've been using them for application testing, seeing what rows are being modified by different actions in a program.
[ "arrays", "powershell", "comparison" ]
4
4
5,298
3
0
2008-08-22T09:00:26.250000
2008-08-22T12:53:16.767000
21,965
21,991
Programmatically encrypting a config-file in .NET
Could somebody please do a rundown of how to programmatically encrypt a config-file in.NET, preferably in C#. What I would like to do is do some kind of check on an application's startup to see if a section is unprotected, and if it is, then encrypt it. This for both settings and connection-strings. Also if anyone could list the types of encryption-providers and what is the difference between them. I don't know if the code for doing this in a normal WinForms-application is transparent to doing this in ASP.NET.
To summarize the answers and what I've found so far, here are some good links to answer this question: Encrypting Configuration Information in ASP.NET 2.0 Applications - 4GuysFromRolla.com How To: Encrypt Configuration Sections in ASP.NET 2.0 Using DPAPI - MSDN Please feel free to complement with other links, maybe some to WinForms- or WPF-applications.
Programmatically encrypting a config-file in .NET Could somebody please do a rundown of how to programmatically encrypt a config-file in.NET, preferably in C#. What I would like to do is do some kind of check on an application's startup to see if a section is unprotected, and if it is, then encrypt it. This for both settings and connection-strings. Also if anyone could list the types of encryption-providers and what is the difference between them. I don't know if the code for doing this in a normal WinForms-application is transparent to doing this in ASP.NET.
TITLE: Programmatically encrypting a config-file in .NET QUESTION: Could somebody please do a rundown of how to programmatically encrypt a config-file in.NET, preferably in C#. What I would like to do is do some kind of check on an application's startup to see if a section is unprotected, and if it is, then encrypt it. This for both settings and connection-strings. Also if anyone could list the types of encryption-providers and what is the difference between them. I don't know if the code for doing this in a normal WinForms-application is transparent to doing this in ASP.NET. ANSWER: To summarize the answers and what I've found so far, here are some good links to answer this question: Encrypting Configuration Information in ASP.NET 2.0 Applications - 4GuysFromRolla.com How To: Encrypt Configuration Sections in ASP.NET 2.0 Using DPAPI - MSDN Please feel free to complement with other links, maybe some to WinForms- or WPF-applications.
[ "c#", ".net", "configuration", "encryption", "configuration-files" ]
19
14
16,999
5
0
2008-08-22T09:12:54.830000
2008-08-22T09:46:35.780000
21,987
23,285
FlashWindowEx FLASHW_STOP still keeps taskbar colored
I am developing an application that controls an Machine. When I receive an error from the Machine the users should be able to directly notice it, one way that is done is Flashing the tray on the taskbar. When the machine clears the error the tray should stop flashing. There's one little annoyance using the FlashWindowEx function, when I clear the flashing of the window, it stays (in my case WinXP) orange (not flashing). [Flags] public enum FlashMode { /// /// Stop flashing. The system restores the window to its original state. /// FLASHW_STOP = 0, /// /// Flash the window caption. /// FLASHW_CAPTION = 1, /// /// Flash the taskbar button. /// FLASHW_TRAY = 2, /// /// Flash both the window caption and taskbar button. /// This is equivalent to setting the FLASHW_CAPTION | FLASHW_TRAY flags. /// FLASHW_ALL = 3, /// /// Flash continuously, until the FLASHW_STOP flag is set. /// FLASHW_TIMER = 4, /// /// Flash continuously until the window comes to the foreground. /// FLASHW_TIMERNOFG = 12 } public static bool FlashWindowEx(IntPtr hWnd, FlashMode fm) { FLASHWINFO fInfo = new FLASHWINFO(); fInfo.cbSize = Convert.ToUInt32(Marshal.SizeOf(fInfo)); fInfo.hwnd = hWnd; fInfo.dwFlags = (UInt32)fm; fInfo.uCount = UInt32.MaxValue; fInfo.dwTimeout = 0; return FlashWindowEx(ref fInfo); } [StructLayout(LayoutKind.Sequential)] public struct FLASHWINFO { public UInt32 cbSize; public IntPtr hwnd; public UInt32 dwFlags; public UInt32 uCount; public UInt32 dwTimeout; } In my case I use FLASHW_TRAY to start flashing and FLASHW_STOP to stop the flashing. Am I doing something wrong or is this a known bug of WinXP and is there a fix for it?
Behaviour is the same when a window finishes flashing for as long as it's supposed to: the taskbar button stays coloured. I don't think this is a bug. If you think about it, when you use FLASHW_STOP, the flashing does in fact stop, but the point of the flashing is to get the user's attention. The button stays coloured because the user still may not have looked down and discovered which window was trying to get her attention. Keeping the button coloured keeps that information available.
FlashWindowEx FLASHW_STOP still keeps taskbar colored I am developing an application that controls an Machine. When I receive an error from the Machine the users should be able to directly notice it, one way that is done is Flashing the tray on the taskbar. When the machine clears the error the tray should stop flashing. There's one little annoyance using the FlashWindowEx function, when I clear the flashing of the window, it stays (in my case WinXP) orange (not flashing). [Flags] public enum FlashMode { /// /// Stop flashing. The system restores the window to its original state. /// FLASHW_STOP = 0, /// /// Flash the window caption. /// FLASHW_CAPTION = 1, /// /// Flash the taskbar button. /// FLASHW_TRAY = 2, /// /// Flash both the window caption and taskbar button. /// This is equivalent to setting the FLASHW_CAPTION | FLASHW_TRAY flags. /// FLASHW_ALL = 3, /// /// Flash continuously, until the FLASHW_STOP flag is set. /// FLASHW_TIMER = 4, /// /// Flash continuously until the window comes to the foreground. /// FLASHW_TIMERNOFG = 12 } public static bool FlashWindowEx(IntPtr hWnd, FlashMode fm) { FLASHWINFO fInfo = new FLASHWINFO(); fInfo.cbSize = Convert.ToUInt32(Marshal.SizeOf(fInfo)); fInfo.hwnd = hWnd; fInfo.dwFlags = (UInt32)fm; fInfo.uCount = UInt32.MaxValue; fInfo.dwTimeout = 0; return FlashWindowEx(ref fInfo); } [StructLayout(LayoutKind.Sequential)] public struct FLASHWINFO { public UInt32 cbSize; public IntPtr hwnd; public UInt32 dwFlags; public UInt32 uCount; public UInt32 dwTimeout; } In my case I use FLASHW_TRAY to start flashing and FLASHW_STOP to stop the flashing. Am I doing something wrong or is this a known bug of WinXP and is there a fix for it?
TITLE: FlashWindowEx FLASHW_STOP still keeps taskbar colored QUESTION: I am developing an application that controls an Machine. When I receive an error from the Machine the users should be able to directly notice it, one way that is done is Flashing the tray on the taskbar. When the machine clears the error the tray should stop flashing. There's one little annoyance using the FlashWindowEx function, when I clear the flashing of the window, it stays (in my case WinXP) orange (not flashing). [Flags] public enum FlashMode { /// /// Stop flashing. The system restores the window to its original state. /// FLASHW_STOP = 0, /// /// Flash the window caption. /// FLASHW_CAPTION = 1, /// /// Flash the taskbar button. /// FLASHW_TRAY = 2, /// /// Flash both the window caption and taskbar button. /// This is equivalent to setting the FLASHW_CAPTION | FLASHW_TRAY flags. /// FLASHW_ALL = 3, /// /// Flash continuously, until the FLASHW_STOP flag is set. /// FLASHW_TIMER = 4, /// /// Flash continuously until the window comes to the foreground. /// FLASHW_TIMERNOFG = 12 } public static bool FlashWindowEx(IntPtr hWnd, FlashMode fm) { FLASHWINFO fInfo = new FLASHWINFO(); fInfo.cbSize = Convert.ToUInt32(Marshal.SizeOf(fInfo)); fInfo.hwnd = hWnd; fInfo.dwFlags = (UInt32)fm; fInfo.uCount = UInt32.MaxValue; fInfo.dwTimeout = 0; return FlashWindowEx(ref fInfo); } [StructLayout(LayoutKind.Sequential)] public struct FLASHWINFO { public UInt32 cbSize; public IntPtr hwnd; public UInt32 dwFlags; public UInt32 uCount; public UInt32 dwTimeout; } In my case I use FLASHW_TRAY to start flashing and FLASHW_STOP to stop the flashing. Am I doing something wrong or is this a known bug of WinXP and is there a fix for it? ANSWER: Behaviour is the same when a window finishes flashing for as long as it's supposed to: the taskbar button stays coloured. I don't think this is a bug. If you think about it, when you use FLASHW_STOP, the flashing does in fact stop, but the point of the flashing is to get the user's attention. The button stays coloured because the user still may not have looked down and discovered which window was trying to get her attention. Keeping the button coloured keeps that information available.
[ "c#", "winapi", "pinvoke" ]
7
7
3,864
5
0
2008-08-22T09:42:41.047000
2008-08-22T19:33:47.320000
21,992
22,005
XmlHttpRequest return values
I'm looking for (arguably) the correct way to return data from a XmlHttpRequest. Options I see are: Plain HTML. Let the request format the data and return it in a usable format. Advantage: easy to consume by the calling page. Disadvantage: Very rigid, stuck with a fixed layout. XML. Let the request return XML, format it using XSLT on the calling page. Advantage: the requested service is easily consumed by other sources. Disadvantage: Is browser support for XSLT good enough? JSON. Let the request return JSON, consume it using javascript, render HTML accordingly. Advantage: easier to 'OO-ify' the javascript making the request. Disadvantage: Probably not as easy to use as the previous two options. I've also thought about going for option one while abstracting the view logic in the called service in such a way that switching in and out different layouts would be trivial. Personally I think this option is the best out of three, for compatibility reasons. While typing this, I got another insight. Would it be a good idea to allow all three response formats, based on a parameter added to the request?
If you're looking for a quick solution that should work with most available frameworks, I'd go for JSON. It's easy to start with and works. If you're trying to build a larger application that you're going to extend (in terms of size or maybe your own API for 3rd party extensions) I'd go for XML. You could write a proxy to provide the information in JSON or HTML too, but having XML as the main source is definitly worth the time and effort while building the app. Like @John Topley said: it depends.
XmlHttpRequest return values I'm looking for (arguably) the correct way to return data from a XmlHttpRequest. Options I see are: Plain HTML. Let the request format the data and return it in a usable format. Advantage: easy to consume by the calling page. Disadvantage: Very rigid, stuck with a fixed layout. XML. Let the request return XML, format it using XSLT on the calling page. Advantage: the requested service is easily consumed by other sources. Disadvantage: Is browser support for XSLT good enough? JSON. Let the request return JSON, consume it using javascript, render HTML accordingly. Advantage: easier to 'OO-ify' the javascript making the request. Disadvantage: Probably not as easy to use as the previous two options. I've also thought about going for option one while abstracting the view logic in the called service in such a way that switching in and out different layouts would be trivial. Personally I think this option is the best out of three, for compatibility reasons. While typing this, I got another insight. Would it be a good idea to allow all three response formats, based on a parameter added to the request?
TITLE: XmlHttpRequest return values QUESTION: I'm looking for (arguably) the correct way to return data from a XmlHttpRequest. Options I see are: Plain HTML. Let the request format the data and return it in a usable format. Advantage: easy to consume by the calling page. Disadvantage: Very rigid, stuck with a fixed layout. XML. Let the request return XML, format it using XSLT on the calling page. Advantage: the requested service is easily consumed by other sources. Disadvantage: Is browser support for XSLT good enough? JSON. Let the request return JSON, consume it using javascript, render HTML accordingly. Advantage: easier to 'OO-ify' the javascript making the request. Disadvantage: Probably not as easy to use as the previous two options. I've also thought about going for option one while abstracting the view logic in the called service in such a way that switching in and out different layouts would be trivial. Personally I think this option is the best out of three, for compatibility reasons. While typing this, I got another insight. Would it be a good idea to allow all three response formats, based on a parameter added to the request? ANSWER: If you're looking for a quick solution that should work with most available frameworks, I'd go for JSON. It's easy to start with and works. If you're trying to build a larger application that you're going to extend (in terms of size or maybe your own API for 3rd party extensions) I'd go for XML. You could write a proxy to provide the information in JSON or HTML too, but having XML as the main source is definitly worth the time and effort while building the app. Like @John Topley said: it depends.
[ "javascript", "ajax" ]
3
2
2,004
5
0
2008-08-22T09:47:15.997000
2008-08-22T09:59:15.437000
21,999
22,793
WPF Anti aliasing workaround
Anti aliasing cannot be turned off in WPF. But I want to remove the blurred look of WPF fonts when they are small. One possibility would be to use a.net 2.0 component. This looks like it would lose the transparency capability and Blend support. Never tried it though. Anyone has a solution for this? Any drawbacks from it? Thank you
Have you tried putting a WindowsFormsHost control on a WPF window/control? That will allow WPF to render a WinForms control. UPDATE November 2012: This question and answer is 4 years old. Text rendering has since improved in WPF. Please don't put WinForms controls in WPF apps; that was a hackish way to fix font rendering. It's no longer needed.
WPF Anti aliasing workaround Anti aliasing cannot be turned off in WPF. But I want to remove the blurred look of WPF fonts when they are small. One possibility would be to use a.net 2.0 component. This looks like it would lose the transparency capability and Blend support. Never tried it though. Anyone has a solution for this? Any drawbacks from it? Thank you
TITLE: WPF Anti aliasing workaround QUESTION: Anti aliasing cannot be turned off in WPF. But I want to remove the blurred look of WPF fonts when they are small. One possibility would be to use a.net 2.0 component. This looks like it would lose the transparency capability and Blend support. Never tried it though. Anyone has a solution for this? Any drawbacks from it? Thank you ANSWER: Have you tried putting a WindowsFormsHost control on a WPF window/control? That will allow WPF to render a WinForms control. UPDATE November 2012: This question and answer is 4 years old. Text rendering has since improved in WPF. Please don't put WinForms controls in WPF apps; that was a hackish way to fix font rendering. It's no longer needed.
[ ".net", "wpf" ]
10
3
13,374
6
0
2008-08-22T09:54:43.793000
2008-08-22T16:28:35.890000
22,000
22,025
Table cells larger than they are meant to be
I've created a map system for a game that runs on the principle of drawing the picture of the map from tiles. There are many reasons for this which I won't go into here but if you really want to know then I'm sure you can find out how to contact me;) I have made the latest version live so you can see exactly where the problem lies and the source. The issue is the line between the top 2 tiles and the bottom 2 tiles, I can't figure out why it's gone like this and any help would be appreciated. In the source is a marker called "stackoverflow", if you search for "stackoverflow" when viewing source then it should take you to the table in question. I have also uploaded an image of the issue.
I think you need to use display: block on your images. When images are inline there's a little extra space for the line spacing.
Table cells larger than they are meant to be I've created a map system for a game that runs on the principle of drawing the picture of the map from tiles. There are many reasons for this which I won't go into here but if you really want to know then I'm sure you can find out how to contact me;) I have made the latest version live so you can see exactly where the problem lies and the source. The issue is the line between the top 2 tiles and the bottom 2 tiles, I can't figure out why it's gone like this and any help would be appreciated. In the source is a marker called "stackoverflow", if you search for "stackoverflow" when viewing source then it should take you to the table in question. I have also uploaded an image of the issue.
TITLE: Table cells larger than they are meant to be QUESTION: I've created a map system for a game that runs on the principle of drawing the picture of the map from tiles. There are many reasons for this which I won't go into here but if you really want to know then I'm sure you can find out how to contact me;) I have made the latest version live so you can see exactly where the problem lies and the source. The issue is the line between the top 2 tiles and the bottom 2 tiles, I can't figure out why it's gone like this and any help would be appreciated. In the source is a marker called "stackoverflow", if you search for "stackoverflow" when viewing source then it should take you to the table in question. I have also uploaded an image of the issue. ANSWER: I think you need to use display: block on your images. When images are inline there's a little extra space for the line spacing.
[ "html", "css" ]
15
35
9,607
4
0
2008-08-22T09:55:34.057000
2008-08-22T10:14:24.387000
22,011
22,044
Switching to ORMs
I'm toying with the idea of phasing in an ORM into an application I support. The app is not very structured with no unit tests. So any change will be risky. I'm obviously concerned that I've got a good enough reason to change. The idea is that there will be less boiler plate code for data access and there for greater productivity. Do this ring true with your experiences? Is it possible or even a good idea to phase it in? What are the downsides of an ORM?
I would strongly recommend getting a copy of Michael Feather's book Working Effectively With Legacy Code (by "Legacy Code" Feathers means any system that isn't adequately covered by unit tests). It is full of good ideas which should help you with your refactoring and phasing in of best practices. Sure, you could phase in the introduction of an ORM, initially using it for accessing some subset of your domain model. And yes, I have found that use of an ORM speeds up development time - this is one of the key benefits and I certainly don't miss the days when I used to laboriously hand-craft data access layers. Downsides of ORM - from experience, there is inevitably a bit of a learning curve in getting to grips with the concepts, configuration and idiosyncracies of the chosen ORM solution. Edit: corrected author's name
Switching to ORMs I'm toying with the idea of phasing in an ORM into an application I support. The app is not very structured with no unit tests. So any change will be risky. I'm obviously concerned that I've got a good enough reason to change. The idea is that there will be less boiler plate code for data access and there for greater productivity. Do this ring true with your experiences? Is it possible or even a good idea to phase it in? What are the downsides of an ORM?
TITLE: Switching to ORMs QUESTION: I'm toying with the idea of phasing in an ORM into an application I support. The app is not very structured with no unit tests. So any change will be risky. I'm obviously concerned that I've got a good enough reason to change. The idea is that there will be less boiler plate code for data access and there for greater productivity. Do this ring true with your experiences? Is it possible or even a good idea to phase it in? What are the downsides of an ORM? ANSWER: I would strongly recommend getting a copy of Michael Feather's book Working Effectively With Legacy Code (by "Legacy Code" Feathers means any system that isn't adequately covered by unit tests). It is full of good ideas which should help you with your refactoring and phasing in of best practices. Sure, you could phase in the introduction of an ORM, initially using it for accessing some subset of your domain model. And yes, I have found that use of an ORM speeds up development time - this is one of the key benefits and I certainly don't miss the days when I used to laboriously hand-craft data access layers. Downsides of ORM - from experience, there is inevitably a bit of a learning curve in getting to grips with the concepts, configuration and idiosyncracies of the chosen ORM solution. Edit: corrected author's name
[ "language-agnostic", "orm" ]
2
3
362
7
0
2008-08-22T10:05:44.283000
2008-08-22T10:34:57.677000
22,012
22,026
Loading assemblies and its dependencies
My application dynamically loads assemblies at runtime from specific subfolders. These assemblies are compiled with dependencies to other assemblies. The runtime trys to load these from the application directory. But I want to put them into the modules directory. Is there a way to tell the runtime that the dlls are in a seperate subfolder?
One nice approach I've used lately is to add an event handler for the AppDomain's AssemblyResolve event. AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler); Then in the event handler method you can load the assembly that was attempted to be resolved using one of the Assembly.Load, Assembly.LoadFrom overrides and return it from the method. EDIT: Based on your additional information I think using the technique above, specifically resolving the references to an assembly yourself is the only real approach that is going to work without restructuring your app. What it gives you is that the location of each and every assembly that the CLR fails to resolve can be determined and loaded by your code at runtime... I've used this in similar situations for both pluggable architectures and for an assembly reference integrity scanning tool.
Loading assemblies and its dependencies My application dynamically loads assemblies at runtime from specific subfolders. These assemblies are compiled with dependencies to other assemblies. The runtime trys to load these from the application directory. But I want to put them into the modules directory. Is there a way to tell the runtime that the dlls are in a seperate subfolder?
TITLE: Loading assemblies and its dependencies QUESTION: My application dynamically loads assemblies at runtime from specific subfolders. These assemblies are compiled with dependencies to other assemblies. The runtime trys to load these from the application directory. But I want to put them into the modules directory. Is there a way to tell the runtime that the dlls are in a seperate subfolder? ANSWER: One nice approach I've used lately is to add an event handler for the AppDomain's AssemblyResolve event. AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler); Then in the event handler method you can load the assembly that was attempted to be resolved using one of the Assembly.Load, Assembly.LoadFrom overrides and return it from the method. EDIT: Based on your additional information I think using the technique above, specifically resolving the references to an assembly yourself is the only real approach that is going to work without restructuring your app. What it gives you is that the location of each and every assembly that the CLR fails to resolve can be determined and loaded by your code at runtime... I've used this in similar situations for both pluggable architectures and for an assembly reference integrity scanning tool.
[ "c#", ".net" ]
22
19
12,993
3
0
2008-08-22T10:06:48.210000
2008-08-22T10:15:01.203000
22,067
938,672
MS Project Gantt chart control usage in C#
Has anybody used the MS Project Gantt chart control in C#? If yes, can you share some resources regarding this?
You could also check Gantt Chart Library for WPF or Windows Forms, they do not require Microsoft Project installed on the client computer, but provide similar UI for project and related Gantt Charts.
MS Project Gantt chart control usage in C# Has anybody used the MS Project Gantt chart control in C#? If yes, can you share some resources regarding this?
TITLE: MS Project Gantt chart control usage in C# QUESTION: Has anybody used the MS Project Gantt chart control in C#? If yes, can you share some resources regarding this? ANSWER: You could also check Gantt Chart Library for WPF or Windows Forms, they do not require Microsoft Project installed on the client computer, but provide similar UI for project and related Gantt Charts.
[ "c#", ".net-2.0", "controls", "ms-project", "gantt-chart" ]
8
5
28,546
5
0
2008-08-22T11:00:27.067000
2009-06-02T09:34:12.080000
22,084
22,112
Controls versus standard HTML
I'm getting into ASP.NET (C# - I know it doesn't matter for this particular question, but full disclosure and all that), and while I love that the asp: -style controls save me a lot of tedious HTML-crafting, I am often frustrated with certain behaviors. I encountered one last night when working with Master Pages: my, when converted into HTML, became. There are other issues--I noticed that when you auto-populate a DataGrid, it adds attributes to the resulting table that I don't necessarily want there. I know that there is a certain amount of "convention over configuration" that you have to accept when you rely on a framework to take over some of your tedious duties, but the "conventions" in these cases aren't so much any established conventions, but rather unnecessary extras. I know why the ID adds the prefix, but I should be able to tweak and turn things like this off, especially since, as a bit of a web standards evangelist, I don't duplicated HTML id's in a single page anyway. So the question here is for those ASP.NET devs more seasoned than I: in your experiences in developing and deploying apps, how do you leverage these controls? Do you find yourself resorting back to hard-coded HTML? Do you use a blend? I don't want to design my HTML around idiosyncratic quirks in these controls, but, if possible, I'd like to leverage them when possible. What's a boy to do?
Personally, I think the standard ASP.NET controls are fine for inhouse stuff - quick and dirty is good in that scenario. But, I once worked with a web developer who was also a designer and he refused to use the ASP.NET controls and only code in HTML and add runat="server" tags when needed. This was more because he wanted to know exactly how his HTML was going to be rendered, and at the time anyway, some of the ASP.NET controls wouldn't render to standards compliance. I sit somewhere in the middle - use HTML where appropriate and not when not. You can sort of best of both worlds with the CSS control Adapters
Controls versus standard HTML I'm getting into ASP.NET (C# - I know it doesn't matter for this particular question, but full disclosure and all that), and while I love that the asp: -style controls save me a lot of tedious HTML-crafting, I am often frustrated with certain behaviors. I encountered one last night when working with Master Pages: my, when converted into HTML, became. There are other issues--I noticed that when you auto-populate a DataGrid, it adds attributes to the resulting table that I don't necessarily want there. I know that there is a certain amount of "convention over configuration" that you have to accept when you rely on a framework to take over some of your tedious duties, but the "conventions" in these cases aren't so much any established conventions, but rather unnecessary extras. I know why the ID adds the prefix, but I should be able to tweak and turn things like this off, especially since, as a bit of a web standards evangelist, I don't duplicated HTML id's in a single page anyway. So the question here is for those ASP.NET devs more seasoned than I: in your experiences in developing and deploying apps, how do you leverage these controls? Do you find yourself resorting back to hard-coded HTML? Do you use a blend? I don't want to design my HTML around idiosyncratic quirks in these controls, but, if possible, I'd like to leverage them when possible. What's a boy to do?
TITLE: Controls versus standard HTML QUESTION: I'm getting into ASP.NET (C# - I know it doesn't matter for this particular question, but full disclosure and all that), and while I love that the asp: -style controls save me a lot of tedious HTML-crafting, I am often frustrated with certain behaviors. I encountered one last night when working with Master Pages: my, when converted into HTML, became. There are other issues--I noticed that when you auto-populate a DataGrid, it adds attributes to the resulting table that I don't necessarily want there. I know that there is a certain amount of "convention over configuration" that you have to accept when you rely on a framework to take over some of your tedious duties, but the "conventions" in these cases aren't so much any established conventions, but rather unnecessary extras. I know why the ID adds the prefix, but I should be able to tweak and turn things like this off, especially since, as a bit of a web standards evangelist, I don't duplicated HTML id's in a single page anyway. So the question here is for those ASP.NET devs more seasoned than I: in your experiences in developing and deploying apps, how do you leverage these controls? Do you find yourself resorting back to hard-coded HTML? Do you use a blend? I don't want to design my HTML around idiosyncratic quirks in these controls, but, if possible, I'd like to leverage them when possible. What's a boy to do? ANSWER: Personally, I think the standard ASP.NET controls are fine for inhouse stuff - quick and dirty is good in that scenario. But, I once worked with a web developer who was also a designer and he refused to use the ASP.NET controls and only code in HTML and add runat="server" tags when needed. This was more because he wanted to know exactly how his HTML was going to be rendered, and at the time anyway, some of the ASP.NET controls wouldn't render to standards compliance. I sit somewhere in the middle - use HTML where appropriate and not when not. You can sort of best of both worlds with the CSS control Adapters
[ "c#", "asp.net", "controls" ]
14
14
4,904
11
0
2008-08-22T11:18:07.510000
2008-08-22T11:34:27.003000
22,106
22,113
Difference between `/dev/ttyS0` and `/dev/ttys0`?
In Linux, what is the difference between /dev/ttyS0 and /dev/ttys0? I know that the first is a serial port, but what about the second, with the small s?
see this For a pseudo terminal pair such as ptyp3 and ttyp3, the pty... is the master or controlling terminal and the tty... is the slave. There are only 16 ttyp's: ttyp0-ttypf (f is a hexadecimal digit). To get more pairs, the 3 letters q, r, s may be used instead of p. For example the pair ttys8, ptys8 is a pseudo terminal pair. The master and slave are really the same "port" but the slave is used by the application program and the master is used by a network program (or the like) which supplies (and gets) data to/from the slave port.
Difference between `/dev/ttyS0` and `/dev/ttys0`? In Linux, what is the difference between /dev/ttyS0 and /dev/ttys0? I know that the first is a serial port, but what about the second, with the small s?
TITLE: Difference between `/dev/ttyS0` and `/dev/ttys0`? QUESTION: In Linux, what is the difference between /dev/ttyS0 and /dev/ttys0? I know that the first is a serial port, but what about the second, with the small s? ANSWER: see this For a pseudo terminal pair such as ptyp3 and ttyp3, the pty... is the master or controlling terminal and the tty... is the slave. There are only 16 ttyp's: ttyp0-ttypf (f is a hexadecimal digit). To get more pairs, the 3 letters q, r, s may be used instead of p. For example the pair ttys8, ptys8 is a pseudo terminal pair. The master and slave are really the same "port" but the slave is used by the application program and the master is used by a network program (or the like) which supplies (and gets) data to/from the slave port.
[ "linux", "serial-port" ]
2
1
6,512
3
0
2008-08-22T11:29:57.123000
2008-08-22T11:35:06.423000
22,115
22,133
Using Regex to generate Strings rather than match them
I am writing a Java utility that helps me to generate loads of data for performance testing. It would be really cool to be able to specify a regex for Strings so that my generator spits out things that match this. Is something out there already baked that I can use to do this? Or is there a library that gets me most of the way there?
Firstly, with a complex enough regexp, I believe this can be impossible. But you should be able to put something together for simple regexps. If you take a look at the source code of the class java.util.regex.Pattern, you'll see that it uses an internal representation of Node instances. Each of the different pattern components have their own implementation of a Node subclass. These Nodes are organised into a tree. By producing a visitor that traverses this tree, you should be able to call an overloaded generator method or some kind of Builder that cobbles something together.
Using Regex to generate Strings rather than match them I am writing a Java utility that helps me to generate loads of data for performance testing. It would be really cool to be able to specify a regex for Strings so that my generator spits out things that match this. Is something out there already baked that I can use to do this? Or is there a library that gets me most of the way there?
TITLE: Using Regex to generate Strings rather than match them QUESTION: I am writing a Java utility that helps me to generate loads of data for performance testing. It would be really cool to be able to specify a regex for Strings so that my generator spits out things that match this. Is something out there already baked that I can use to do this? Or is there a library that gets me most of the way there? ANSWER: Firstly, with a complex enough regexp, I believe this can be impossible. But you should be able to put something together for simple regexps. If you take a look at the source code of the class java.util.regex.Pattern, you'll see that it uses an internal representation of Node instances. Each of the different pattern components have their own implementation of a Node subclass. These Nodes are organised into a tree. By producing a visitor that traverses this tree, you should be able to call an overloaded generator method or some kind of Builder that cobbles something together.
[ "java", "regex" ]
135
57
114,362
12
0
2008-08-22T11:35:41.990000
2008-08-22T11:54:06.270000
22,145
22,170
Calculating a cutting list with the least amount of off cut waste
I am working on a project where I produce an aluminium extrusion cutting list. The aluminium extrusions come in lengths of 5m. I have a list of smaller lengths that need to be cut from the 5m lengths of aluminium extrusions. The smaller lengths need to be cut in the order that produces the least amount of off cut waste from the 5m lengths of aluminium extrusions. Currently I order the cutting list in such a way that generally the longest of the smaller lengths gets cut first and the shortest of smaller lengths gets cut last. The exception to this rule is whenever a shorter length will not fit in what is left of the 5m length of aluminium extrusion, I use the longest shorter length that will fit. This seems to produce a very efficient (very little off cut waste) cutting list and doesn't take long to calculate. I imagine, however, that even though the cutting list is very efficient, it is not necessarily the most efficient. Does anyone know of a way to calculate the most efficient cutting list which can be calculated in a reasonable amount of time? EDIT: Thanks for the answers, I'll continue to use the "greedy" approach as it seems to be doing a very good job (out performs any human attempts to create an efficient cutting list) and is very fast.
This is a classic, difficult problem to solve efficiently. The algorithm you describe sounds like a Greedy Algorithm. Take a look at this Wikipedia article for more information: The Cutting Stock Problem
Calculating a cutting list with the least amount of off cut waste I am working on a project where I produce an aluminium extrusion cutting list. The aluminium extrusions come in lengths of 5m. I have a list of smaller lengths that need to be cut from the 5m lengths of aluminium extrusions. The smaller lengths need to be cut in the order that produces the least amount of off cut waste from the 5m lengths of aluminium extrusions. Currently I order the cutting list in such a way that generally the longest of the smaller lengths gets cut first and the shortest of smaller lengths gets cut last. The exception to this rule is whenever a shorter length will not fit in what is left of the 5m length of aluminium extrusion, I use the longest shorter length that will fit. This seems to produce a very efficient (very little off cut waste) cutting list and doesn't take long to calculate. I imagine, however, that even though the cutting list is very efficient, it is not necessarily the most efficient. Does anyone know of a way to calculate the most efficient cutting list which can be calculated in a reasonable amount of time? EDIT: Thanks for the answers, I'll continue to use the "greedy" approach as it seems to be doing a very good job (out performs any human attempts to create an efficient cutting list) and is very fast.
TITLE: Calculating a cutting list with the least amount of off cut waste QUESTION: I am working on a project where I produce an aluminium extrusion cutting list. The aluminium extrusions come in lengths of 5m. I have a list of smaller lengths that need to be cut from the 5m lengths of aluminium extrusions. The smaller lengths need to be cut in the order that produces the least amount of off cut waste from the 5m lengths of aluminium extrusions. Currently I order the cutting list in such a way that generally the longest of the smaller lengths gets cut first and the shortest of smaller lengths gets cut last. The exception to this rule is whenever a shorter length will not fit in what is left of the 5m length of aluminium extrusion, I use the longest shorter length that will fit. This seems to produce a very efficient (very little off cut waste) cutting list and doesn't take long to calculate. I imagine, however, that even though the cutting list is very efficient, it is not necessarily the most efficient. Does anyone know of a way to calculate the most efficient cutting list which can be calculated in a reasonable amount of time? EDIT: Thanks for the answers, I'll continue to use the "greedy" approach as it seems to be doing a very good job (out performs any human attempts to create an efficient cutting list) and is very fast. ANSWER: This is a classic, difficult problem to solve efficiently. The algorithm you describe sounds like a Greedy Algorithm. Take a look at this Wikipedia article for more information: The Cutting Stock Problem
[ "algorithm" ]
22
17
42,684
8
0
2008-08-22T11:58:56.943000
2008-08-22T12:10:17.823000
22,149
522,827
Unicode vs UTF-8 confusion in Python / Django?
I stumbled over this passage in the Django tutorial: Django models have a default str () method that calls unicode () and converts the result to a UTF-8 bytestring. This means that unicode(p) will return a Unicode string, and str(p) will return a normal string, with characters encoded as UTF-8. Now, I'm confused because afaik Unicode is not any particular representation, so what is a "Unicode string" in Python? Does that mean UCS-2? Googling turned up this "Python Unicode Tutorial" which boldly states Unicode is a two-byte encoding which covers all of the world's common writing systems. which is plain wrong, or is it? I have been confused many times by character set and encoding issues, but here I'm quite sure that the documentation I'm reading is confused. Does anybody know what's going on in Python when it gives me a "Unicode string"?
what is a "Unicode string" in Python? Does that mean UCS-2? Unicode strings in Python are stored internally either as UCS-2 (fixed-length 16-bit representation, almost the same as UTF-16) or UCS-4/UTF-32 (fixed-length 32-bit representation). It's a compile-time option; on Windows it's always UTF-16 whilst many Linux distributions set UTF-32 (‘wide mode’) for their versions of Python. You are generally not supposed to care: you will see Unicode code-points as single elements in your strings and you won't know whether they're stored as two or four bytes. If you're in a UTF-16 build and you need to handle characters outside the Basic Multilingual Plane you'll be Doing It Wrong, but that's still very rare, and users who really need the extra characters should be compiling wide builds. plain wrong, or is it? Yes, it's quite wrong. To be fair I think that tutorial is rather old; it probably pre-dates wide Unicode strings, if not Unicode 3.1 (the version that introduced characters outside the Basic Multilingual Plane). There is an additional source of confusion stemming from Windows's habit of using the term “Unicode” to mean, specifically, the UTF-16LE encoding that NT uses internally. People from Microsoftland may often copy this somewhat misleading habit.
Unicode vs UTF-8 confusion in Python / Django? I stumbled over this passage in the Django tutorial: Django models have a default str () method that calls unicode () and converts the result to a UTF-8 bytestring. This means that unicode(p) will return a Unicode string, and str(p) will return a normal string, with characters encoded as UTF-8. Now, I'm confused because afaik Unicode is not any particular representation, so what is a "Unicode string" in Python? Does that mean UCS-2? Googling turned up this "Python Unicode Tutorial" which boldly states Unicode is a two-byte encoding which covers all of the world's common writing systems. which is plain wrong, or is it? I have been confused many times by character set and encoding issues, but here I'm quite sure that the documentation I'm reading is confused. Does anybody know what's going on in Python when it gives me a "Unicode string"?
TITLE: Unicode vs UTF-8 confusion in Python / Django? QUESTION: I stumbled over this passage in the Django tutorial: Django models have a default str () method that calls unicode () and converts the result to a UTF-8 bytestring. This means that unicode(p) will return a Unicode string, and str(p) will return a normal string, with characters encoded as UTF-8. Now, I'm confused because afaik Unicode is not any particular representation, so what is a "Unicode string" in Python? Does that mean UCS-2? Googling turned up this "Python Unicode Tutorial" which boldly states Unicode is a two-byte encoding which covers all of the world's common writing systems. which is plain wrong, or is it? I have been confused many times by character set and encoding issues, but here I'm quite sure that the documentation I'm reading is confused. Does anybody know what's going on in Python when it gives me a "Unicode string"? ANSWER: what is a "Unicode string" in Python? Does that mean UCS-2? Unicode strings in Python are stored internally either as UCS-2 (fixed-length 16-bit representation, almost the same as UTF-16) or UCS-4/UTF-32 (fixed-length 32-bit representation). It's a compile-time option; on Windows it's always UTF-16 whilst many Linux distributions set UTF-32 (‘wide mode’) for their versions of Python. You are generally not supposed to care: you will see Unicode code-points as single elements in your strings and you won't know whether they're stored as two or four bytes. If you're in a UTF-16 build and you need to handle characters outside the Basic Multilingual Plane you'll be Doing It Wrong, but that's still very rare, and users who really need the extra characters should be compiling wide builds. plain wrong, or is it? Yes, it's quite wrong. To be fair I think that tutorial is rather old; it probably pre-dates wide Unicode strings, if not Unicode 3.1 (the version that introduced characters outside the Basic Multilingual Plane). There is an additional source of confusion stemming from Windows's habit of using the term “Unicode” to mean, specifically, the UTF-16LE encoding that NT uses internally. People from Microsoftland may often copy this somewhat misleading habit.
[ "python", "django", "unicode" ]
34
54
14,394
5
0
2008-08-22T12:01:53.490000
2009-02-07T00:54:09.373000
22,156
22,174
What is the difference between HttpHandler and a Web User Control and when to use each one?
I've been using user controls extensively but never use a HttpHandler and was wondering if I am doing something suboptimal or wrong
Expect a better answer (probably before I finish typing this) but as a quick summary. A user control is something that can be added to a page. A HttpHandler can be used instead of a page.
What is the difference between HttpHandler and a Web User Control and when to use each one? I've been using user controls extensively but never use a HttpHandler and was wondering if I am doing something suboptimal or wrong
TITLE: What is the difference between HttpHandler and a Web User Control and when to use each one? QUESTION: I've been using user controls extensively but never use a HttpHandler and was wondering if I am doing something suboptimal or wrong ANSWER: Expect a better answer (probably before I finish typing this) but as a quick summary. A user control is something that can be added to a page. A HttpHandler can be used instead of a page.
[ "asp.net" ]
1
0
698
5
0
2008-08-22T12:03:36.060000
2008-08-22T12:11:39.333000
22,165
22,220
Transactional Design Pattern
I have a need to create a "transactional" process using an external API that does not support COM+ or.NET transactions (Sharepoint to be exact) What I need to do is to be able to perform a number of processes in a sequence, but any failure in that sequence means that I will have to manually undo all of the previous steps. In my case there are only 2 types of step, both af which are fairly easy to undo/roll back. Does anyony have any suggestions for design patterns or structures that could be usefull for this?
If your changes are done to the SharePoint object model, you can use the fact that changes are not committed until you call the Update() method of the modified object, such as SPList.Update() or SPWeb.Update(). Otherwise, I would use the Command Design Pattern. Chapter 6 in Head First Design Patterns even has an example that implements the undo functionality.
Transactional Design Pattern I have a need to create a "transactional" process using an external API that does not support COM+ or.NET transactions (Sharepoint to be exact) What I need to do is to be able to perform a number of processes in a sequence, but any failure in that sequence means that I will have to manually undo all of the previous steps. In my case there are only 2 types of step, both af which are fairly easy to undo/roll back. Does anyony have any suggestions for design patterns or structures that could be usefull for this?
TITLE: Transactional Design Pattern QUESTION: I have a need to create a "transactional" process using an external API that does not support COM+ or.NET transactions (Sharepoint to be exact) What I need to do is to be able to perform a number of processes in a sequence, but any failure in that sequence means that I will have to manually undo all of the previous steps. In my case there are only 2 types of step, both af which are fairly easy to undo/roll back. Does anyony have any suggestions for design patterns or structures that could be usefull for this? ANSWER: If your changes are done to the SharePoint object model, you can use the fact that changes are not committed until you call the Update() method of the modified object, such as SPList.Update() or SPWeb.Update(). Otherwise, I would use the Command Design Pattern. Chapter 6 in Head First Design Patterns even has an example that implements the undo functionality.
[ "sharepoint", "design-patterns", "transactions" ]
5
3
2,062
6
0
2008-08-22T12:08:40.650000
2008-08-22T12:40:18.250000
22,181
26,103
ADO.NET Mapping From SQLDataReader to Domain Object?
I have a very simple mapping function called "BuildEntity" that does the usual boring "left/right" coding required to dump my reader data into my domain object. (shown below) My question is this - If I don't bring back every column in this mapping as is, I get the "System.IndexOutOfRangeException" exception and wanted to know if ado.net had anything to correct this so I don't need to bring back every column with each call into SQL... What I'm really looking for is something like "IsValidColumn" so I can keep this 1 mapping function throughout my DataAccess class with all the left/right mappings defined - and have it work even when a sproc doesn't return every column listed... Using reader As SqlDataReader = cmd.ExecuteReader() Dim product As Product While reader.Read() product = New Product() product.ID = Convert.ToInt32(reader("ProductID")) product.SupplierID = Convert.ToInt32(reader("SupplierID")) product.CategoryID = Convert.ToInt32(reader("CategoryID")) product.ProductName = Convert.ToString(reader("ProductName")) product.QuantityPerUnit = Convert.ToString(reader("QuantityPerUnit")) product.UnitPrice = Convert.ToDouble(reader("UnitPrice")) product.UnitsInStock = Convert.ToInt32(reader("UnitsInStock")) product.UnitsOnOrder = Convert.ToInt32(reader("UnitsOnOrder")) product.ReorderLevel = Convert.ToInt32(reader("ReorderLevel")) productList.Add(product) End While
Although connection.GetSchema("Tables") does return meta data about the tables in your database, it won't return everything in your sproc if you define any custom columns. For example, if you throw in some random ad-hoc column like *SELECT ProductName,'Testing' As ProductTestName FROM dbo.Products" you won't see 'ProductTestName' as a column because it's not in the Schema of the Products table. To solve this, and ask for every column available in the returned data, leverage a method on the SqlDataReader object "GetSchemaTable()" If I add this to the existing code sample you listed in your original question, you will notice just after the reader is declared I add a data table to capture the meta data from the reader itself. Next I loop through this meta data and add each column to another table that I use in the left-right code to check if each column exists. Updated Source Code Using reader As SqlDataReader = cmd.ExecuteReader() Dim table As DataTable = reader.GetSchemaTable() Dim colNames As New DataTable() For Each row As DataRow In table.Rows colNames.Columns.Add(row.ItemArray(0)) Next Dim product As Product While reader.Read() product = New Product() If Not colNames.Columns("ProductID") Is Nothing Then product.ID = Convert.ToInt32(reader("ProductID")) End If product.SupplierID = Convert.ToInt32(reader("SupplierID")) product.CategoryID = Convert.ToInt32(reader("CategoryID")) product.ProductName = Convert.ToString(reader("ProductName")) product.QuantityPerUnit = Convert.ToString(reader("QuantityPerUnit")) product.UnitPrice = Convert.ToDouble(reader("UnitPrice")) product.UnitsInStock = Convert.ToInt32(reader("UnitsInStock")) product.UnitsOnOrder = Convert.ToInt32(reader("UnitsOnOrder")) product.ReorderLevel = Convert.ToInt32(reader("ReorderLevel")) productList.Add(product) End While This is a hack to be honest, as you should return every column to hydrate your object correctly. But I thought to include this reader method as it would actually grab all the columns, even if they are not defined in your table schema. This approach to mapping your relational data into your domain model might cause some issues when you get into a lazy loading scenario.
ADO.NET Mapping From SQLDataReader to Domain Object? I have a very simple mapping function called "BuildEntity" that does the usual boring "left/right" coding required to dump my reader data into my domain object. (shown below) My question is this - If I don't bring back every column in this mapping as is, I get the "System.IndexOutOfRangeException" exception and wanted to know if ado.net had anything to correct this so I don't need to bring back every column with each call into SQL... What I'm really looking for is something like "IsValidColumn" so I can keep this 1 mapping function throughout my DataAccess class with all the left/right mappings defined - and have it work even when a sproc doesn't return every column listed... Using reader As SqlDataReader = cmd.ExecuteReader() Dim product As Product While reader.Read() product = New Product() product.ID = Convert.ToInt32(reader("ProductID")) product.SupplierID = Convert.ToInt32(reader("SupplierID")) product.CategoryID = Convert.ToInt32(reader("CategoryID")) product.ProductName = Convert.ToString(reader("ProductName")) product.QuantityPerUnit = Convert.ToString(reader("QuantityPerUnit")) product.UnitPrice = Convert.ToDouble(reader("UnitPrice")) product.UnitsInStock = Convert.ToInt32(reader("UnitsInStock")) product.UnitsOnOrder = Convert.ToInt32(reader("UnitsOnOrder")) product.ReorderLevel = Convert.ToInt32(reader("ReorderLevel")) productList.Add(product) End While
TITLE: ADO.NET Mapping From SQLDataReader to Domain Object? QUESTION: I have a very simple mapping function called "BuildEntity" that does the usual boring "left/right" coding required to dump my reader data into my domain object. (shown below) My question is this - If I don't bring back every column in this mapping as is, I get the "System.IndexOutOfRangeException" exception and wanted to know if ado.net had anything to correct this so I don't need to bring back every column with each call into SQL... What I'm really looking for is something like "IsValidColumn" so I can keep this 1 mapping function throughout my DataAccess class with all the left/right mappings defined - and have it work even when a sproc doesn't return every column listed... Using reader As SqlDataReader = cmd.ExecuteReader() Dim product As Product While reader.Read() product = New Product() product.ID = Convert.ToInt32(reader("ProductID")) product.SupplierID = Convert.ToInt32(reader("SupplierID")) product.CategoryID = Convert.ToInt32(reader("CategoryID")) product.ProductName = Convert.ToString(reader("ProductName")) product.QuantityPerUnit = Convert.ToString(reader("QuantityPerUnit")) product.UnitPrice = Convert.ToDouble(reader("UnitPrice")) product.UnitsInStock = Convert.ToInt32(reader("UnitsInStock")) product.UnitsOnOrder = Convert.ToInt32(reader("UnitsOnOrder")) product.ReorderLevel = Convert.ToInt32(reader("ReorderLevel")) productList.Add(product) End While ANSWER: Although connection.GetSchema("Tables") does return meta data about the tables in your database, it won't return everything in your sproc if you define any custom columns. For example, if you throw in some random ad-hoc column like *SELECT ProductName,'Testing' As ProductTestName FROM dbo.Products" you won't see 'ProductTestName' as a column because it's not in the Schema of the Products table. To solve this, and ask for every column available in the returned data, leverage a method on the SqlDataReader object "GetSchemaTable()" If I add this to the existing code sample you listed in your original question, you will notice just after the reader is declared I add a data table to capture the meta data from the reader itself. Next I loop through this meta data and add each column to another table that I use in the left-right code to check if each column exists. Updated Source Code Using reader As SqlDataReader = cmd.ExecuteReader() Dim table As DataTable = reader.GetSchemaTable() Dim colNames As New DataTable() For Each row As DataRow In table.Rows colNames.Columns.Add(row.ItemArray(0)) Next Dim product As Product While reader.Read() product = New Product() If Not colNames.Columns("ProductID") Is Nothing Then product.ID = Convert.ToInt32(reader("ProductID")) End If product.SupplierID = Convert.ToInt32(reader("SupplierID")) product.CategoryID = Convert.ToInt32(reader("CategoryID")) product.ProductName = Convert.ToString(reader("ProductName")) product.QuantityPerUnit = Convert.ToString(reader("QuantityPerUnit")) product.UnitPrice = Convert.ToDouble(reader("UnitPrice")) product.UnitsInStock = Convert.ToInt32(reader("UnitsInStock")) product.UnitsOnOrder = Convert.ToInt32(reader("UnitsOnOrder")) product.ReorderLevel = Convert.ToInt32(reader("ReorderLevel")) productList.Add(product) End While This is a hack to be honest, as you should return every column to hydrate your object correctly. But I thought to include this reader method as it would actually grab all the columns, even if they are not defined in your table schema. This approach to mapping your relational data into your domain model might cause some issues when you get into a lazy loading scenario.
[ "ado.net" ]
3
1
7,573
8
0
2008-08-22T12:14:37.563000
2008-08-25T14:25:40.497000
22,187
22,285
Erlang-style Concurrency for Other Languages
What libraries exist for other programming languages to provide an Erlang-style concurrency model (processes, mailboxes, pattern-matching receive, etc.)? Note: I am specifically interested in things that are intended to be similar to Erlang, not just any threading or queueing library.
Message Passing Interface (MPI) ( http://www-unix.mcs.anl.gov/mpi/ ) is a highly scalable and robust library for parallel programming, geared original towards C but now available in several flavors http://en.wikipedia.org/wiki/Message_Passing_Interface#Implementations. While the library doesn't introduce new syntax, it provides a communication protocol to orchestrate the sharing of data between routines which are parallelizable. Traditionally, it is used in large cluster computing rather than on a single system for concurrency, although multi-core systems can certainly take advantage of this library. Another interesting solution to the problem of parallel programming is OpenMP, which is an attempt to provide a portable extension on various platforms to provide hints to the compiler about what sections of code are easily parallelizable. For example ( http://en.wikipedia.org/wiki/OpenMP#Work-sharing_constructs ): #define N 100000 int main(int argc, char *argv[]) { int i, a[N]; #pragma omp parallel for for (i=0;i There are advantages and disadvantages to both, of course, but the former has proven to be extremely successful in academia and other heavy scientific computing applications. YMMV.
Erlang-style Concurrency for Other Languages What libraries exist for other programming languages to provide an Erlang-style concurrency model (processes, mailboxes, pattern-matching receive, etc.)? Note: I am specifically interested in things that are intended to be similar to Erlang, not just any threading or queueing library.
TITLE: Erlang-style Concurrency for Other Languages QUESTION: What libraries exist for other programming languages to provide an Erlang-style concurrency model (processes, mailboxes, pattern-matching receive, etc.)? Note: I am specifically interested in things that are intended to be similar to Erlang, not just any threading or queueing library. ANSWER: Message Passing Interface (MPI) ( http://www-unix.mcs.anl.gov/mpi/ ) is a highly scalable and robust library for parallel programming, geared original towards C but now available in several flavors http://en.wikipedia.org/wiki/Message_Passing_Interface#Implementations. While the library doesn't introduce new syntax, it provides a communication protocol to orchestrate the sharing of data between routines which are parallelizable. Traditionally, it is used in large cluster computing rather than on a single system for concurrency, although multi-core systems can certainly take advantage of this library. Another interesting solution to the problem of parallel programming is OpenMP, which is an attempt to provide a portable extension on various platforms to provide hints to the compiler about what sections of code are easily parallelizable. For example ( http://en.wikipedia.org/wiki/OpenMP#Work-sharing_constructs ): #define N 100000 int main(int argc, char *argv[]) { int i, a[N]; #pragma omp parallel for for (i=0;i There are advantages and disadvantages to both, of course, but the former has proven to be extremely successful in academia and other heavy scientific computing applications. YMMV.
[ "multithreading", "concurrency", "erlang" ]
21
8
4,306
13
0
2008-08-22T12:19:29.983000
2008-08-22T13:08:51.863000
22,212
27,815
TClientDataSet Aggregates specification aren't added automatically when creating an Aggregate field
I need to create an Aggregate Field in a TClientDataSet, but as said in the docs: Choose OK. The newly defined aggregate field is automatically added to the client dataset and its Aggregates property is automatically updated to include the appropriate aggregate specification. When I add a new aggregate field, the aggregate specification isn't added to the TClientDataSet's Aggregates, therefore I can't use its OnUpdateMethod. I also tried handling the OnChange event of my new Aggregate Field, but it isn't fired at all. Am I doing something wrong? I just want to have an aggregated field and fire an event everything it's value change. Is this broken on delphi? Because what is in the documentation doesn't reflect the actual behavior. edit: @Michal Sznajder I'm using Delphi 2007
I think you may be getting confused between TAggregate and TAggregateField objects, and the Delphi documentation probably isn't helping. AFAICT, TAggregateField objects are automatically 'recalculated' and can be bound to data-aware controls like TDBText, but don't have any OnUpdate event. "TAggregate" objects, on the other hand, do have an OnUpdate event, but can't be bound to data-aware controls. This may be enlightening: http://dn.codegear.com/article/29272
TClientDataSet Aggregates specification aren't added automatically when creating an Aggregate field I need to create an Aggregate Field in a TClientDataSet, but as said in the docs: Choose OK. The newly defined aggregate field is automatically added to the client dataset and its Aggregates property is automatically updated to include the appropriate aggregate specification. When I add a new aggregate field, the aggregate specification isn't added to the TClientDataSet's Aggregates, therefore I can't use its OnUpdateMethod. I also tried handling the OnChange event of my new Aggregate Field, but it isn't fired at all. Am I doing something wrong? I just want to have an aggregated field and fire an event everything it's value change. Is this broken on delphi? Because what is in the documentation doesn't reflect the actual behavior. edit: @Michal Sznajder I'm using Delphi 2007
TITLE: TClientDataSet Aggregates specification aren't added automatically when creating an Aggregate field QUESTION: I need to create an Aggregate Field in a TClientDataSet, but as said in the docs: Choose OK. The newly defined aggregate field is automatically added to the client dataset and its Aggregates property is automatically updated to include the appropriate aggregate specification. When I add a new aggregate field, the aggregate specification isn't added to the TClientDataSet's Aggregates, therefore I can't use its OnUpdateMethod. I also tried handling the OnChange event of my new Aggregate Field, but it isn't fired at all. Am I doing something wrong? I just want to have an aggregated field and fire an event everything it's value change. Is this broken on delphi? Because what is in the documentation doesn't reflect the actual behavior. edit: @Michal Sznajder I'm using Delphi 2007 ANSWER: I think you may be getting confused between TAggregate and TAggregateField objects, and the Delphi documentation probably isn't helping. AFAICT, TAggregateField objects are automatically 'recalculated' and can be bound to data-aware controls like TDBText, but don't have any OnUpdate event. "TAggregate" objects, on the other hand, do have an OnUpdate event, but can't be bound to data-aware controls. This may be enlightening: http://dn.codegear.com/article/29272
[ "delphi" ]
1
4
1,510
2
0
2008-08-22T12:34:44.673000
2008-08-26T11:52:35.960000
22,239
22,262
Why does int main() {} compile?
(I'm using Visual C++ 2008) I've always heard that main() is required to return an integer, but here I didn't put in return 0; and and it compiled with 0 errors and 0 warnings! In the debug window it says the program has exited with code 0. If this function is named anything other than main(), the compiler complains saying 'blah' must return a value. Sticking a return; also causes the error to appear. But leaving it out completely, it compiles just fine. #include using namespace std; int main() { cout << "Hey look I'm supposed to return an int but I'm not gonna!\n"; } Could this be a bug in VC++?
3.6.1 Main function.... 2 An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation-defined. All implementations shall allow both of the following definitions of main: int main() { /*... */ } and int main(int argc, char* argv[]) { /*... */ }.... and it continues to add... 5 A return statement in main has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling exit with the return value as the argument. If control reaches the end of main without encountering a return statement, the effect is that of executing return 0; attempting to find an online copy of the C++ standard so I could quote this passage I found a blog post that quotes all the right bits better than I could.
Why does int main() {} compile? (I'm using Visual C++ 2008) I've always heard that main() is required to return an integer, but here I didn't put in return 0; and and it compiled with 0 errors and 0 warnings! In the debug window it says the program has exited with code 0. If this function is named anything other than main(), the compiler complains saying 'blah' must return a value. Sticking a return; also causes the error to appear. But leaving it out completely, it compiles just fine. #include using namespace std; int main() { cout << "Hey look I'm supposed to return an int but I'm not gonna!\n"; } Could this be a bug in VC++?
TITLE: Why does int main() {} compile? QUESTION: (I'm using Visual C++ 2008) I've always heard that main() is required to return an integer, but here I didn't put in return 0; and and it compiled with 0 errors and 0 warnings! In the debug window it says the program has exited with code 0. If this function is named anything other than main(), the compiler complains saying 'blah' must return a value. Sticking a return; also causes the error to appear. But leaving it out completely, it compiles just fine. #include using namespace std; int main() { cout << "Hey look I'm supposed to return an int but I'm not gonna!\n"; } Could this be a bug in VC++? ANSWER: 3.6.1 Main function.... 2 An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation-defined. All implementations shall allow both of the following definitions of main: int main() { /*... */ } and int main(int argc, char* argv[]) { /*... */ }.... and it continues to add... 5 A return statement in main has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling exit with the return value as the argument. If control reaches the end of main without encountering a return statement, the effect is that of executing return 0; attempting to find an online copy of the C++ standard so I could quote this passage I found a blog post that quotes all the right bits better than I could.
[ "c++", "return-value", "program-entry-point" ]
37
72
10,527
4
0
2008-08-22T12:49:37.213000
2008-08-22T12:54:54.313000
22,245
22,364
How do I change my workspace in Team Foundation Server 2005 and 2008?
I have multiple projects in a couple of different workspaces. However, it seems like I can never figure out how to change my current workspace. The result is that files that I have checked out on my machine are shown to be checked out by somebody else and are not accessible.
I'm going to assume you mean "workspace", not "workstation", as your question doesn't quite make sense to me otherwise. In Visual Studio, go to the Source Control Explorer (View->Other Windows->Source Control Explorer). At the top of the source control explorer window you should have a toolbar with a few buttons. Somewhere on that toolbar (for me it's at the right) there should be a Workspace dropdown. Just select the workspace you want to use from that dropdown.
How do I change my workspace in Team Foundation Server 2005 and 2008? I have multiple projects in a couple of different workspaces. However, it seems like I can never figure out how to change my current workspace. The result is that files that I have checked out on my machine are shown to be checked out by somebody else and are not accessible.
TITLE: How do I change my workspace in Team Foundation Server 2005 and 2008? QUESTION: I have multiple projects in a couple of different workspaces. However, it seems like I can never figure out how to change my current workspace. The result is that files that I have checked out on my machine are shown to be checked out by somebody else and are not accessible. ANSWER: I'm going to assume you mean "workspace", not "workstation", as your question doesn't quite make sense to me otherwise. In Visual Studio, go to the Source Control Explorer (View->Other Windows->Source Control Explorer). At the top of the source control explorer window you should have a toolbar with a few buttons. Somewhere on that toolbar (for me it's at the right) there should be a Workspace dropdown. Just select the workspace you want to use from that dropdown.
[ "tfs", "tfs-2005" ]
25
35
46,347
6
0
2008-08-22T12:51:03.043000
2008-08-22T13:36:08.707000
22,309
28,847
ARMV4i (Windows Mobile 6) Native Code disassembler
Does anyone know of a disassembler for ARMV4i executables and DLLs? I've got a plug-in DLL I'm writing with a very rare data abort (<5% of the time) that I have narrowed down to a specific function (via dumpbin and the address output by the data abort ). However, it is a fairly large function and I would like to narrow it down a little. I know it's happening in a memset() call, but that particular function has about 35 of them, so I was hoping that by looking at the disassembly I could figure out where about the problem actually is.
IDA Pro will definitely do ARM disassembly. And they (Datarescue) once arranged me a licence at about 11PM local time, so I like to recommend them... I see from http://www.datarescue.com/idabase/ that there's been some rearrangement of the company, but I guess it's still a good product. Here's the link to the new publisher: http://www.hex-rays.com/idapro/
ARMV4i (Windows Mobile 6) Native Code disassembler Does anyone know of a disassembler for ARMV4i executables and DLLs? I've got a plug-in DLL I'm writing with a very rare data abort (<5% of the time) that I have narrowed down to a specific function (via dumpbin and the address output by the data abort ). However, it is a fairly large function and I would like to narrow it down a little. I know it's happening in a memset() call, but that particular function has about 35 of them, so I was hoping that by looking at the disassembly I could figure out where about the problem actually is.
TITLE: ARMV4i (Windows Mobile 6) Native Code disassembler QUESTION: Does anyone know of a disassembler for ARMV4i executables and DLLs? I've got a plug-in DLL I'm writing with a very rare data abort (<5% of the time) that I have narrowed down to a specific function (via dumpbin and the address output by the data abort ). However, it is a fairly large function and I would like to narrow it down a little. I know it's happening in a memset() call, but that particular function has about 35 of them, so I was hoping that by looking at the disassembly I could figure out where about the problem actually is. ANSWER: IDA Pro will definitely do ARM disassembly. And they (Datarescue) once arranged me a licence at about 11PM local time, so I like to recommend them... I see from http://www.datarescue.com/idabase/ that there's been some rearrangement of the company, but I guess it's still a good product. Here's the link to the new publisher: http://www.hex-rays.com/idapro/
[ "windows-mobile", "arm", "disassembly" ]
2
3
7,207
4
0
2008-08-22T13:17:48.317000
2008-08-26T18:57:33.580000
22,318
429,683
IE Securty Zone Issues
I'm developing a website which will be used in the corporate intranet which uses JCIFS and NTLM to automatically authenticate the users without asking them to log on. Everything seems to be working in IE 6, but some users are being prompted for their passwords in IE 7. We've had some success by getting the users to change their Logon option to "Automatic logon using current username and password" (Tools > Internet Options > Securty Tab > Select Local Intranet > Custom Level > All the way at the bottom User Authentication > Logon), but we are still having a few users who are getting username/password prompts. Also, we've had some users report they can just click cancel when the prompt comes up and the page will come up correctly. If anyone has any other suggestions, I'd greatly appreciate them.
Turned out that the new security settings on the laptops required NTLMv2 which is not well supported by the JCIFS NLTM library. After some research, found out that JCIFS implementation of NTLM is very hacky (as described by the JCIFS devs) and they're removing support in the next major version of JCIFS. We've moved to using the Tomcat IIS Connector ( http://tomcat.apache.org/connectors-doc/webserver_howto/iis.html ), which works much better. Thanks everyone for your responses.
IE Securty Zone Issues I'm developing a website which will be used in the corporate intranet which uses JCIFS and NTLM to automatically authenticate the users without asking them to log on. Everything seems to be working in IE 6, but some users are being prompted for their passwords in IE 7. We've had some success by getting the users to change their Logon option to "Automatic logon using current username and password" (Tools > Internet Options > Securty Tab > Select Local Intranet > Custom Level > All the way at the bottom User Authentication > Logon), but we are still having a few users who are getting username/password prompts. Also, we've had some users report they can just click cancel when the prompt comes up and the page will come up correctly. If anyone has any other suggestions, I'd greatly appreciate them.
TITLE: IE Securty Zone Issues QUESTION: I'm developing a website which will be used in the corporate intranet which uses JCIFS and NTLM to automatically authenticate the users without asking them to log on. Everything seems to be working in IE 6, but some users are being prompted for their passwords in IE 7. We've had some success by getting the users to change their Logon option to "Automatic logon using current username and password" (Tools > Internet Options > Securty Tab > Select Local Intranet > Custom Level > All the way at the bottom User Authentication > Logon), but we are still having a few users who are getting username/password prompts. Also, we've had some users report they can just click cancel when the prompt comes up and the page will come up correctly. If anyone has any other suggestions, I'd greatly appreciate them. ANSWER: Turned out that the new security settings on the laptops required NTLMv2 which is not well supported by the JCIFS NLTM library. After some research, found out that JCIFS implementation of NTLM is very hacky (as described by the JCIFS devs) and they're removing support in the next major version of JCIFS. We've moved to using the Tomcat IIS Connector ( http://tomcat.apache.org/connectors-doc/webserver_howto/iis.html ), which works much better. Thanks everyone for your responses.
[ "internet-explorer", "ntlm", "intranet", "jcifs", "security-zone" ]
0
0
594
3
0
2008-08-22T13:21:18.807000
2009-01-09T20:49:58.550000
22,319
22,693
How to send out email at a user's local time in .NET / Sql Server?
I am writing a program that needs to send out an email every hour on the hour, but at a time local to the user. Say I have 2 users in different time zones. John is in New York and Fred is in Los Angeles. The server is in Chicago. If I want to send an email at 6 PM local to each user, I'd have to send the email to John at 7 PM Server time and Fred at 4 PM Server time. What's a good approach to this in.NET / Sql Server? I have found an xml file with all of the time zone information, so I am considering writing a script to import it into the database, then querying off of it. Edit: I used “t4znet.dll” and did all comparisons on the.NET side.
You have two options: Store the adjusted time for the mail action into the database for each user. Then just compare server time with stored time. To avoid confusion and portability issues, I would store all times in UTC. So, send mail when SERVER_UTC_TIME() == storedUtcTime. Store the local time for each mail action into the database, then convert on-the-fly. Send mail when SERVER_UTC_TIME() == TO_UTC_TIME(storedLocalTime, userTimeZone). You should decide what makes most sense for your application. For example if the mailing time is always the same for all users, it makes more sense to go with option (2). If the events times can change between users and even per user, it may make development and debugging easier if you choose option (1). Either way you will need to know the user's time zone. *These function calls are obviously pseudo, since I don't know their invocations in T-SQL, but they should exist.
How to send out email at a user's local time in .NET / Sql Server? I am writing a program that needs to send out an email every hour on the hour, but at a time local to the user. Say I have 2 users in different time zones. John is in New York and Fred is in Los Angeles. The server is in Chicago. If I want to send an email at 6 PM local to each user, I'd have to send the email to John at 7 PM Server time and Fred at 4 PM Server time. What's a good approach to this in.NET / Sql Server? I have found an xml file with all of the time zone information, so I am considering writing a script to import it into the database, then querying off of it. Edit: I used “t4znet.dll” and did all comparisons on the.NET side.
TITLE: How to send out email at a user's local time in .NET / Sql Server? QUESTION: I am writing a program that needs to send out an email every hour on the hour, but at a time local to the user. Say I have 2 users in different time zones. John is in New York and Fred is in Los Angeles. The server is in Chicago. If I want to send an email at 6 PM local to each user, I'd have to send the email to John at 7 PM Server time and Fred at 4 PM Server time. What's a good approach to this in.NET / Sql Server? I have found an xml file with all of the time zone information, so I am considering writing a script to import it into the database, then querying off of it. Edit: I used “t4znet.dll” and did all comparisons on the.NET side. ANSWER: You have two options: Store the adjusted time for the mail action into the database for each user. Then just compare server time with stored time. To avoid confusion and portability issues, I would store all times in UTC. So, send mail when SERVER_UTC_TIME() == storedUtcTime. Store the local time for each mail action into the database, then convert on-the-fly. Send mail when SERVER_UTC_TIME() == TO_UTC_TIME(storedLocalTime, userTimeZone). You should decide what makes most sense for your application. For example if the mailing time is always the same for all users, it makes more sense to go with option (2). If the events times can change between users and even per user, it may make development and debugging easier if you choose option (1). Either way you will need to know the user's time zone. *These function calls are obviously pseudo, since I don't know their invocations in T-SQL, but they should exist.
[ "sql", ".net", "sql-server", "timezone" ]
3
0
967
3
0
2008-08-22T13:22:31.050000
2008-08-22T15:44:23.033000
22,321
160,441
Remoting server auto-discovery. Broadcast or not?
I have a client/server application that communicates with.Net remoting. I need my clients to be able to find the server(s) on the network without requiring client-side configuration. As far as I know, there is no support for discovery in remoting. I am prepared to implement a UDP solution where the clients will be able to find the servers via broadcast messages. I want to hear the collective SO wisdom before I go ahead. Is this the best way? Any other suggestions?
I've looked at both SSDP and UPnP for this type of functionality, but I'd recommend going with a custom UDP multicast solution. Basically, multicast is very similar to a broadcast, but only machines that have joined the multicast group (i.e. requested the broadcast) are contacted. IMHO, SSDP and UPnP and bloated and overly complicated for resource discovery... but hey, it's a standard.;)
Remoting server auto-discovery. Broadcast or not? I have a client/server application that communicates with.Net remoting. I need my clients to be able to find the server(s) on the network without requiring client-side configuration. As far as I know, there is no support for discovery in remoting. I am prepared to implement a UDP solution where the clients will be able to find the servers via broadcast messages. I want to hear the collective SO wisdom before I go ahead. Is this the best way? Any other suggestions?
TITLE: Remoting server auto-discovery. Broadcast or not? QUESTION: I have a client/server application that communicates with.Net remoting. I need my clients to be able to find the server(s) on the network without requiring client-side configuration. As far as I know, there is no support for discovery in remoting. I am prepared to implement a UDP solution where the clients will be able to find the servers via broadcast messages. I want to hear the collective SO wisdom before I go ahead. Is this the best way? Any other suggestions? ANSWER: I've looked at both SSDP and UPnP for this type of functionality, but I'd recommend going with a custom UDP multicast solution. Basically, multicast is very similar to a broadcast, but only machines that have joined the multicast group (i.e. requested the broadcast) are contacted. IMHO, SSDP and UPnP and bloated and overly complicated for resource discovery... but hey, it's a standard.;)
[ ".net", "networking", "remoting", "udp", "broadcast" ]
4
4
4,077
5
0
2008-08-22T13:22:38.867000
2008-10-02T01:01:22.280000
22,322
479,664
How to late bind 32bit/64 bit libs at runtime
I've got a problem similar to,but subtly different from, that described here (Loading assemblies and their dependencies). I have a C++ DLL for 3D rendering that is what we sell to customers. For.NET users we will have a CLR wrapper around it. The C++ DLL can be built in both 32 and 64bit versions, but I think this means we need to have two CLR wrappers since the CLR binds to a specific DLL? Say now our customer has a.NET app that can be either 32 or 64bit, and that it being a pure.NET app it leaves the CLR to work it out from a single set of assemblies. The question is how can the app code dynamically choose between our 32 and 64bit CLR/DLL combinations at run-time? Even more specifically, is the suggested answer to the aforementioned question applicable here too (i.e. create a ResolveEvent handler)?
I finally have an answer for this that appears to work. Compile both 32 & 64 bit versions - both managed & unmanaged - into separate folders. Then have the.NET app choose at run time which directory to load the assemblies from. The problem with using the ResolveEvent is that it only gets called if assemblies aren't found, so it is all to easy to accidentally end up with 32 bit versions. Instead use a second AppDomain object where we can change the ApplicationBase property to point at the right folder. So you end up with code like: static void Main(String[] argv) { // Create a new AppDomain, but with the base directory set to either the 32-bit or 64-bit // sub-directories. AppDomainSetup objADS = new AppDomainSetup(); System.String assemblyDir = System.IO.Path.GetDirectoryName(Application.ExecutablePath); switch (System.IntPtr.Size) { case (4): assemblyDir += "\\win32\\"; break; case (8): assemblyDir += "\\x64\\"; break; } objADS.ApplicationBase = assemblyDir; // We set the PrivateBinPath to the application directory, so that we can still // load the platform neutral assemblies from the app directory. objADS.PrivateBinPath = System.IO.Path.GetDirectoryName(Application.ExecutablePath); AppDomain objAD = AppDomain.CreateDomain("", null, objADS); if (argv.Length > 0) objAD.ExecuteAssembly(argv[0]); else objAD.ExecuteAssembly("MyApplication.exe"); AppDomain.Unload(objAD); } You end up with 2 exes - your normal app and a second switching app that chooses which bits to load. Note - I can't take credit for the details of this myself. One of my colleagues sussed that out given my initial pointer. If and when he signs up to StackOverflow I'll assign the answer to him
How to late bind 32bit/64 bit libs at runtime I've got a problem similar to,but subtly different from, that described here (Loading assemblies and their dependencies). I have a C++ DLL for 3D rendering that is what we sell to customers. For.NET users we will have a CLR wrapper around it. The C++ DLL can be built in both 32 and 64bit versions, but I think this means we need to have two CLR wrappers since the CLR binds to a specific DLL? Say now our customer has a.NET app that can be either 32 or 64bit, and that it being a pure.NET app it leaves the CLR to work it out from a single set of assemblies. The question is how can the app code dynamically choose between our 32 and 64bit CLR/DLL combinations at run-time? Even more specifically, is the suggested answer to the aforementioned question applicable here too (i.e. create a ResolveEvent handler)?
TITLE: How to late bind 32bit/64 bit libs at runtime QUESTION: I've got a problem similar to,but subtly different from, that described here (Loading assemblies and their dependencies). I have a C++ DLL for 3D rendering that is what we sell to customers. For.NET users we will have a CLR wrapper around it. The C++ DLL can be built in both 32 and 64bit versions, but I think this means we need to have two CLR wrappers since the CLR binds to a specific DLL? Say now our customer has a.NET app that can be either 32 or 64bit, and that it being a pure.NET app it leaves the CLR to work it out from a single set of assemblies. The question is how can the app code dynamically choose between our 32 and 64bit CLR/DLL combinations at run-time? Even more specifically, is the suggested answer to the aforementioned question applicable here too (i.e. create a ResolveEvent handler)? ANSWER: I finally have an answer for this that appears to work. Compile both 32 & 64 bit versions - both managed & unmanaged - into separate folders. Then have the.NET app choose at run time which directory to load the assemblies from. The problem with using the ResolveEvent is that it only gets called if assemblies aren't found, so it is all to easy to accidentally end up with 32 bit versions. Instead use a second AppDomain object where we can change the ApplicationBase property to point at the right folder. So you end up with code like: static void Main(String[] argv) { // Create a new AppDomain, but with the base directory set to either the 32-bit or 64-bit // sub-directories. AppDomainSetup objADS = new AppDomainSetup(); System.String assemblyDir = System.IO.Path.GetDirectoryName(Application.ExecutablePath); switch (System.IntPtr.Size) { case (4): assemblyDir += "\\win32\\"; break; case (8): assemblyDir += "\\x64\\"; break; } objADS.ApplicationBase = assemblyDir; // We set the PrivateBinPath to the application directory, so that we can still // load the platform neutral assemblies from the app directory. objADS.PrivateBinPath = System.IO.Path.GetDirectoryName(Application.ExecutablePath); AppDomain objAD = AppDomain.CreateDomain("", null, objADS); if (argv.Length > 0) objAD.ExecuteAssembly(argv[0]); else objAD.ExecuteAssembly("MyApplication.exe"); AppDomain.Unload(objAD); } You end up with 2 exes - your normal app and a second switching app that chooses which bits to load. Note - I can't take credit for the details of this myself. One of my colleagues sussed that out given my initial pointer. If and when he signs up to StackOverflow I'll assign the answer to him
[ "c#", ".net", "64-bit", "clr", "x86-64" ]
18
9
4,339
3
0
2008-08-22T13:23:15.773000
2009-01-26T12:42:19.303000
22,326
27,425
Word Automation: Write RTF text without going through clipboard
I am trying to replace the current selection in Word (2003/2007) by some RTF string stored in a variable. Here is the current code: Clipboard.SetText(strRTFString, TextDataFormat.Rtf) oWord.ActiveDocument.ActiveWindow.Selection.PasteAndFormat(0) Is there any way to do the same thing without going through the clipboard. Or is there any way to push the clipboard data to a safe place and restore it after?
Put the RTF in a file instead of the clipboard, then insert from the file, e.g. Selection.InsertFile FileName:="myfile.rtf", Range:="", _ ConfirmConversions:=False, Link:=False, Attachment:=False
Word Automation: Write RTF text without going through clipboard I am trying to replace the current selection in Word (2003/2007) by some RTF string stored in a variable. Here is the current code: Clipboard.SetText(strRTFString, TextDataFormat.Rtf) oWord.ActiveDocument.ActiveWindow.Selection.PasteAndFormat(0) Is there any way to do the same thing without going through the clipboard. Or is there any way to push the clipboard data to a safe place and restore it after?
TITLE: Word Automation: Write RTF text without going through clipboard QUESTION: I am trying to replace the current selection in Word (2003/2007) by some RTF string stored in a variable. Here is the current code: Clipboard.SetText(strRTFString, TextDataFormat.Rtf) oWord.ActiveDocument.ActiveWindow.Selection.PasteAndFormat(0) Is there any way to do the same thing without going through the clipboard. Or is there any way to push the clipboard data to a safe place and restore it after? ANSWER: Put the RTF in a file instead of the clipboard, then insert from the file, e.g. Selection.InsertFile FileName:="myfile.rtf", Range:="", _ ConfirmConversions:=False, Link:=False, Attachment:=False
[ "vba", "automation", "ms-word" ]
11
14
7,002
2
0
2008-08-22T13:24:24.697000
2008-08-26T04:54:01.520000
22,340
204,036
WCF push to client through firewall?
See also How does a WCF server inform a WCF client about changes? (Better solution then simple polling, e.g. Coment or long polling) I need to use push-technology with WCF through client firewalls. This must be a common problem, and I know for a fact it works in theory (see links below), but I have failed to get it working, and I haven't been able to find a code sample that demonstrates it. Requirements: WCF Clients connects to server through tcp port 80 (netTcpBinding). Server pushes back information at irregular intervals (1 min to several hours). Users should not have to configure their firewalls, server pushes must pass through firewalls that have all inbound ports closed. TCP duplex on the same connection is needed for this, a dual binding does not work since a port has to be opened on the client firewall. Clients sends heartbeats to server at regular intervals (perhaps every 15 mins) so server knows client is still alive. Server is IIS7 with WAS. The solution seems to be duplex netTcpBinding. Based on this information: WCF through firewalls and NATs Keeping connections open in IIS But I have yet to find a code sample that works.. I've tried combining the "Duplex" and "TcpActivation" samples from Microsoft's WCF Samples without any luck. Please can someone point me to example code that works, or build a small sample app. Thanks a lot!
I've found a couple of solutions: ZeroC Ice GPL with a commercial option. Have only tested quickly. Looks more powerful than.NET Remoting and is very actively developed. RemObjects Commercial, active development, supports everything but does not seem to have all the more advanced features that GenuineChannels use. GenuineChannels. It uses remoting with a lot of nice added features, the most important one being it works through NATs without the need to open the client firewall. Unfortunately seems to be very dead. Another solution is to use streaming with IIS, according to this article: Keeping connections open in IIS The client makes the first connection (http with IIS6, tcp with IIS7) to the server at port 80, the connection is then kept open with a streaming response that never ends. I haven't had the time to experiment with this, and I haven't found a sample that says it specifically solves the firewall-problem, but here's an excellent sample that probably works: Streaming XML.
WCF push to client through firewall? See also How does a WCF server inform a WCF client about changes? (Better solution then simple polling, e.g. Coment or long polling) I need to use push-technology with WCF through client firewalls. This must be a common problem, and I know for a fact it works in theory (see links below), but I have failed to get it working, and I haven't been able to find a code sample that demonstrates it. Requirements: WCF Clients connects to server through tcp port 80 (netTcpBinding). Server pushes back information at irregular intervals (1 min to several hours). Users should not have to configure their firewalls, server pushes must pass through firewalls that have all inbound ports closed. TCP duplex on the same connection is needed for this, a dual binding does not work since a port has to be opened on the client firewall. Clients sends heartbeats to server at regular intervals (perhaps every 15 mins) so server knows client is still alive. Server is IIS7 with WAS. The solution seems to be duplex netTcpBinding. Based on this information: WCF through firewalls and NATs Keeping connections open in IIS But I have yet to find a code sample that works.. I've tried combining the "Duplex" and "TcpActivation" samples from Microsoft's WCF Samples without any luck. Please can someone point me to example code that works, or build a small sample app. Thanks a lot!
TITLE: WCF push to client through firewall? QUESTION: See also How does a WCF server inform a WCF client about changes? (Better solution then simple polling, e.g. Coment or long polling) I need to use push-technology with WCF through client firewalls. This must be a common problem, and I know for a fact it works in theory (see links below), but I have failed to get it working, and I haven't been able to find a code sample that demonstrates it. Requirements: WCF Clients connects to server through tcp port 80 (netTcpBinding). Server pushes back information at irregular intervals (1 min to several hours). Users should not have to configure their firewalls, server pushes must pass through firewalls that have all inbound ports closed. TCP duplex on the same connection is needed for this, a dual binding does not work since a port has to be opened on the client firewall. Clients sends heartbeats to server at regular intervals (perhaps every 15 mins) so server knows client is still alive. Server is IIS7 with WAS. The solution seems to be duplex netTcpBinding. Based on this information: WCF through firewalls and NATs Keeping connections open in IIS But I have yet to find a code sample that works.. I've tried combining the "Duplex" and "TcpActivation" samples from Microsoft's WCF Samples without any luck. Please can someone point me to example code that works, or build a small sample app. Thanks a lot! ANSWER: I've found a couple of solutions: ZeroC Ice GPL with a commercial option. Have only tested quickly. Looks more powerful than.NET Remoting and is very actively developed. RemObjects Commercial, active development, supports everything but does not seem to have all the more advanced features that GenuineChannels use. GenuineChannels. It uses remoting with a lot of nice added features, the most important one being it works through NATs without the need to open the client firewall. Unfortunately seems to be very dead. Another solution is to use streaming with IIS, according to this article: Keeping connections open in IIS The client makes the first connection (http with IIS6, tcp with IIS7) to the server at port 80, the connection is then kept open with a streaming response that never ends. I haven't had the time to experiment with this, and I haven't found a sample that says it specifically solves the firewall-problem, but here's an excellent sample that probably works: Streaming XML.
[ ".net", "wcf", "firewall", "push", "duplex" ]
9
5
11,831
6
0
2008-08-22T13:27:53.937000
2008-10-15T08:32:34.547000
22,356
22,397
Cleanest Way to Invoke Cross-Thread Events
I find that the.NET event model is such that I'll often be raising an event on one thread and listening for it on another thread. I was wondering what the cleanest way to marshal an event from a background thread onto my UI thread is. Based on the community suggestions, I've used this: // earlier in the code mCoolObject.CoolEvent+= new CoolObjectEventHandler(mCoolObject_CoolEvent); // then private void mCoolObject_CoolEvent(object sender, CoolObjectEventArgs args) { if (InvokeRequired) { CoolObjectEventHandler cb = new CoolObjectEventHandler( mCoolObject_CoolEvent); Invoke(cb, new object[] { sender, args }); return; } // do the dirty work of my method here }
A couple of observations: Don't create simple delegates explicitly in code like that unless you're pre-2.0 so you could use: BeginInvoke(new EventHandler (mCoolObject_CoolEvent), sender, args); Also you don't need to create and populate the object array because the args parameter is a "params" type so you can just pass in the list. I would probably favor Invoke over BeginInvoke as the latter will result in the code being called asynchronously which may or may not be what you're after but would make handling subsequent exceptions difficult to propagate without a call to EndInvoke. What would happen is that your app will end up getting a TargetInvocationException instead.
Cleanest Way to Invoke Cross-Thread Events I find that the.NET event model is such that I'll often be raising an event on one thread and listening for it on another thread. I was wondering what the cleanest way to marshal an event from a background thread onto my UI thread is. Based on the community suggestions, I've used this: // earlier in the code mCoolObject.CoolEvent+= new CoolObjectEventHandler(mCoolObject_CoolEvent); // then private void mCoolObject_CoolEvent(object sender, CoolObjectEventArgs args) { if (InvokeRequired) { CoolObjectEventHandler cb = new CoolObjectEventHandler( mCoolObject_CoolEvent); Invoke(cb, new object[] { sender, args }); return; } // do the dirty work of my method here }
TITLE: Cleanest Way to Invoke Cross-Thread Events QUESTION: I find that the.NET event model is such that I'll often be raising an event on one thread and listening for it on another thread. I was wondering what the cleanest way to marshal an event from a background thread onto my UI thread is. Based on the community suggestions, I've used this: // earlier in the code mCoolObject.CoolEvent+= new CoolObjectEventHandler(mCoolObject_CoolEvent); // then private void mCoolObject_CoolEvent(object sender, CoolObjectEventArgs args) { if (InvokeRequired) { CoolObjectEventHandler cb = new CoolObjectEventHandler( mCoolObject_CoolEvent); Invoke(cb, new object[] { sender, args }); return; } // do the dirty work of my method here } ANSWER: A couple of observations: Don't create simple delegates explicitly in code like that unless you're pre-2.0 so you could use: BeginInvoke(new EventHandler (mCoolObject_CoolEvent), sender, args); Also you don't need to create and populate the object array because the args parameter is a "params" type so you can just pass in the list. I would probably favor Invoke over BeginInvoke as the latter will result in the code being called asynchronously which may or may not be what you're after but would make handling subsequent exceptions difficult to propagate without a call to EndInvoke. What would happen is that your app will end up getting a TargetInvocationException instead.
[ "c#", "multithreading", "events" ]
82
29
124,870
10
0
2008-08-22T13:34:02.583000
2008-08-22T13:45:40.993000
22,379
22,399
Implementing a log watcher
I'm wondering how you can implement a program similar to tail -f in C/C++, a program that watches for and processes new lines added to a log file?
You can use fseek() to clear the eof condition on the stream. Essentially, read to the end of the file, sleep for a while, fseek() (without changing your position) to clear eof, the read to end of file again. wash, rinse, repeat. man fseek(3) for details. Here's what it looks like in perl. perl's seek() is essentially a wrapper for fseek(3), so the logic is the same: wembley 0 /home/jj33/swap >#> cat p my $f = shift; open(I, "<$f") || die "Couldn't open $f: $!\n"; while (1) { seek(I, 0, 1); while (defined(my $l = )) { print "Got: $l"; } print "Hit EOF, sleeping\n"; sleep(10); } wembley 0 /home/jj33/swap >#> cat tfile This is some text in a file wembley 0 /home/jj33/swap >#> perl p tfile Got: This is Got: some Got: text Got: in Got: a file Hit EOF, sleeping Then, in another session: wembley 0 /home/jj33/swap > echo "another line of text" >> tfile And back to the original program output: Hit EOF, sleeping Got: another line of text Hit EOF, sleeping
Implementing a log watcher I'm wondering how you can implement a program similar to tail -f in C/C++, a program that watches for and processes new lines added to a log file?
TITLE: Implementing a log watcher QUESTION: I'm wondering how you can implement a program similar to tail -f in C/C++, a program that watches for and processes new lines added to a log file? ANSWER: You can use fseek() to clear the eof condition on the stream. Essentially, read to the end of the file, sleep for a while, fseek() (without changing your position) to clear eof, the read to end of file again. wash, rinse, repeat. man fseek(3) for details. Here's what it looks like in perl. perl's seek() is essentially a wrapper for fseek(3), so the logic is the same: wembley 0 /home/jj33/swap >#> cat p my $f = shift; open(I, "<$f") || die "Couldn't open $f: $!\n"; while (1) { seek(I, 0, 1); while (defined(my $l = )) { print "Got: $l"; } print "Hit EOF, sleeping\n"; sleep(10); } wembley 0 /home/jj33/swap >#> cat tfile This is some text in a file wembley 0 /home/jj33/swap >#> perl p tfile Got: This is Got: some Got: text Got: in Got: a file Hit EOF, sleeping Then, in another session: wembley 0 /home/jj33/swap > echo "another line of text" >> tfile And back to the original program output: Hit EOF, sleeping Got: another line of text Hit EOF, sleeping
[ "c++", "c", "file", "io" ]
3
5
970
4
0
2008-08-22T13:40:32.597000
2008-08-22T13:46:16.093000
22,401
22,407
Does PHP have built-in data structures?
I'm looking at the PHP Manual, and I'm not seeing a section on data structures that most languages have, such as lists and sets. Am I just blind or does PHP not have anything like this built in?
The only native data structure in PHP is array. Fortunately, arrays are quite flexible and can be used as hash tables as well. http://www.php.net/array However, there is SPL which is sort of a clone of C++ STL. http://www.php.net/manual/en/book.spl.php
Does PHP have built-in data structures? I'm looking at the PHP Manual, and I'm not seeing a section on data structures that most languages have, such as lists and sets. Am I just blind or does PHP not have anything like this built in?
TITLE: Does PHP have built-in data structures? QUESTION: I'm looking at the PHP Manual, and I'm not seeing a section on data structures that most languages have, such as lists and sets. Am I just blind or does PHP not have anything like this built in? ANSWER: The only native data structure in PHP is array. Fortunately, arrays are quite flexible and can be used as hash tables as well. http://www.php.net/array However, there is SPL which is sort of a clone of C++ STL. http://www.php.net/manual/en/book.spl.php
[ "php", "data-structures" ]
69
62
63,596
10
0
2008-08-22T13:47:43.297000
2008-08-22T13:51:02.447000
22,409
848,533
How do I convert images between CMYK and RGB in ColdFusion (Java)?
I have a need to convert images from CMYK to RGB - not necessarily back again, but hey, if it can be done... With the release of ColdFusion 8, we got the CFImage tag, but it doesn't support this conversion; and nor does Image.cfc, or Alagad's Image Component. However, it should be possible in Java; which we can leverage through CF. For example, here's how you might create a Java thread to sleep a process: I would guess a similar method could be used to leverage java to do this image conversion, but not being a Java developer, I don't have a clue where to start. Can anyone lend a hand here?
I use the Java ImageIO libraries ( https://jai-imageio.dev.java.net ). They aren't perfect, but can be simple and get the job done. As far as converting from CMYK to RGB, here is the best I have been able to come up with. Download and install the ImageIO JARs and native libraries for your platform. The native libraries are essential. Without them the ImageIO JAR files will not be able to detect the CMYK images. Originally, I was under the impression that the native libraries would improve performance but was not required for any functionality. I was wrong. The only other thing that I noticed is that the converted RGB images are sometimes much lighter than the CMYK images. If anyone knows how to solve that problem, I would be appreciative. Below is some code to convert a CMYK image into an RGB image of any supported format. Thank you, Randy Stegbauer package cmyk; import java.awt.color.ColorSpace; import java.awt.image.BufferedImage; import java.awt.image.ColorConvertOp; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import org.apache.commons.lang.StringUtils; public class Main { /** * Creates new RGB images from all the CMYK images passed * in on the command line. * The new filename generated is, for example "GIF_original_filename.gif". * */ public static void main(String[] args) { for (int ii = 0; ii < args.length; ii++) { String filename = args[ii]; boolean cmyk = isCMYK(filename); System.out.println(cmyk + ": " + filename); if (cmyk) { try { String rgbFile = cmyk2rgb(filename); System.out.println(isCMYK(rgbFile) + ": " + rgbFile); } catch (IOException e) { System.out.println(e.getMessage()); } } } } /** * If 'filename' is a CMYK file, then convert the image into RGB, * store it into a JPEG file, and return the new filename. * * @param filename */ private static String cmyk2rgb(String filename) throws IOException { // Change this format into any ImageIO supported format. String format = "gif"; File imageFile = new File(filename); String rgbFilename = filename; BufferedImage image = ImageIO.read(imageFile); if (image!= null) { int colorSpaceType = image.getColorModel().getColorSpace().getType(); if (colorSpaceType == ColorSpace.TYPE_CMYK) { BufferedImage rgbImage = new BufferedImage( image.getWidth(), image.getHeight(), BufferedImage.TYPE_3BYTE_BGR); ColorConvertOp op = new ColorConvertOp(null); op.filter(image, rgbImage); rgbFilename = changeExtension(imageFile.getName(), format); rgbFilename = new File(imageFile.getParent(), format + "_" + rgbFilename).getPath(); ImageIO.write(rgbImage, format, new File(rgbFilename)); } } return rgbFilename; } /** * Change the extension of 'filename' to 'newExtension'. * * @param filename * @param newExtension * @return filename with new extension */ private static String changeExtension(String filename, String newExtension) { String result = filename; if (filename!= null && newExtension!= null && newExtension.length()!= 0); { int dot = filename.lastIndexOf('.'); if (dot!= -1) { result = filename.substring(0, dot) + '.' + newExtension; } } return result; } private static boolean isCMYK(String filename) { boolean result = false; BufferedImage img = null; try { img = ImageIO.read(new File(filename)); } catch (IOException e) { System.out.println(e.getMessage() + ": " + filename); } if (img!= null) { int colorSpaceType = img.getColorModel().getColorSpace().getType(); result = colorSpaceType == ColorSpace.TYPE_CMYK; } return result; } }
How do I convert images between CMYK and RGB in ColdFusion (Java)? I have a need to convert images from CMYK to RGB - not necessarily back again, but hey, if it can be done... With the release of ColdFusion 8, we got the CFImage tag, but it doesn't support this conversion; and nor does Image.cfc, or Alagad's Image Component. However, it should be possible in Java; which we can leverage through CF. For example, here's how you might create a Java thread to sleep a process: I would guess a similar method could be used to leverage java to do this image conversion, but not being a Java developer, I don't have a clue where to start. Can anyone lend a hand here?
TITLE: How do I convert images between CMYK and RGB in ColdFusion (Java)? QUESTION: I have a need to convert images from CMYK to RGB - not necessarily back again, but hey, if it can be done... With the release of ColdFusion 8, we got the CFImage tag, but it doesn't support this conversion; and nor does Image.cfc, or Alagad's Image Component. However, it should be possible in Java; which we can leverage through CF. For example, here's how you might create a Java thread to sleep a process: I would guess a similar method could be used to leverage java to do this image conversion, but not being a Java developer, I don't have a clue where to start. Can anyone lend a hand here? ANSWER: I use the Java ImageIO libraries ( https://jai-imageio.dev.java.net ). They aren't perfect, but can be simple and get the job done. As far as converting from CMYK to RGB, here is the best I have been able to come up with. Download and install the ImageIO JARs and native libraries for your platform. The native libraries are essential. Without them the ImageIO JAR files will not be able to detect the CMYK images. Originally, I was under the impression that the native libraries would improve performance but was not required for any functionality. I was wrong. The only other thing that I noticed is that the converted RGB images are sometimes much lighter than the CMYK images. If anyone knows how to solve that problem, I would be appreciative. Below is some code to convert a CMYK image into an RGB image of any supported format. Thank you, Randy Stegbauer package cmyk; import java.awt.color.ColorSpace; import java.awt.image.BufferedImage; import java.awt.image.ColorConvertOp; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import org.apache.commons.lang.StringUtils; public class Main { /** * Creates new RGB images from all the CMYK images passed * in on the command line. * The new filename generated is, for example "GIF_original_filename.gif". * */ public static void main(String[] args) { for (int ii = 0; ii < args.length; ii++) { String filename = args[ii]; boolean cmyk = isCMYK(filename); System.out.println(cmyk + ": " + filename); if (cmyk) { try { String rgbFile = cmyk2rgb(filename); System.out.println(isCMYK(rgbFile) + ": " + rgbFile); } catch (IOException e) { System.out.println(e.getMessage()); } } } } /** * If 'filename' is a CMYK file, then convert the image into RGB, * store it into a JPEG file, and return the new filename. * * @param filename */ private static String cmyk2rgb(String filename) throws IOException { // Change this format into any ImageIO supported format. String format = "gif"; File imageFile = new File(filename); String rgbFilename = filename; BufferedImage image = ImageIO.read(imageFile); if (image!= null) { int colorSpaceType = image.getColorModel().getColorSpace().getType(); if (colorSpaceType == ColorSpace.TYPE_CMYK) { BufferedImage rgbImage = new BufferedImage( image.getWidth(), image.getHeight(), BufferedImage.TYPE_3BYTE_BGR); ColorConvertOp op = new ColorConvertOp(null); op.filter(image, rgbImage); rgbFilename = changeExtension(imageFile.getName(), format); rgbFilename = new File(imageFile.getParent(), format + "_" + rgbFilename).getPath(); ImageIO.write(rgbImage, format, new File(rgbFilename)); } } return rgbFilename; } /** * Change the extension of 'filename' to 'newExtension'. * * @param filename * @param newExtension * @return filename with new extension */ private static String changeExtension(String filename, String newExtension) { String result = filename; if (filename!= null && newExtension!= null && newExtension.length()!= 0); { int dot = filename.lastIndexOf('.'); if (dot!= -1) { result = filename.substring(0, dot) + '.' + newExtension; } } return result; } private static boolean isCMYK(String filename) { boolean result = false; BufferedImage img = null; try { img = ImageIO.read(new File(filename)); } catch (IOException e) { System.out.println(e.getMessage() + ": " + filename); } if (img!= null) { int colorSpaceType = img.getColorModel().getColorSpace().getType(); result = colorSpaceType == ColorSpace.TYPE_CMYK; } return result; } }
[ "java", "image", "coldfusion" ]
8
6
12,764
4
0
2008-08-22T13:51:39.263000
2009-05-11T15:01:05.827000
22,417
22,448
SQL Query Help - Scoring Multiple Choice Tests
Say I have a Student table, it's got an int ID. I have a fixed set of 10 multiple choice questions with 5 possible answers. I have a normalized answer table that has the question id, the Student.answer (1-5) and the Student.ID I'm trying to write a single query that will return all scores over a certain pecentage. To this end I wrote a simple UDF that accepts the Student.answers and the correct answer, so it has 20 parameters. I'm starting to wonder if it's better to denormalize the answer table, bring it into my applcation and let my application do the scoring. Anyone ever tackle something like this and have insight?
If I understand your schema and question correctly, how about something like this: select student_name, score from students join (select student_answers.student_id, count(*) as score from student_answers, answer_key group by student_id where student_answers.question_id = answer_key.question_id and student_answers.answer = answer_key.answer) as student_scores on students.student_id = student_scores.student_id where score >= 7 order by score, student_name That should select the students with a score of 7 or more, for example. Just adjust the where clause for your purposes.
SQL Query Help - Scoring Multiple Choice Tests Say I have a Student table, it's got an int ID. I have a fixed set of 10 multiple choice questions with 5 possible answers. I have a normalized answer table that has the question id, the Student.answer (1-5) and the Student.ID I'm trying to write a single query that will return all scores over a certain pecentage. To this end I wrote a simple UDF that accepts the Student.answers and the correct answer, so it has 20 parameters. I'm starting to wonder if it's better to denormalize the answer table, bring it into my applcation and let my application do the scoring. Anyone ever tackle something like this and have insight?
TITLE: SQL Query Help - Scoring Multiple Choice Tests QUESTION: Say I have a Student table, it's got an int ID. I have a fixed set of 10 multiple choice questions with 5 possible answers. I have a normalized answer table that has the question id, the Student.answer (1-5) and the Student.ID I'm trying to write a single query that will return all scores over a certain pecentage. To this end I wrote a simple UDF that accepts the Student.answers and the correct answer, so it has 20 parameters. I'm starting to wonder if it's better to denormalize the answer table, bring it into my applcation and let my application do the scoring. Anyone ever tackle something like this and have insight? ANSWER: If I understand your schema and question correctly, how about something like this: select student_name, score from students join (select student_answers.student_id, count(*) as score from student_answers, answer_key group by student_id where student_answers.question_id = answer_key.question_id and student_answers.answer = answer_key.answer) as student_scores on students.student_id = student_scores.student_id where score >= 7 order by score, student_name That should select the students with a score of 7 or more, for example. Just adjust the where clause for your purposes.
[ "dynamic-sql" ]
0
2
2,382
6
0
2008-08-22T13:53:46.137000
2008-08-22T14:11:58.577000
22,431
22,745
Search strategies in ORMs
I am looking for information on handling search in different ORMs. Currently I am redeveloping some old application in PHP and one of requirements is: make everything or almost everything searchable, so user just types "punkrock live" and the app finds videos clips, music tracks, reviews, upcoming events or even user comments labeled that way. In environment where everything is searchable ORM need to support this feature in two ways: providing some indexing API on "O" side of ORM providing means for bulk database retrieval on "R" side Ideal solution would return ready made objects based on searched string. Do you know any good end-to-end solutions that does the job, not necessarily in PHP? If you dealt with similar problem it would be nice to listen what your experience is. Something more than Use Lucene or semantic web is the way oneliners, tho;-)*
I have recently integrated the Compass search engine into a Java EE 5 application. It is based on Lucene Java and supports different ORM frameworks as well as other types of models like XML or no real model at all;) In the case of an object model managed by an ORM framework you can annotate your classes with special annotations (e.g. @Searchable), register your classes and let Compass index them on application startup and listen to changes to the model automatically. When it comes to searching, you have the power of Lucene at hand. Compass then gives you instances of your model objects as search result. It's not PHP, but you said it didn't have to be PHP necessarily;) Don't know if this helps, though...
Search strategies in ORMs I am looking for information on handling search in different ORMs. Currently I am redeveloping some old application in PHP and one of requirements is: make everything or almost everything searchable, so user just types "punkrock live" and the app finds videos clips, music tracks, reviews, upcoming events or even user comments labeled that way. In environment where everything is searchable ORM need to support this feature in two ways: providing some indexing API on "O" side of ORM providing means for bulk database retrieval on "R" side Ideal solution would return ready made objects based on searched string. Do you know any good end-to-end solutions that does the job, not necessarily in PHP? If you dealt with similar problem it would be nice to listen what your experience is. Something more than Use Lucene or semantic web is the way oneliners, tho;-)*
TITLE: Search strategies in ORMs QUESTION: I am looking for information on handling search in different ORMs. Currently I am redeveloping some old application in PHP and one of requirements is: make everything or almost everything searchable, so user just types "punkrock live" and the app finds videos clips, music tracks, reviews, upcoming events or even user comments labeled that way. In environment where everything is searchable ORM need to support this feature in two ways: providing some indexing API on "O" side of ORM providing means for bulk database retrieval on "R" side Ideal solution would return ready made objects based on searched string. Do you know any good end-to-end solutions that does the job, not necessarily in PHP? If you dealt with similar problem it would be nice to listen what your experience is. Something more than Use Lucene or semantic web is the way oneliners, tho;-)* ANSWER: I have recently integrated the Compass search engine into a Java EE 5 application. It is based on Lucene Java and supports different ORM frameworks as well as other types of models like XML or no real model at all;) In the case of an object model managed by an ORM framework you can annotate your classes with special annotations (e.g. @Searchable), register your classes and let Compass index them on application startup and listen to changes to the model automatically. When it comes to searching, you have the power of Lucene at hand. Compass then gives you instances of your model objects as search result. It's not PHP, but you said it didn't have to be PHP necessarily;) Don't know if this helps, though...
[ "search", "orm", "doctrine", "propel" ]
1
2
306
2
0
2008-08-22T14:05:05.410000
2008-08-22T16:05:16.197000
22,444
22,449
My regex is matching too much. How do I make it stop?
I have this gigantic ugly string: J0000000: Transaction A0001401 started on 8/22/2008 9:49:29 AM J0000010: Project name: E:\foo.pf J0000011: Job name: MBiek Direct Mail Test J0000020: Document 1 - Completed successfully I'm trying to extract pieces from it using regex. In this case, I want to grab everything after Project Name up to the part where it says J0000011: (the 11 is going to be a different number every time). Here's the regex I've been playing with: Project name:\s+(.*)\s+J[0-9]{7}: The problem is that it doesn't stop until it hits the J0000020: at the end. How do I make the regex stop at the first occurrence of J[0-9]{7}?
Make.* non-greedy by adding '? ' after it: Project name:\s+(.*?)\s+J[0-9]{7}:
My regex is matching too much. How do I make it stop? I have this gigantic ugly string: J0000000: Transaction A0001401 started on 8/22/2008 9:49:29 AM J0000010: Project name: E:\foo.pf J0000011: Job name: MBiek Direct Mail Test J0000020: Document 1 - Completed successfully I'm trying to extract pieces from it using regex. In this case, I want to grab everything after Project Name up to the part where it says J0000011: (the 11 is going to be a different number every time). Here's the regex I've been playing with: Project name:\s+(.*)\s+J[0-9]{7}: The problem is that it doesn't stop until it hits the J0000020: at the end. How do I make the regex stop at the first occurrence of J[0-9]{7}?
TITLE: My regex is matching too much. How do I make it stop? QUESTION: I have this gigantic ugly string: J0000000: Transaction A0001401 started on 8/22/2008 9:49:29 AM J0000010: Project name: E:\foo.pf J0000011: Job name: MBiek Direct Mail Test J0000020: Document 1 - Completed successfully I'm trying to extract pieces from it using regex. In this case, I want to grab everything after Project Name up to the part where it says J0000011: (the 11 is going to be a different number every time). Here's the regex I've been playing with: Project name:\s+(.*)\s+J[0-9]{7}: The problem is that it doesn't stop until it hits the J0000020: at the end. How do I make the regex stop at the first occurrence of J[0-9]{7}? ANSWER: Make.* non-greedy by adding '? ' after it: Project name:\s+(.*?)\s+J[0-9]{7}:
[ "regex" ]
121
184
82,133
4
0
2008-08-22T14:10:40.170000
2008-08-22T14:12:01.243000
22,459
22,473
memset() causing data abort
I'm getting some strange, intermittent, data aborts (< 5% of the time) in some of my code, when calling memset(). The problem is that is usually doesn't happen unless the code is running for a couple days, so it's hard to catch it in the act. I'm using the following code: char *msg = (char*)malloc(sizeof(char)*2048); char *temp = (char*)malloc(sizeof(char)*1024); memset(msg, 0, 2048); memset(temp, 0, 1024); char *tempstr = (char*)malloc(sizeof(char)*128); sprintf(temp, "%s %s/%s %s%s", EZMPPOST, EZMPTAG, EZMPVER, TYPETXT, EOL); strcat(msg, temp); //Add Data memset(tempstr, '\0', 128); wcstombs(tempstr, gdevID, wcslen(gdevID)); sprintf(temp, "%s: %s%s", "DeviceID", tempstr, EOL); strcat(msg, temp); As you can see, I'm not trying to use memset with a size larger that what's originally allocated with malloc() Anyone see what might be wrong with this?
malloc can return NULL if no memory is available. You're not checking for that.
memset() causing data abort I'm getting some strange, intermittent, data aborts (< 5% of the time) in some of my code, when calling memset(). The problem is that is usually doesn't happen unless the code is running for a couple days, so it's hard to catch it in the act. I'm using the following code: char *msg = (char*)malloc(sizeof(char)*2048); char *temp = (char*)malloc(sizeof(char)*1024); memset(msg, 0, 2048); memset(temp, 0, 1024); char *tempstr = (char*)malloc(sizeof(char)*128); sprintf(temp, "%s %s/%s %s%s", EZMPPOST, EZMPTAG, EZMPVER, TYPETXT, EOL); strcat(msg, temp); //Add Data memset(tempstr, '\0', 128); wcstombs(tempstr, gdevID, wcslen(gdevID)); sprintf(temp, "%s: %s%s", "DeviceID", tempstr, EOL); strcat(msg, temp); As you can see, I'm not trying to use memset with a size larger that what's originally allocated with malloc() Anyone see what might be wrong with this?
TITLE: memset() causing data abort QUESTION: I'm getting some strange, intermittent, data aborts (< 5% of the time) in some of my code, when calling memset(). The problem is that is usually doesn't happen unless the code is running for a couple days, so it's hard to catch it in the act. I'm using the following code: char *msg = (char*)malloc(sizeof(char)*2048); char *temp = (char*)malloc(sizeof(char)*1024); memset(msg, 0, 2048); memset(temp, 0, 1024); char *tempstr = (char*)malloc(sizeof(char)*128); sprintf(temp, "%s %s/%s %s%s", EZMPPOST, EZMPTAG, EZMPVER, TYPETXT, EOL); strcat(msg, temp); //Add Data memset(tempstr, '\0', 128); wcstombs(tempstr, gdevID, wcslen(gdevID)); sprintf(temp, "%s: %s%s", "DeviceID", tempstr, EOL); strcat(msg, temp); As you can see, I'm not trying to use memset with a size larger that what's originally allocated with malloc() Anyone see what might be wrong with this? ANSWER: malloc can return NULL if no memory is available. You're not checking for that.
[ "c++", "c", "memory", "windows-mobile" ]
4
21
5,359
10
0
2008-08-22T14:17:01.747000
2008-08-22T14:21:43.030000
22,465
158,640
I'm looking for a Windows hosting provider that supports custom os images (like AMZN EC2)
I've come to love Amazon's EC2 service and I'm looking for something similar that supports the ability to save a running Windows server image and start new instances from it. I contacted GoGrid (the feature is planned in future) and Mosso (no joy) Anyone know of any hosting/cloud providers that can dothis?
I have just received a message from Amazon to the effect that that they will be supporting Windows Server on EC2 this fall. Wahaay!!
I'm looking for a Windows hosting provider that supports custom os images (like AMZN EC2) I've come to love Amazon's EC2 service and I'm looking for something similar that supports the ability to save a running Windows server image and start new instances from it. I contacted GoGrid (the feature is planned in future) and Mosso (no joy) Anyone know of any hosting/cloud providers that can dothis?
TITLE: I'm looking for a Windows hosting provider that supports custom os images (like AMZN EC2) QUESTION: I've come to love Amazon's EC2 service and I'm looking for something similar that supports the ability to save a running Windows server image and start new instances from it. I contacted GoGrid (the feature is planned in future) and Mosso (no joy) Anyone know of any hosting/cloud providers that can dothis? ANSWER: I have just received a message from Amazon to the effect that that they will be supporting Windows Server on EC2 this fall. Wahaay!!
[ "hosting", "windows-server-2003", "amazon-ec2", "virtual", "cloud" ]
1
4
426
5
0
2008-08-22T14:19:13.223000
2008-10-01T17:00:05.913000
22,466
22,613
jQuery AJAX vs. UpdatePanel
We've got a page with a ton of jQuery (approximately 2000 lines) that we want to trim down b/c it is a maintenance nightmare, and it might be easier to maintain on the server. We've thought about using UpdatePanel for this. However, we don't like the fact that the UpdatePanel is sending the whole page back to the server.
Don't move to UpdatePanels. After coming from jQuery, the drop in performance would be untenable. Especially on a page as complex as yours sounds. If you have 2,000 lines of JavaScript code, the solution is to refactor that code. If you put 2,000 lines of C# code in one file, it would be difficult to maintain too. That would be difficult to manage effectively with any language or tool. If you're using 3.5 SP1, you can use the ScriptManager's new script combining to separate your JavaScript into multiple files with no penalty. That way, you can logically partition your code just as you would with server side code.
jQuery AJAX vs. UpdatePanel We've got a page with a ton of jQuery (approximately 2000 lines) that we want to trim down b/c it is a maintenance nightmare, and it might be easier to maintain on the server. We've thought about using UpdatePanel for this. However, we don't like the fact that the UpdatePanel is sending the whole page back to the server.
TITLE: jQuery AJAX vs. UpdatePanel QUESTION: We've got a page with a ton of jQuery (approximately 2000 lines) that we want to trim down b/c it is a maintenance nightmare, and it might be easier to maintain on the server. We've thought about using UpdatePanel for this. However, we don't like the fact that the UpdatePanel is sending the whole page back to the server. ANSWER: Don't move to UpdatePanels. After coming from jQuery, the drop in performance would be untenable. Especially on a page as complex as yours sounds. If you have 2,000 lines of JavaScript code, the solution is to refactor that code. If you put 2,000 lines of C# code in one file, it would be difficult to maintain too. That would be difficult to manage effectively with any language or tool. If you're using 3.5 SP1, you can use the ScriptManager's new script combining to separate your JavaScript into multiple files with no penalty. That way, you can logically partition your code just as you would with server side code.
[ "javascript", "jquery", "asp.net", "ajax", "updatepanel" ]
24
41
13,362
4
0
2008-08-22T14:19:49.570000
2008-08-22T15:09:44.770000
22,469
27,771
What's a good machine for iPhone development?
I'm going to be working on some iPhone apps so I've been given a golden ticket to buy a Mac. However the golden ticket isn't worth that much, and I'm thinking iMac. Now, Macs are great, I love 'em and use 'em at home, but I know that the iMac is geared more towards the average consumer than the professional. Is an iMac going to be powerful enough to do iPhone development on? If it helps any, the only thing I envision doing on the Mac is running XCode and maybe a web browser. Is there anybody out there doing iPhone development and having trouble running the required tools on their machine? If so, what do you have?
Any modern Mac will be fine. I work on a two year old MacBook (2GHz) with 2Gb of memory and its perfectly usable. The biggest constraint I find it screen real-estate. I am way more productive on my 22" external screen. Go big if you get an iMac or consider adding an external monitor to the base model.
What's a good machine for iPhone development? I'm going to be working on some iPhone apps so I've been given a golden ticket to buy a Mac. However the golden ticket isn't worth that much, and I'm thinking iMac. Now, Macs are great, I love 'em and use 'em at home, but I know that the iMac is geared more towards the average consumer than the professional. Is an iMac going to be powerful enough to do iPhone development on? If it helps any, the only thing I envision doing on the Mac is running XCode and maybe a web browser. Is there anybody out there doing iPhone development and having trouble running the required tools on their machine? If so, what do you have?
TITLE: What's a good machine for iPhone development? QUESTION: I'm going to be working on some iPhone apps so I've been given a golden ticket to buy a Mac. However the golden ticket isn't worth that much, and I'm thinking iMac. Now, Macs are great, I love 'em and use 'em at home, but I know that the iMac is geared more towards the average consumer than the professional. Is an iMac going to be powerful enough to do iPhone development on? If it helps any, the only thing I envision doing on the Mac is running XCode and maybe a web browser. Is there anybody out there doing iPhone development and having trouble running the required tools on their machine? If so, what do you have? ANSWER: Any modern Mac will be fine. I work on a two year old MacBook (2GHz) with 2Gb of memory and its perfectly usable. The biggest constraint I find it screen real-estate. I am way more productive on my 22" external screen. Go big if you get an iMac or consider adding an external monitor to the base model.
[ "ios", "macos" ]
48
28
38,472
19
0
2008-08-22T14:20:35.730000
2008-08-26T11:19:43.853000
22,474
22,476
How do I display records containing specific information in SQl
How do I select all records that contain "LCS" within the title column in sql.
SELECT * FROM TABLE WHERE TABLE.TITLE LIKE '%LCS%'; % is the wild card matcher.
How do I display records containing specific information in SQl How do I select all records that contain "LCS" within the title column in sql.
TITLE: How do I display records containing specific information in SQl QUESTION: How do I select all records that contain "LCS" within the title column in sql. ANSWER: SELECT * FROM TABLE WHERE TABLE.TITLE LIKE '%LCS%'; % is the wild card matcher.
[ "sql", "sql-server" ]
2
2
361
3
0
2008-08-22T14:21:47.460000
2008-08-22T14:22:40.563000
22,500
22,547
What are the major differences between ANSI C and K&R C?
The Wikipedia article on ANSI C says: One of the aims of the ANSI C standardization process was to produce a superset of K&R C (the first published standard), incorporating many of the unofficial features subsequently introduced. However, the standards committee also included several new features, such as function prototypes (borrowed from the C++ programming language), and a more capable preprocessor. The syntax for parameter declarations was also changed to reflect the C++ style. That makes me think that there are differences. However, I didn't see a comparison between K&R C and ANSI C. Is there such a document? If not, what are the major differences? EDIT: I believe the K&R book says "ANSI C" on the cover. At least I believe the version that I have at home does. So perhaps there isn't a difference anymore?
There may be some confusion here about what "K&R C" is. The term refers to the language as documented in the first edition of "The C Programming Language." Roughly speaking: the input language of the Bell Labs C compiler circa 1978. Kernighan and Ritchie were involved in the ANSI standardization process. The "ANSI C" dialect superceded "K&R C" and subsequent editions of "The C Programming Language" adopt the ANSI conventions. "K&R C" is a "dead language," except to the extent that some compilers still accept legacy code.
What are the major differences between ANSI C and K&R C? The Wikipedia article on ANSI C says: One of the aims of the ANSI C standardization process was to produce a superset of K&R C (the first published standard), incorporating many of the unofficial features subsequently introduced. However, the standards committee also included several new features, such as function prototypes (borrowed from the C++ programming language), and a more capable preprocessor. The syntax for parameter declarations was also changed to reflect the C++ style. That makes me think that there are differences. However, I didn't see a comparison between K&R C and ANSI C. Is there such a document? If not, what are the major differences? EDIT: I believe the K&R book says "ANSI C" on the cover. At least I believe the version that I have at home does. So perhaps there isn't a difference anymore?
TITLE: What are the major differences between ANSI C and K&R C? QUESTION: The Wikipedia article on ANSI C says: One of the aims of the ANSI C standardization process was to produce a superset of K&R C (the first published standard), incorporating many of the unofficial features subsequently introduced. However, the standards committee also included several new features, such as function prototypes (borrowed from the C++ programming language), and a more capable preprocessor. The syntax for parameter declarations was also changed to reflect the C++ style. That makes me think that there are differences. However, I didn't see a comparison between K&R C and ANSI C. Is there such a document? If not, what are the major differences? EDIT: I believe the K&R book says "ANSI C" on the cover. At least I believe the version that I have at home does. So perhaps there isn't a difference anymore? ANSWER: There may be some confusion here about what "K&R C" is. The term refers to the language as documented in the first edition of "The C Programming Language." Roughly speaking: the input language of the Bell Labs C compiler circa 1978. Kernighan and Ritchie were involved in the ANSI standardization process. The "ANSI C" dialect superceded "K&R C" and subsequent editions of "The C Programming Language" adopt the ANSI conventions. "K&R C" is a "dead language," except to the extent that some compilers still accept legacy code.
[ "c", "kr-c", "c89" ]
48
33
44,439
11
0
2008-08-22T14:29:27.410000
2008-08-22T14:48:18.003000
22,509
22,585
Why is ASP.NET gzip compression corrupting CSS?
I have an ASP.NET webforms application (3.5 SP1) that I'm working on, and attempting to enable gzip fpr HTML and CSS that comes down the pipe. I'm using this implementation (and tried a few others that hook into Application_BeginRequest), and it seems to be corrupting the external CSS file that the pages use, but intermittently...suddenly all styles will disappear on a page refresh, stay that way for awhile, and then suddenly start working again. Both IE7 and FF3 exhibit this behavior. When viewing the CSS using the web developer toolbar, it returns jibberish. The cache-control header is coming through as "private," but I don't know enough to figure out if that's a contributing factor or not. Also, this is running on the ASP.NET Development Server. Maybe it'd be fine with IIS, but I'm developing on XP and it'd be IIS5.
Is it only CSS files that get corrupted? Do JS files (or any other static text files) come through ok? Also can you duplicate the behavior if you browse directly to the CSS file? I've only enabled compression on Windows 2003 server's IIS using this approach: IIS → Web Sites → Properties → Service tab, check both boxes IIS → Web Service Extensions → Right click, Add New Name Http Compression Required Files %systemroot%\system32\inetsrv\gzip.dll IIS → Right click top node, Internet Information Services, check Enable Direct Metabase Edit Backup and Edit %systemroot%\system32\inetsrv\MetaBase.xml Find Location ="/LM/W3SVC/Filters/Compression/gzip" Add png, css, js and any other static file extensions to HcFileExtensions Add aspx and any other executable extensions to HcScriptFileExtensions Save Restart IIS (run iisreset ) If you have a Windows 2003/2008 server to play with you could try that approach.
Why is ASP.NET gzip compression corrupting CSS? I have an ASP.NET webforms application (3.5 SP1) that I'm working on, and attempting to enable gzip fpr HTML and CSS that comes down the pipe. I'm using this implementation (and tried a few others that hook into Application_BeginRequest), and it seems to be corrupting the external CSS file that the pages use, but intermittently...suddenly all styles will disappear on a page refresh, stay that way for awhile, and then suddenly start working again. Both IE7 and FF3 exhibit this behavior. When viewing the CSS using the web developer toolbar, it returns jibberish. The cache-control header is coming through as "private," but I don't know enough to figure out if that's a contributing factor or not. Also, this is running on the ASP.NET Development Server. Maybe it'd be fine with IIS, but I'm developing on XP and it'd be IIS5.
TITLE: Why is ASP.NET gzip compression corrupting CSS? QUESTION: I have an ASP.NET webforms application (3.5 SP1) that I'm working on, and attempting to enable gzip fpr HTML and CSS that comes down the pipe. I'm using this implementation (and tried a few others that hook into Application_BeginRequest), and it seems to be corrupting the external CSS file that the pages use, but intermittently...suddenly all styles will disappear on a page refresh, stay that way for awhile, and then suddenly start working again. Both IE7 and FF3 exhibit this behavior. When viewing the CSS using the web developer toolbar, it returns jibberish. The cache-control header is coming through as "private," but I don't know enough to figure out if that's a contributing factor or not. Also, this is running on the ASP.NET Development Server. Maybe it'd be fine with IIS, but I'm developing on XP and it'd be IIS5. ANSWER: Is it only CSS files that get corrupted? Do JS files (or any other static text files) come through ok? Also can you duplicate the behavior if you browse directly to the CSS file? I've only enabled compression on Windows 2003 server's IIS using this approach: IIS → Web Sites → Properties → Service tab, check both boxes IIS → Web Service Extensions → Right click, Add New Name Http Compression Required Files %systemroot%\system32\inetsrv\gzip.dll IIS → Right click top node, Internet Information Services, check Enable Direct Metabase Edit Backup and Edit %systemroot%\system32\inetsrv\MetaBase.xml Find Location ="/LM/W3SVC/Filters/Compression/gzip" Add png, css, js and any other static file extensions to HcFileExtensions Add aspx and any other executable extensions to HcScriptFileExtensions Save Restart IIS (run iisreset ) If you have a Windows 2003/2008 server to play with you could try that approach.
[ "asp.net", "compression", "gzip" ]
10
5
3,653
2
0
2008-08-22T14:33:00.973000
2008-08-22T14:57:38.433000
22,519
49,821
How do I secure a folder used to let users upload files?
I have a folder in my web server used for the users to upload photos using an ASP page. Is it safe enough to give IUSR write permissions to the folder? Must I secure something else? I am afraid of hackers bypassing the ASP page and uploading content directly to the folder. I'm using ASP classic and IIS6 on Windows 2003 Server. The upload is through HTTP, not FTP. Edit: Changing the question for clarity and changing my answers as comments.
also, I would recommend not to let the users upload into a folder that's accessible from the web. Even the best MIME type detection may fail and you absolutely don't want users to upload, say, an executable disguised as a jpeg in a case where your MIME sniffing fails, but the one in IIS works correctly. In the PHP world it's even worse, because an attacker could upload a malicious PHP script and later access it via the webserver. Always, always store the uploaded files in a directory somewhere outside the document root and access them via some accessing-script which does additional sanitizing (and at least explicitly sets a image/whatever MIME type.
How do I secure a folder used to let users upload files? I have a folder in my web server used for the users to upload photos using an ASP page. Is it safe enough to give IUSR write permissions to the folder? Must I secure something else? I am afraid of hackers bypassing the ASP page and uploading content directly to the folder. I'm using ASP classic and IIS6 on Windows 2003 Server. The upload is through HTTP, not FTP. Edit: Changing the question for clarity and changing my answers as comments.
TITLE: How do I secure a folder used to let users upload files? QUESTION: I have a folder in my web server used for the users to upload photos using an ASP page. Is it safe enough to give IUSR write permissions to the folder? Must I secure something else? I am afraid of hackers bypassing the ASP page and uploading content directly to the folder. I'm using ASP classic and IIS6 on Windows 2003 Server. The upload is through HTTP, not FTP. Edit: Changing the question for clarity and changing my answers as comments. ANSWER: also, I would recommend not to let the users upload into a folder that's accessible from the web. Even the best MIME type detection may fail and you absolutely don't want users to upload, say, an executable disguised as a jpeg in a case where your MIME sniffing fails, but the one in IIS works correctly. In the PHP world it's even worse, because an attacker could upload a malicious PHP script and later access it via the webserver. Always, always store the uploaded files in a directory somewhere outside the document root and access them via some accessing-script which does additional sanitizing (and at least explicitly sets a image/whatever MIME type.
[ "security", "iis", "asp-classic", "iis-6", "windows-server-2003" ]
4
3
5,567
4
0
2008-08-22T14:38:15.110000
2008-09-08T14:35:25.053000
22,524
23,004
Execute shortcuts like programs
Example: You have a shortcut s to SomeProgram in the current directory. In cmd.exe, you can type s and it will launch the program. In PowerShell, typing s gives: The term 's' is not recognized as a cmdlet, function, operable program, or script file. Verify the term and try again. If you type s.lnk or SomeProgram, it runs the program just fine. How can I configure PowerShell to execute shortcuts just like programs?
On my Vista system typing S won't launch a lnk file unless I have the environment variable PATHEXT set with.lnk in the list. When I do. S will work in cmd.exe and I have to do.\S in powershell.
Execute shortcuts like programs Example: You have a shortcut s to SomeProgram in the current directory. In cmd.exe, you can type s and it will launch the program. In PowerShell, typing s gives: The term 's' is not recognized as a cmdlet, function, operable program, or script file. Verify the term and try again. If you type s.lnk or SomeProgram, it runs the program just fine. How can I configure PowerShell to execute shortcuts just like programs?
TITLE: Execute shortcuts like programs QUESTION: Example: You have a shortcut s to SomeProgram in the current directory. In cmd.exe, you can type s and it will launch the program. In PowerShell, typing s gives: The term 's' is not recognized as a cmdlet, function, operable program, or script file. Verify the term and try again. If you type s.lnk or SomeProgram, it runs the program just fine. How can I configure PowerShell to execute shortcuts just like programs? ANSWER: On my Vista system typing S won't launch a lnk file unless I have the environment variable PATHEXT set with.lnk in the list. When I do. S will work in cmd.exe and I have to do.\S in powershell.
[ "powershell" ]
17
9
37,681
6
0
2008-08-22T14:39:14.033000
2008-08-22T17:42:52.500000
22,528
22,587
PHP includes vs OOP
I would like to have a reference for the pros and cons of using include files vs objects(classes) when developing PHP applications. I know I would benefit from having one place to go for this answer...I have a few opinions of my own but I look forward to hearing others. A Simple Example: Certain pages on my site are only accessible to logged in users. I have two options for implementation (there are others but let's limit it to these two) Create an authenticate.php file and include it on every page. It holds the logic for authentication. Create a user object, which has an authenticate function, reference the object for authentication on every page. Edit I'd like to see some way weigh the benefits of one over the other. My current (and weak reasons) follow: Includes - Sometimes a function is just easier/shorter/faster to call Objects - Grouping of functionality and properties leads for longer term maintenance. Includes - Less code to write (no constructor, no class syntax) call me lazy but this is true. Objects - Force formality and a single approach to functions and creation. Includes - Easier for a novice to deal with Objects - Harder for novices, but frowned upon by professionals. I look at these factors at the start of a project to decide if I want to do includes or objects. Those are a few pros and cons off the top of my head.
These are not really opposite choices. You will have to include the checking code anyway. I read your question as procedural programming vs. OO programming. Writing a few lines of code, or a function, and including it in your page header was how things were done in PHP3 or PHP4. It's simple, it works (that's how we did it in osCommerce, for example, an eCommerce PHP application). But it's not easy to maintain and modify, as many developers can confirm. In PHP5 you'd write a user object which will carry its own data and methods for authentication. Your code will be clearer and easier to maintain as everything having to do with users and authentication will be concentrated in a single place.
PHP includes vs OOP I would like to have a reference for the pros and cons of using include files vs objects(classes) when developing PHP applications. I know I would benefit from having one place to go for this answer...I have a few opinions of my own but I look forward to hearing others. A Simple Example: Certain pages on my site are only accessible to logged in users. I have two options for implementation (there are others but let's limit it to these two) Create an authenticate.php file and include it on every page. It holds the logic for authentication. Create a user object, which has an authenticate function, reference the object for authentication on every page. Edit I'd like to see some way weigh the benefits of one over the other. My current (and weak reasons) follow: Includes - Sometimes a function is just easier/shorter/faster to call Objects - Grouping of functionality and properties leads for longer term maintenance. Includes - Less code to write (no constructor, no class syntax) call me lazy but this is true. Objects - Force formality and a single approach to functions and creation. Includes - Easier for a novice to deal with Objects - Harder for novices, but frowned upon by professionals. I look at these factors at the start of a project to decide if I want to do includes or objects. Those are a few pros and cons off the top of my head.
TITLE: PHP includes vs OOP QUESTION: I would like to have a reference for the pros and cons of using include files vs objects(classes) when developing PHP applications. I know I would benefit from having one place to go for this answer...I have a few opinions of my own but I look forward to hearing others. A Simple Example: Certain pages on my site are only accessible to logged in users. I have two options for implementation (there are others but let's limit it to these two) Create an authenticate.php file and include it on every page. It holds the logic for authentication. Create a user object, which has an authenticate function, reference the object for authentication on every page. Edit I'd like to see some way weigh the benefits of one over the other. My current (and weak reasons) follow: Includes - Sometimes a function is just easier/shorter/faster to call Objects - Grouping of functionality and properties leads for longer term maintenance. Includes - Less code to write (no constructor, no class syntax) call me lazy but this is true. Objects - Force formality and a single approach to functions and creation. Includes - Easier for a novice to deal with Objects - Harder for novices, but frowned upon by professionals. I look at these factors at the start of a project to decide if I want to do includes or objects. Those are a few pros and cons off the top of my head. ANSWER: These are not really opposite choices. You will have to include the checking code anyway. I read your question as procedural programming vs. OO programming. Writing a few lines of code, or a function, and including it in your page header was how things were done in PHP3 or PHP4. It's simple, it works (that's how we did it in osCommerce, for example, an eCommerce PHP application). But it's not easy to maintain and modify, as many developers can confirm. In PHP5 you'd write a user object which will carry its own data and methods for authentication. Your code will be clearer and easier to maintain as everything having to do with users and authentication will be concentrated in a single place.
[ "php", "coding-style" ]
11
13
3,237
6
0
2008-08-22T14:41:20.597000
2008-08-22T14:57:46.547000
22,552
22,572
Passing a commented, multi-line (freespace) regex to preg_match
I have a regex that is going to end up being a bit long and it'd make it much easier to read to have it across multiple lines. I tried this but it just barfs. preg_match( '^J[0-9]{7}:\s+ (.*?) #Extract the Transaction Start Date msg \s+J[0-9]{7}:\s+Project\sname:\s+ (.*?) #Extract the Project Name \s+J[0-9]{7}:\s+Job\sname:\s+ (.*?) #Extract the Job Name \s+J[0-9]{7}:\s+', $this->getResultVar('FullMessage'), $atmp ); Is there are way to pass a regex in the above form to preg_match?
You can use the extended syntax: preg_match("/ test /x", $foo, $bar);
Passing a commented, multi-line (freespace) regex to preg_match I have a regex that is going to end up being a bit long and it'd make it much easier to read to have it across multiple lines. I tried this but it just barfs. preg_match( '^J[0-9]{7}:\s+ (.*?) #Extract the Transaction Start Date msg \s+J[0-9]{7}:\s+Project\sname:\s+ (.*?) #Extract the Project Name \s+J[0-9]{7}:\s+Job\sname:\s+ (.*?) #Extract the Job Name \s+J[0-9]{7}:\s+', $this->getResultVar('FullMessage'), $atmp ); Is there are way to pass a regex in the above form to preg_match?
TITLE: Passing a commented, multi-line (freespace) regex to preg_match QUESTION: I have a regex that is going to end up being a bit long and it'd make it much easier to read to have it across multiple lines. I tried this but it just barfs. preg_match( '^J[0-9]{7}:\s+ (.*?) #Extract the Transaction Start Date msg \s+J[0-9]{7}:\s+Project\sname:\s+ (.*?) #Extract the Project Name \s+J[0-9]{7}:\s+Job\sname:\s+ (.*?) #Extract the Job Name \s+J[0-9]{7}:\s+', $this->getResultVar('FullMessage'), $atmp ); Is there are way to pass a regex in the above form to preg_match? ANSWER: You can use the extended syntax: preg_match("/ test /x", $foo, $bar);
[ "php", "regex" ]
2
5
1,033
5
0
2008-08-22T14:49:36.037000
2008-08-22T14:54:20.267000
22,566
22,573
How do I read in the contents of a directory in Perl?
How do I get Perl to read the contents of a given directory into an array? Backticks can do it, but is there some method using 'scandir' or a similar term?
opendir(D, "/path/to/directory") || die "Can't open directory: $!\n"; while (my $f = readdir(D)) { print "\$f = $f\n"; } closedir(D); EDIT: Oh, sorry, missed the "into an array" part: my $d = shift; opendir(D, "$d") || die "Can't open directory $d: $!\n"; my @list = readdir(D); closedir(D); foreach my $f (@list) { print "\$f = $f\n"; } EDIT2: Most of the other answers are valid, but I wanted to comment on this answer specifically, in which this solution is offered: opendir(DIR, $somedir) || die "Can't open directory $somedir: $!"; @dots = grep { (!/^\./) && -f "$somedir/$_" } readdir(DIR); closedir DIR; First, to document what it's doing since the poster didn't: it's passing the returned list from readdir() through a grep() that only returns those values that are files (as opposed to directories, devices, named pipes, etc.) and that do not begin with a dot (which makes the list name @dots misleading, but that's due to the change he made when copying it over from the readdir() documentation). Since it limits the contents of the directory it returns, I don't think it's technically a correct answer to this question, but it illustrates a common idiom used to filter filenames in Perl, and I thought it would be valuable to document. Another example seen a lot is: @list = grep!/^\.\.?$/, readdir(D); This snippet reads all contents from the directory handle D except '.' and '..', since those are very rarely desired to be used in the listing.
How do I read in the contents of a directory in Perl? How do I get Perl to read the contents of a given directory into an array? Backticks can do it, but is there some method using 'scandir' or a similar term?
TITLE: How do I read in the contents of a directory in Perl? QUESTION: How do I get Perl to read the contents of a given directory into an array? Backticks can do it, but is there some method using 'scandir' or a similar term? ANSWER: opendir(D, "/path/to/directory") || die "Can't open directory: $!\n"; while (my $f = readdir(D)) { print "\$f = $f\n"; } closedir(D); EDIT: Oh, sorry, missed the "into an array" part: my $d = shift; opendir(D, "$d") || die "Can't open directory $d: $!\n"; my @list = readdir(D); closedir(D); foreach my $f (@list) { print "\$f = $f\n"; } EDIT2: Most of the other answers are valid, but I wanted to comment on this answer specifically, in which this solution is offered: opendir(DIR, $somedir) || die "Can't open directory $somedir: $!"; @dots = grep { (!/^\./) && -f "$somedir/$_" } readdir(DIR); closedir DIR; First, to document what it's doing since the poster didn't: it's passing the returned list from readdir() through a grep() that only returns those values that are files (as opposed to directories, devices, named pipes, etc.) and that do not begin with a dot (which makes the list name @dots misleading, but that's due to the change he made when copying it over from the readdir() documentation). Since it limits the contents of the directory it returns, I don't think it's technically a correct answer to this question, but it illustrates a common idiom used to filter filenames in Perl, and I thought it would be valuable to document. Another example seen a lot is: @list = grep!/^\.\.?$/, readdir(D); This snippet reads all contents from the directory handle D except '.' and '..', since those are very rarely desired to be used in the listing.
[ "perl", "file-io", "filesystems" ]
39
58
64,625
9
0
2008-08-22T14:53:21.970000
2008-08-22T14:54:22.857000
22,570
22,592
What's a good way to check if two datetimes are on the same calendar day in TSQL?
Here is the issue I am having: I have a large query that needs to compare datetimes in the where clause to see if two dates are on the same day. My current solution, which sucks, is to send the datetimes into a UDF to convert them to midnight of the same day, and then check those dates for equality. When it comes to the query plan, this is a disaster, as are almost all UDFs in joins or where clauses. This is one of the only places in my application that I haven't been able to root out the functions and give the query optimizer something it can actually use to locate the best index. In this case, merging the function code back into the query seems impractical. I think I am missing something simple here. Here's the function for reference. if not exists (select * from dbo.sysobjects where id = object_id(N'dbo.f_MakeDate') and type in (N'FN', N'IF', N'TF', N'FS', N'FT')) exec('create function dbo.f_MakeDate() returns int as begin declare @retval int return @retval end') go alter function dbo.f_MakeDate ( @Day datetime, @Hour int, @Minute int ) returns datetime as /* Creates a datetime using the year-month-day portion of @Day, and the @Hour and @Minute provided */ begin declare @retval datetime set @retval = cast( cast(datepart(m, @Day) as varchar(2)) + '/' + cast(datepart(d, @Day) as varchar(2)) + '/' + cast(datepart(yyyy, @Day) as varchar(4)) + ' ' + cast(@Hour as varchar(2)) + ':' + cast(@Minute as varchar(2)) as datetime) return @retval end go To complicate matters, I am joining on time zone tables to check the date against the local time, which could be different for every row: where dbo.f_MakeDate(dateadd(hh, tz.Offset + case when ds.LocalTimeZone is not null then 1 else 0 end, t.TheDateINeedToCheck), 0, 0) = @activityDateMidnight [Edit] I'm incorporating @Todd's suggestion: where datediff(day, dateadd(hh, tz.Offset + case when ds.LocalTimeZone is not null then 1 else 0 end, t.TheDateINeedToCheck), @ActivityDate) = 0 My misconception about how datediff works (the same day of year in consecutive years yields 366, not 0 as I expected) caused me to waste a lot of effort. But the query plan didn't change. I think I need to go back to the drawing board with the whole thing.
This is much more concise: where datediff(day, date1, date2) = 0
What's a good way to check if two datetimes are on the same calendar day in TSQL? Here is the issue I am having: I have a large query that needs to compare datetimes in the where clause to see if two dates are on the same day. My current solution, which sucks, is to send the datetimes into a UDF to convert them to midnight of the same day, and then check those dates for equality. When it comes to the query plan, this is a disaster, as are almost all UDFs in joins or where clauses. This is one of the only places in my application that I haven't been able to root out the functions and give the query optimizer something it can actually use to locate the best index. In this case, merging the function code back into the query seems impractical. I think I am missing something simple here. Here's the function for reference. if not exists (select * from dbo.sysobjects where id = object_id(N'dbo.f_MakeDate') and type in (N'FN', N'IF', N'TF', N'FS', N'FT')) exec('create function dbo.f_MakeDate() returns int as begin declare @retval int return @retval end') go alter function dbo.f_MakeDate ( @Day datetime, @Hour int, @Minute int ) returns datetime as /* Creates a datetime using the year-month-day portion of @Day, and the @Hour and @Minute provided */ begin declare @retval datetime set @retval = cast( cast(datepart(m, @Day) as varchar(2)) + '/' + cast(datepart(d, @Day) as varchar(2)) + '/' + cast(datepart(yyyy, @Day) as varchar(4)) + ' ' + cast(@Hour as varchar(2)) + ':' + cast(@Minute as varchar(2)) as datetime) return @retval end go To complicate matters, I am joining on time zone tables to check the date against the local time, which could be different for every row: where dbo.f_MakeDate(dateadd(hh, tz.Offset + case when ds.LocalTimeZone is not null then 1 else 0 end, t.TheDateINeedToCheck), 0, 0) = @activityDateMidnight [Edit] I'm incorporating @Todd's suggestion: where datediff(day, dateadd(hh, tz.Offset + case when ds.LocalTimeZone is not null then 1 else 0 end, t.TheDateINeedToCheck), @ActivityDate) = 0 My misconception about how datediff works (the same day of year in consecutive years yields 366, not 0 as I expected) caused me to waste a lot of effort. But the query plan didn't change. I think I need to go back to the drawing board with the whole thing.
TITLE: What's a good way to check if two datetimes are on the same calendar day in TSQL? QUESTION: Here is the issue I am having: I have a large query that needs to compare datetimes in the where clause to see if two dates are on the same day. My current solution, which sucks, is to send the datetimes into a UDF to convert them to midnight of the same day, and then check those dates for equality. When it comes to the query plan, this is a disaster, as are almost all UDFs in joins or where clauses. This is one of the only places in my application that I haven't been able to root out the functions and give the query optimizer something it can actually use to locate the best index. In this case, merging the function code back into the query seems impractical. I think I am missing something simple here. Here's the function for reference. if not exists (select * from dbo.sysobjects where id = object_id(N'dbo.f_MakeDate') and type in (N'FN', N'IF', N'TF', N'FS', N'FT')) exec('create function dbo.f_MakeDate() returns int as begin declare @retval int return @retval end') go alter function dbo.f_MakeDate ( @Day datetime, @Hour int, @Minute int ) returns datetime as /* Creates a datetime using the year-month-day portion of @Day, and the @Hour and @Minute provided */ begin declare @retval datetime set @retval = cast( cast(datepart(m, @Day) as varchar(2)) + '/' + cast(datepart(d, @Day) as varchar(2)) + '/' + cast(datepart(yyyy, @Day) as varchar(4)) + ' ' + cast(@Hour as varchar(2)) + ':' + cast(@Minute as varchar(2)) as datetime) return @retval end go To complicate matters, I am joining on time zone tables to check the date against the local time, which could be different for every row: where dbo.f_MakeDate(dateadd(hh, tz.Offset + case when ds.LocalTimeZone is not null then 1 else 0 end, t.TheDateINeedToCheck), 0, 0) = @activityDateMidnight [Edit] I'm incorporating @Todd's suggestion: where datediff(day, dateadd(hh, tz.Offset + case when ds.LocalTimeZone is not null then 1 else 0 end, t.TheDateINeedToCheck), @ActivityDate) = 0 My misconception about how datediff works (the same day of year in consecutive years yields 366, not 0 as I expected) caused me to waste a lot of effort. But the query plan didn't change. I think I need to go back to the drawing board with the whole thing. ANSWER: This is much more concise: where datediff(day, date1, date2) = 0
[ "sql", "sql-server", "t-sql", "datetime", "user-defined-functions" ]
37
87
64,745
8
0
2008-08-22T14:53:47.710000
2008-08-22T15:02:46.300000
22,590
22,653
How do I cluster an upload folder with ASP.Net?
We have a situation where users are allowed to upload content, and then separately make some changes, then submit a form based on those changes. This works fine in a single-server, non-failover environment, however we would like some sort of solution for sharing the files between servers that supports failover. Has anyone run into this in the past? And what kind of solutions were you able to develop? Obviously persisting to the database is one option, but we'd prefer to avoid that.
At a former job we had a cluster of web servers with an F5 load balancer in front of them. We had a very similar problem in that our applications allowed users to upload content which might include photo's and such. These were legacy applications and we did not want to edit them to use a database and a SAN solution was too expensive for our situation. We ended up using a file replication service on the two clustered servers. This ran as a service on both machines using an account that had network access to paths on the opposite server. When a file was uploaded, this backend service sync'd the data in the file system folders making it available to be served from either web server. Two of the products we reviewed were ViceVersa and PeerSync. I think we ended up using PeerSync.
How do I cluster an upload folder with ASP.Net? We have a situation where users are allowed to upload content, and then separately make some changes, then submit a form based on those changes. This works fine in a single-server, non-failover environment, however we would like some sort of solution for sharing the files between servers that supports failover. Has anyone run into this in the past? And what kind of solutions were you able to develop? Obviously persisting to the database is one option, but we'd prefer to avoid that.
TITLE: How do I cluster an upload folder with ASP.Net? QUESTION: We have a situation where users are allowed to upload content, and then separately make some changes, then submit a form based on those changes. This works fine in a single-server, non-failover environment, however we would like some sort of solution for sharing the files between servers that supports failover. Has anyone run into this in the past? And what kind of solutions were you able to develop? Obviously persisting to the database is one option, but we'd prefer to avoid that. ANSWER: At a former job we had a cluster of web servers with an F5 load balancer in front of them. We had a very similar problem in that our applications allowed users to upload content which might include photo's and such. These were legacy applications and we did not want to edit them to use a database and a SAN solution was too expensive for our situation. We ended up using a file replication service on the two clustered servers. This ran as a service on both machines using an account that had network access to paths on the opposite server. When a file was uploaded, this backend service sync'd the data in the file system folders making it available to be served from either web server. Two of the products we reviewed were ViceVersa and PeerSync. I think we ended up using PeerSync.
[ "asp.net", "iis-6", "windows-server-2003", "cluster-computing", "failover" ]
5
1
755
4
0
2008-08-22T15:02:06.630000
2008-08-22T15:20:19.673000
22,598
22,627
ASP.NET Tutorials
can you recommend some good ASP.NET tutorials or a good book? Should I jump right to ASP.NET MVC/html/javascript or learn web forms first? Thanks
A great book if you're just beginning is Matthew MacDonald's Beginning ASP.NET 3.5 in C# 2008: From Novice to Professional. Once you're done with that a great reference (also by MacDonald) is Pro ASP.NET 3.5 in C# 2008. One of my favorite sources of information online is 4GuysFromRolla.
ASP.NET Tutorials can you recommend some good ASP.NET tutorials or a good book? Should I jump right to ASP.NET MVC/html/javascript or learn web forms first? Thanks
TITLE: ASP.NET Tutorials QUESTION: can you recommend some good ASP.NET tutorials or a good book? Should I jump right to ASP.NET MVC/html/javascript or learn web forms first? Thanks ANSWER: A great book if you're just beginning is Matthew MacDonald's Beginning ASP.NET 3.5 in C# 2008: From Novice to Professional. Once you're done with that a great reference (also by MacDonald) is Pro ASP.NET 3.5 in C# 2008. One of my favorite sources of information online is 4GuysFromRolla.
[ "asp.net", "asp.net-mvc" ]
2
2
700
5
0
2008-08-22T15:06:36.883000
2008-08-22T15:13:13.577000
22,607
22,666
Install Leopard inside VMWare
I’m thinking about trying some development for the iPhone, is it possible to install Leopard inside VMWare? I already have a pretty high spec PC with a comfy setup that I’d like to use, or do I need to buy a real Mac?
It is legal to run Mac OS X Server in a virtual machine on Apple hardware. All other forms of Mac OS X virtualization are currently forbidden.
Install Leopard inside VMWare I’m thinking about trying some development for the iPhone, is it possible to install Leopard inside VMWare? I already have a pretty high spec PC with a comfy setup that I’d like to use, or do I need to buy a real Mac?
TITLE: Install Leopard inside VMWare QUESTION: I’m thinking about trying some development for the iPhone, is it possible to install Leopard inside VMWare? I already have a pretty high spec PC with a comfy setup that I’d like to use, or do I need to buy a real Mac? ANSWER: It is legal to run Mac OS X Server in a virtual machine on Apple hardware. All other forms of Mac OS X virtualization are currently forbidden.
[ "iphone", "macos", "virtualization" ]
10
12
2,698
6
0
2008-08-22T15:08:50.840000
2008-08-22T15:29:14.223000
22,617
22,624
Format numbers to strings in Python
I need to find out how to format numbers as strings. My code is here: return str(hours)+":"+str(minutes)+":"+str(seconds)+" "+ampm Hours and minutes are integers, and seconds is a float. the str() function will convert all of these numbers to the tenths (0.1) place. So instead of my string outputting "5:30:59.07 pm", it would display something like "5.0:30.0:59.1 pm". Bottom line, what library / function do I need to do this for me?
Starting with Python 3.6, formatting in Python can be done using formatted string literals or f-strings: hours, minutes, seconds = 6, 56, 33 f'{hours:02}:{minutes:02}:{seconds:02} {"pm" if hours > 12 else "am"}' or the str.format function starting with 2.7: "{:02}:{:02}:{:02} {}".format(hours, minutes, seconds, "pm" if hours > 12 else "am") or the string formatting % operator for even older versions of Python, but see the note in the docs: "%02d:%02d:%02d" % (hours, minutes, seconds) And for your specific case of formatting time, there’s time.strftime: import time t = (0, 0, 0, hours, minutes, seconds, 0, 0, 0) time.strftime('%I:%M:%S %p', t)
Format numbers to strings in Python I need to find out how to format numbers as strings. My code is here: return str(hours)+":"+str(minutes)+":"+str(seconds)+" "+ampm Hours and minutes are integers, and seconds is a float. the str() function will convert all of these numbers to the tenths (0.1) place. So instead of my string outputting "5:30:59.07 pm", it would display something like "5.0:30.0:59.1 pm". Bottom line, what library / function do I need to do this for me?
TITLE: Format numbers to strings in Python QUESTION: I need to find out how to format numbers as strings. My code is here: return str(hours)+":"+str(minutes)+":"+str(seconds)+" "+ampm Hours and minutes are integers, and seconds is a float. the str() function will convert all of these numbers to the tenths (0.1) place. So instead of my string outputting "5:30:59.07 pm", it would display something like "5.0:30.0:59.1 pm". Bottom line, what library / function do I need to do this for me? ANSWER: Starting with Python 3.6, formatting in Python can be done using formatted string literals or f-strings: hours, minutes, seconds = 6, 56, 33 f'{hours:02}:{minutes:02}:{seconds:02} {"pm" if hours > 12 else "am"}' or the str.format function starting with 2.7: "{:02}:{:02}:{:02} {}".format(hours, minutes, seconds, "pm" if hours > 12 else "am") or the string formatting % operator for even older versions of Python, but see the note in the docs: "%02d:%02d:%02d" % (hours, minutes, seconds) And for your specific case of formatting time, there’s time.strftime: import time t = (0, 0, 0, hours, minutes, seconds, 0, 0, 0) time.strftime('%I:%M:%S %p', t)
[ "python", "string-formatting" ]
129
156
407,135
9
0
2008-08-22T15:10:46.360000
2008-08-22T15:12:41.613000
22,623
22,628
Best practices for catching and re-throwing .NET exceptions
What are the best practices to consider when catching exceptions and re-throwing them? I want to make sure that the Exception object's InnerException and stack trace are preserved. Is there a difference between the following code blocks in the way they handle this? try { //some code } catch (Exception ex) { throw ex; } Vs: try { //some code } catch { throw; }
The way to preserve the stack trace is through the use of the throw; This is valid as well try { // something that bombs here } catch (Exception ex) { throw; } throw ex; is basically like throwing an exception from that point, so the stack trace would only go to where you are issuing the throw ex; statement. Mike is also correct, assuming the exception allows you to pass an exception (which is recommended). Karl Seguin has a great write up on exception handling in his foundations of programming e-book as well, which is a great read. Edit: Working link to Foundations of Programming pdf. Just search the text for "exception".
Best practices for catching and re-throwing .NET exceptions What are the best practices to consider when catching exceptions and re-throwing them? I want to make sure that the Exception object's InnerException and stack trace are preserved. Is there a difference between the following code blocks in the way they handle this? try { //some code } catch (Exception ex) { throw ex; } Vs: try { //some code } catch { throw; }
TITLE: Best practices for catching and re-throwing .NET exceptions QUESTION: What are the best practices to consider when catching exceptions and re-throwing them? I want to make sure that the Exception object's InnerException and stack trace are preserved. Is there a difference between the following code blocks in the way they handle this? try { //some code } catch (Exception ex) { throw ex; } Vs: try { //some code } catch { throw; } ANSWER: The way to preserve the stack trace is through the use of the throw; This is valid as well try { // something that bombs here } catch (Exception ex) { throw; } throw ex; is basically like throwing an exception from that point, so the stack trace would only go to where you are issuing the throw ex; statement. Mike is also correct, assuming the exception allows you to pass an exception (which is recommended). Karl Seguin has a great write up on exception handling in his foundations of programming e-book as well, which is a great read. Edit: Working link to Foundations of Programming pdf. Just search the text for "exception".
[ "c#", ".net", "exception", "rethrow" ]
310
279
194,304
11
0
2008-08-22T15:12:15.340000
2008-08-22T15:13:25.197000
22,674
22,731
What are the main differences between programming for Windows XP and for Vista?
From a desktop application developer point of view, is there any difference between developing for Windows XP and developing for Windows Vista?
User Interface Looking at the Windows Vista User Experience Guidelines you can see that they have changed many UI elements, which you should be aware of. Some major things to take note of: Larger icons New font (Which affects some custom UI constistency) New dialog box features ( task dialogs ) Altered common dialogs (like File Open, Save As, etc.) Dialog text style and tone, and look and feel New Aero Wizards Redesigned toolbars Better notification UI New recommended method of including a search control Glass 64-bit Vista has a 64-bit edition, and although XP did too, your users are more likely to use Vista 64 than XP 64. Now you have to deal with: Registry virtualization Registry redirection ( Wow6432Node ) Registry reflection Digital signatures for kernel modules MSI installers have new properties to deal with UAC User Account Control vastly affects the default permissions that your application has when interacting with the OS. How UAC works and affects your application (also see the requirements doc ) Installers have to deal with UAC New APIs There are new APIs which are targeted at either new methods of application construction or allowing new functionality: Cryptography API: Next Generation (CNG) Extensible Application Markup Language (XAML) Windows Communication Foundation (WCF) Windows Workflow Foundation (WF) And many more smaller ones Installers Because installations can only use common runtimes they install after a transaction has completed, custom actions will fail if your custom action dll requires the Visual C++ runtimes above the VS 2005 CRT (non-SP1).
What are the main differences between programming for Windows XP and for Vista? From a desktop application developer point of view, is there any difference between developing for Windows XP and developing for Windows Vista?
TITLE: What are the main differences between programming for Windows XP and for Vista? QUESTION: From a desktop application developer point of view, is there any difference between developing for Windows XP and developing for Windows Vista? ANSWER: User Interface Looking at the Windows Vista User Experience Guidelines you can see that they have changed many UI elements, which you should be aware of. Some major things to take note of: Larger icons New font (Which affects some custom UI constistency) New dialog box features ( task dialogs ) Altered common dialogs (like File Open, Save As, etc.) Dialog text style and tone, and look and feel New Aero Wizards Redesigned toolbars Better notification UI New recommended method of including a search control Glass 64-bit Vista has a 64-bit edition, and although XP did too, your users are more likely to use Vista 64 than XP 64. Now you have to deal with: Registry virtualization Registry redirection ( Wow6432Node ) Registry reflection Digital signatures for kernel modules MSI installers have new properties to deal with UAC User Account Control vastly affects the default permissions that your application has when interacting with the OS. How UAC works and affects your application (also see the requirements doc ) Installers have to deal with UAC New APIs There are new APIs which are targeted at either new methods of application construction or allowing new functionality: Cryptography API: Next Generation (CNG) Extensible Application Markup Language (XAML) Windows Communication Foundation (WCF) Windows Workflow Foundation (WF) And many more smaller ones Installers Because installations can only use common runtimes they install after a transaction has completed, custom actions will fail if your custom action dll requires the Visual C++ runtimes above the VS 2005 CRT (non-SP1).
[ "windows-vista", "windows-xp" ]
11
20
2,104
4
0
2008-08-22T15:33:39.097000
2008-08-22T16:02:49.137000
22,676
22,682
How to download a file over HTTP?
I have a small utility that I use to download an MP3 file from a website on a schedule and then builds/updates a podcast XML file which I've added to iTunes. The text processing that creates/updates the XML file is written in Python. However, I use wget inside a Windows.bat file to download the actual MP3 file. I would prefer to have the entire utility written in Python. I struggled to find a way to actually download the file in Python, thus why I resorted to using wget. So, how do I download the file using Python?
Use urllib.request.urlopen(): import urllib.request with urllib.request.urlopen('http://www.example.com/') as f: html = f.read().decode('utf-8') This is the most basic way to use the library, minus any error handling. You can also do more complex stuff such as changing headers. On Python 2, the method is in urllib2: import urllib2 response = urllib2.urlopen('http://www.example.com/') html = response.read()
How to download a file over HTTP? I have a small utility that I use to download an MP3 file from a website on a schedule and then builds/updates a podcast XML file which I've added to iTunes. The text processing that creates/updates the XML file is written in Python. However, I use wget inside a Windows.bat file to download the actual MP3 file. I would prefer to have the entire utility written in Python. I struggled to find a way to actually download the file in Python, thus why I resorted to using wget. So, how do I download the file using Python?
TITLE: How to download a file over HTTP? QUESTION: I have a small utility that I use to download an MP3 file from a website on a schedule and then builds/updates a podcast XML file which I've added to iTunes. The text processing that creates/updates the XML file is written in Python. However, I use wget inside a Windows.bat file to download the actual MP3 file. I would prefer to have the entire utility written in Python. I struggled to find a way to actually download the file in Python, thus why I resorted to using wget. So, how do I download the file using Python? ANSWER: Use urllib.request.urlopen(): import urllib.request with urllib.request.urlopen('http://www.example.com/') as f: html = f.read().decode('utf-8') This is the most basic way to use the library, minus any error handling. You can also do more complex stuff such as changing headers. On Python 2, the method is in urllib2: import urllib2 response = urllib2.urlopen('http://www.example.com/') html = response.read()
[ "python", "http", "urllib" ]
1,155
564
1,575,698
31
0
2008-08-22T15:34:13.760000
2008-08-22T15:38:22.330000
22,687
22,702
Alternative SSH Application to Plink
I have recently started having problems with TortoiseCVS, or more specifically with plink, the SSH application that comes with it. The IP address it tries to connect to can not be changed and is stuck with the old CVS repository's IP. Downloading plink from it's home site and calling from the command line still has this problem. TortoiseCVS has the option to choose the SSH application it uses and I was wondering which other alternatives there are that I can use instead?
For what it's worth, plink is just a command-line version of putty written by the same guy. I think jsight probably has the right idea.
Alternative SSH Application to Plink I have recently started having problems with TortoiseCVS, or more specifically with plink, the SSH application that comes with it. The IP address it tries to connect to can not be changed and is stuck with the old CVS repository's IP. Downloading plink from it's home site and calling from the command line still has this problem. TortoiseCVS has the option to choose the SSH application it uses and I was wondering which other alternatives there are that I can use instead?
TITLE: Alternative SSH Application to Plink QUESTION: I have recently started having problems with TortoiseCVS, or more specifically with plink, the SSH application that comes with it. The IP address it tries to connect to can not be changed and is stuck with the old CVS repository's IP. Downloading plink from it's home site and calling from the command line still has this problem. TortoiseCVS has the option to choose the SSH application it uses and I was wondering which other alternatives there are that I can use instead? ANSWER: For what it's worth, plink is just a command-line version of putty written by the same guy. I think jsight probably has the right idea.
[ "ssh", "cvs", "tortoisecvs", "plink" ]
1
0
11,034
9
0
2008-08-22T15:41:08.157000
2008-08-22T15:48:25.707000
22,694
250,676
Use of 3rd party libraries/components in production
When using 3rd party libraries/components in production projects, are you rigorous about using only released versions of said libraries? When do you consider using a pre-release or beta version of a library (in dev? in production, under certain circumstances)? If you come across a bug or shortcoming of the library and you're already committed to using it, do you apply a patch to the library or create a workaround in your code?
I am a big fan of not coding something when someone else has a version that I could not code in a reasonable amount of time or would require me to become an expert on something that wouldn't matter in the long run. There are several open source components and libraries I have used in our production environment such as Quartz.NET, Log4Net, nLog, SharpFTPLibrary (heavily modified) and more. Quartz.NET was in beta when I first released an application using it into production. It was a very stable beta and I had the source code so I could debug an issue and there were a few. When I encountered a bug or an error I would fix it and post the issue to the bug tracker or author. I feel very comfortable using a beta product if the source is available for me to debug any issues or there is a strong following of developers hammering out any issues.
Use of 3rd party libraries/components in production When using 3rd party libraries/components in production projects, are you rigorous about using only released versions of said libraries? When do you consider using a pre-release or beta version of a library (in dev? in production, under certain circumstances)? If you come across a bug or shortcoming of the library and you're already committed to using it, do you apply a patch to the library or create a workaround in your code?
TITLE: Use of 3rd party libraries/components in production QUESTION: When using 3rd party libraries/components in production projects, are you rigorous about using only released versions of said libraries? When do you consider using a pre-release or beta version of a library (in dev? in production, under certain circumstances)? If you come across a bug or shortcoming of the library and you're already committed to using it, do you apply a patch to the library or create a workaround in your code? ANSWER: I am a big fan of not coding something when someone else has a version that I could not code in a reasonable amount of time or would require me to become an expert on something that wouldn't matter in the long run. There are several open source components and libraries I have used in our production environment such as Quartz.NET, Log4Net, nLog, SharpFTPLibrary (heavily modified) and more. Quartz.NET was in beta when I first released an application using it into production. It was a very stable beta and I had the source code so I could debug an issue and there were a few. When I encountered a bug or an error I would fix it and post the issue to the bug tracker or author. I feel very comfortable using a beta product if the source is available for me to debug any issues or there is a strong following of developers hammering out any issues.
[ "dependency-management" ]
4
2
601
5
0
2008-08-22T15:44:28.603000
2008-10-30T15:44:51.790000
22,697
23,048
What's the best mock framework for Java?
What's the best framework for creating mock objects in Java? Why? What are the pros and cons of each framework?
I've had good success using Mockito. When I tried learning about JMock and EasyMock, I found the learning curve to be a bit steep (though maybe that's just me). I like Mockito because of its simple and clean syntax that I was able to grasp pretty quickly. The minimal syntax is designed to support the common cases very well, although the few times I needed to do something more complicated I found what I wanted was supported and easy to grasp. Here's an (abridged) example from the Mockito homepage: import static org.mockito.Mockito.*; List mockedList = mock(List.class); mockedList.clear(); verify(mockedList).clear(); It doesn't get much simpler than that. The only major downside I can think of is that it won't mock static methods.
What's the best mock framework for Java? What's the best framework for creating mock objects in Java? Why? What are the pros and cons of each framework?
TITLE: What's the best mock framework for Java? QUESTION: What's the best framework for creating mock objects in Java? Why? What are the pros and cons of each framework? ANSWER: I've had good success using Mockito. When I tried learning about JMock and EasyMock, I found the learning curve to be a bit steep (though maybe that's just me). I like Mockito because of its simple and clean syntax that I was able to grasp pretty quickly. The minimal syntax is designed to support the common cases very well, although the few times I needed to do something more complicated I found what I wanted was supported and easy to grasp. Here's an (abridged) example from the Mockito homepage: import static org.mockito.Mockito.*; List mockedList = mock(List.class); mockedList.clear(); verify(mockedList).clear(); It doesn't get much simpler than that. The only major downside I can think of is that it won't mock static methods.
[ "java", "unit-testing", "mocking" ]
347
314
221,088
14
0
2008-08-22T15:45:11.423000
2008-08-22T18:02:30.267000
22,704
22,722
What strategies have you employed to improve web application performance?
Any personal experience in overcoming web application performance hurdles? Any recommended strategies for improving the performance of a data-driven web application? My development team works on a web application (JSP reports, HTML, JavaScript) that uses an Oracle database (PL/SQL). The key functionality the application delivers is in reporting, where a user can get PDFs of reports at a high level and drill down to lower levels of supporting details. As the number of supporting detail records has grown into the millions, the performance of the system has significantly degraded. Based on our current analysis of the metrics, the bottleneck seems to be in the logic hitting the DB and the DB performance. Changing the DB model and re-doing some of the server side logic is currently being explored. Partioning, indexing, explain plans, and running statistics are things that have been done on the DB side to try to help improve performance. While they've helped, they haven't solved the issue satisfactorily. The toughest part in analyzing performance data is that the database and web servers are remotely administered by a different part of the IT organization, so the developers don't have regular, full access to see what's going on (especially in the production environment, which is not mirrored exactly in any other development/testing environment).
While my answer may not contain any concrete steps to help this is always where I start. First thing I would do is try to throw away all of your assumptions about what the trouble is and take steps to install metrics everywhere you can. Let the metrics guide you rather than your intuition. I've chased many, many, many white rabbits going on a hunch...the let me down more times than they've been right.
What strategies have you employed to improve web application performance? Any personal experience in overcoming web application performance hurdles? Any recommended strategies for improving the performance of a data-driven web application? My development team works on a web application (JSP reports, HTML, JavaScript) that uses an Oracle database (PL/SQL). The key functionality the application delivers is in reporting, where a user can get PDFs of reports at a high level and drill down to lower levels of supporting details. As the number of supporting detail records has grown into the millions, the performance of the system has significantly degraded. Based on our current analysis of the metrics, the bottleneck seems to be in the logic hitting the DB and the DB performance. Changing the DB model and re-doing some of the server side logic is currently being explored. Partioning, indexing, explain plans, and running statistics are things that have been done on the DB side to try to help improve performance. While they've helped, they haven't solved the issue satisfactorily. The toughest part in analyzing performance data is that the database and web servers are remotely administered by a different part of the IT organization, so the developers don't have regular, full access to see what's going on (especially in the production environment, which is not mirrored exactly in any other development/testing environment).
TITLE: What strategies have you employed to improve web application performance? QUESTION: Any personal experience in overcoming web application performance hurdles? Any recommended strategies for improving the performance of a data-driven web application? My development team works on a web application (JSP reports, HTML, JavaScript) that uses an Oracle database (PL/SQL). The key functionality the application delivers is in reporting, where a user can get PDFs of reports at a high level and drill down to lower levels of supporting details. As the number of supporting detail records has grown into the millions, the performance of the system has significantly degraded. Based on our current analysis of the metrics, the bottleneck seems to be in the logic hitting the DB and the DB performance. Changing the DB model and re-doing some of the server side logic is currently being explored. Partioning, indexing, explain plans, and running statistics are things that have been done on the DB side to try to help improve performance. While they've helped, they haven't solved the issue satisfactorily. The toughest part in analyzing performance data is that the database and web servers are remotely administered by a different part of the IT organization, so the developers don't have regular, full access to see what's going on (especially in the production environment, which is not mirrored exactly in any other development/testing environment). ANSWER: While my answer may not contain any concrete steps to help this is always where I start. First thing I would do is try to throw away all of your assumptions about what the trouble is and take steps to install metrics everywhere you can. Let the metrics guide you rather than your intuition. I've chased many, many, many white rabbits going on a hunch...the let me down more times than they've been right.
[ "performance", "oracle", "web-applications" ]
2
6
593
6
0
2008-08-22T15:48:44.490000
2008-08-22T15:58:41.987000
22,708
22,715
How do I find the Excel column name that corresponds to a given integer?
How would you determine the column name (e.g. "AQ" or "BH") of the nth column in Excel? Edit: A language-agnostic algorithm to determine this is the main goal here.
I once wrote this function to perform that exact task: public static string Column(int column) { column--; if (column >= 0 && column < 26) return ((char)('A' + column)).ToString(); else if (column > 25) return Column(column / 26) + Column(column % 26 + 1); else throw new Exception("Invalid Column #" + (column + 1).ToString()); }
How do I find the Excel column name that corresponds to a given integer? How would you determine the column name (e.g. "AQ" or "BH") of the nth column in Excel? Edit: A language-agnostic algorithm to determine this is the main goal here.
TITLE: How do I find the Excel column name that corresponds to a given integer? QUESTION: How would you determine the column name (e.g. "AQ" or "BH") of the nth column in Excel? Edit: A language-agnostic algorithm to determine this is the main goal here. ANSWER: I once wrote this function to perform that exact task: public static string Column(int column) { column--; if (column >= 0 && column < 26) return ((char)('A' + column)).ToString(); else if (column > 25) return Column(column / 26) + Column(column % 26 + 1); else throw new Exception("Invalid Column #" + (column + 1).ToString()); }
[ "algorithm", "excel", "language-agnostic" ]
34
45
60,656
20
0
2008-08-22T15:49:53.380000
2008-08-22T15:53:47.503000
22,720
22,803
Configure a Java Socket to fail-fast on disconnect?
I have a listening port on my server that I'm connecting to using a Java class and the Socket interface, i.e. Socket mySocket = new Socket(host,port); I then grab an OutputStream, decorate with a PrintWriter in autoflush mode and I'm laughing - except if the listening port closes. Then I get tcp4 0 0 *.9999 *.* LISTEN tcp 0 0 127.0.0.1.45737 127.0.0.1.9999 CLOSE_WAIT and I can't seem to detect the problem in the program - I've tried using the isConnected() method on the socket but it doesn't seem to know that the connection is closed. I want to be aware of the problem the next time I try and write to the Socket so that I can try and reconnect and report the issue. Any advice please? Thanks all
Set a short timeout? Does isOutputShutdown() not get you what you want? You could always build a SocketWatcher class that spins up in its own Thread and repeatedly tries to write empty strings to the Socket until that raises a SocketClosedException.
Configure a Java Socket to fail-fast on disconnect? I have a listening port on my server that I'm connecting to using a Java class and the Socket interface, i.e. Socket mySocket = new Socket(host,port); I then grab an OutputStream, decorate with a PrintWriter in autoflush mode and I'm laughing - except if the listening port closes. Then I get tcp4 0 0 *.9999 *.* LISTEN tcp 0 0 127.0.0.1.45737 127.0.0.1.9999 CLOSE_WAIT and I can't seem to detect the problem in the program - I've tried using the isConnected() method on the socket but it doesn't seem to know that the connection is closed. I want to be aware of the problem the next time I try and write to the Socket so that I can try and reconnect and report the issue. Any advice please? Thanks all
TITLE: Configure a Java Socket to fail-fast on disconnect? QUESTION: I have a listening port on my server that I'm connecting to using a Java class and the Socket interface, i.e. Socket mySocket = new Socket(host,port); I then grab an OutputStream, decorate with a PrintWriter in autoflush mode and I'm laughing - except if the listening port closes. Then I get tcp4 0 0 *.9999 *.* LISTEN tcp 0 0 127.0.0.1.45737 127.0.0.1.9999 CLOSE_WAIT and I can't seem to detect the problem in the program - I've tried using the isConnected() method on the socket but it doesn't seem to know that the connection is closed. I want to be aware of the problem the next time I try and write to the Socket so that I can try and reconnect and report the issue. Any advice please? Thanks all ANSWER: Set a short timeout? Does isOutputShutdown() not get you what you want? You could always build a SocketWatcher class that spins up in its own Thread and repeatedly tries to write empty strings to the Socket until that raises a SocketClosedException.
[ "java", "exception", "sockets", "networking" ]
4
1
3,062
3
0
2008-08-22T15:58:13.077000
2008-08-22T16:33:13.820000
22,732
22,770
How do I pass multiple string parameters to a PowerShell script?
I am trying to do some string concatenation/formatting, but it's putting all the parameters into the first placeholder. Code function CreateAppPoolScript([string]$AppPoolName, [string]$AppPoolUser, [string]$AppPoolPass) { # Command to create an IIS application pool $AppPoolScript = "cscript adsutil.vbs CREATE ""w3svc/AppPools/$AppPoolName"" IIsApplicationPool`n" $AppPoolScript += "cscript adsutil.vbs SET ""w3svc/AppPools/$AppPoolName/WamUserName"" ""$AppPoolUser""`n" $AppPoolScript += "cscript adsutil.vbs SET ""w3svc/AppPools/$AppPoolName/WamUserPass"" ""$AppPoolPass""`n" $AppPoolScript += "cscript adsutil.vbs SET ""w3svc/AppPools/$AppPoolName/AppPoolIdentityType"" 3" return $AppPoolScript } $s = CreateAppPoolScript("name", "user", "pass") write-host $s Output cscript adsutil.vbs CREATE "w3svc/AppPools/name user pass" IIsApplicationPool cscript adsutil.vbs SET "w3svc/AppPools/name user pass/WamUserName" "" cscript adsutil.vbs SET "w3svc/AppPools/name user pass/WamUserPass" "" cscript adsutil.vbs SET "w3svc/AppPools/name user pass/AppPoolIdentityType" 3
Lose the parentheses and commas. Calling your function as: $s = CreateAppPoolScript "name" "user" "pass" gives: cscript adsutil.vbs CREATE "w3svc/AppPools/name" IIsApplicationPool cscript adsutil.vbs SET "w3svc/AppPools/name/WamUserName" "user" cscript adsutil.vbs SET "w3svc/AppPools/name/WamUserPass" "pass" cscript adsutil.vbs SET "w3svc/AppPools/name/AppPoolIdentityType" 3
How do I pass multiple string parameters to a PowerShell script? I am trying to do some string concatenation/formatting, but it's putting all the parameters into the first placeholder. Code function CreateAppPoolScript([string]$AppPoolName, [string]$AppPoolUser, [string]$AppPoolPass) { # Command to create an IIS application pool $AppPoolScript = "cscript adsutil.vbs CREATE ""w3svc/AppPools/$AppPoolName"" IIsApplicationPool`n" $AppPoolScript += "cscript adsutil.vbs SET ""w3svc/AppPools/$AppPoolName/WamUserName"" ""$AppPoolUser""`n" $AppPoolScript += "cscript adsutil.vbs SET ""w3svc/AppPools/$AppPoolName/WamUserPass"" ""$AppPoolPass""`n" $AppPoolScript += "cscript adsutil.vbs SET ""w3svc/AppPools/$AppPoolName/AppPoolIdentityType"" 3" return $AppPoolScript } $s = CreateAppPoolScript("name", "user", "pass") write-host $s Output cscript adsutil.vbs CREATE "w3svc/AppPools/name user pass" IIsApplicationPool cscript adsutil.vbs SET "w3svc/AppPools/name user pass/WamUserName" "" cscript adsutil.vbs SET "w3svc/AppPools/name user pass/WamUserPass" "" cscript adsutil.vbs SET "w3svc/AppPools/name user pass/AppPoolIdentityType" 3
TITLE: How do I pass multiple string parameters to a PowerShell script? QUESTION: I am trying to do some string concatenation/formatting, but it's putting all the parameters into the first placeholder. Code function CreateAppPoolScript([string]$AppPoolName, [string]$AppPoolUser, [string]$AppPoolPass) { # Command to create an IIS application pool $AppPoolScript = "cscript adsutil.vbs CREATE ""w3svc/AppPools/$AppPoolName"" IIsApplicationPool`n" $AppPoolScript += "cscript adsutil.vbs SET ""w3svc/AppPools/$AppPoolName/WamUserName"" ""$AppPoolUser""`n" $AppPoolScript += "cscript adsutil.vbs SET ""w3svc/AppPools/$AppPoolName/WamUserPass"" ""$AppPoolPass""`n" $AppPoolScript += "cscript adsutil.vbs SET ""w3svc/AppPools/$AppPoolName/AppPoolIdentityType"" 3" return $AppPoolScript } $s = CreateAppPoolScript("name", "user", "pass") write-host $s Output cscript adsutil.vbs CREATE "w3svc/AppPools/name user pass" IIsApplicationPool cscript adsutil.vbs SET "w3svc/AppPools/name user pass/WamUserName" "" cscript adsutil.vbs SET "w3svc/AppPools/name user pass/WamUserPass" "" cscript adsutil.vbs SET "w3svc/AppPools/name user pass/AppPoolIdentityType" 3 ANSWER: Lose the parentheses and commas. Calling your function as: $s = CreateAppPoolScript "name" "user" "pass" gives: cscript adsutil.vbs CREATE "w3svc/AppPools/name" IIsApplicationPool cscript adsutil.vbs SET "w3svc/AppPools/name/WamUserName" "user" cscript adsutil.vbs SET "w3svc/AppPools/name/WamUserPass" "pass" cscript adsutil.vbs SET "w3svc/AppPools/name/AppPoolIdentityType" 3
[ "string", "powershell", "parameters", "arguments" ]
35
52
79,354
3
0
2008-08-22T16:03:00.227000
2008-08-22T16:15:03.320000
22,764
1,434,830
How does Ruby 1.9 handle character cases in source code?
In Ruby 1.8 and earlier, Foo is a constant (a Class, a Module, or another constant). Whereas foo is a variable. The key difference is as follows: module Foo bar = 7 BAZ = 8 end Foo::BAZ # => 8 Foo::bar # NoMethodError: undefined method 'bar' for Foo:Module That's all well and good, but Ruby 1.9 allows UTF-8 source code. So is ℃ "uppercase" or "lowecase" as far as this is concerned? What about ⊂ (strict subset) or Ɖfoo? Is there a general rule? Later: Ruby-core is already considering some of the mathematical operators. For example module Kernel def √(num)... end def ∑(*args)... end end would allow x = √2 y = ∑(1, 45,...) I would love to see my_proc = λ { |...|... } x ∈ my_enumerable # same as my_enumerable.include?(x) my_infinite_range = (1..∞) return 'foo' if x ≠ y 2.21 ≈ 2.2
I can't get IRB to accept UTF-8 characters, so I used a test script ( /tmp/utf_test.rb ). "λ" works fine as a variable name: # encoding: UTF-8 λ = 'foo' puts λ # from the command line: > ruby -KU /tmp/utf_test.rb foo "λ" also works fine as a method name: # encoding: UTF-8 Kernel.class_eval do alias_method:λ,:lambda end (λ { puts 'hi' }).call # from the command line: > ruby -KU /tmp/utf_test.rb: hi It doesn't work as a constant, though: # encoding: UTF-8 Object.const_set:λ, 'bar' # from the command line: > ruby -KU /tmp/utf_test.rb: utf_test.rb:2:in `const_set': wrong constant name λ (NameError) Nor does the capitalized version: # encoding: UTF-8 Object.const_set:Λ, 'bar' # from the command line: > ruby -KU /tmp/utf_test.rb: utf_test.rb:2:in `const_set': wrong constant name Λ (NameError) My suspicion is that constant names must start with a capital ASCII letter (must match /^[A-Z]/ ).
How does Ruby 1.9 handle character cases in source code? In Ruby 1.8 and earlier, Foo is a constant (a Class, a Module, or another constant). Whereas foo is a variable. The key difference is as follows: module Foo bar = 7 BAZ = 8 end Foo::BAZ # => 8 Foo::bar # NoMethodError: undefined method 'bar' for Foo:Module That's all well and good, but Ruby 1.9 allows UTF-8 source code. So is ℃ "uppercase" or "lowecase" as far as this is concerned? What about ⊂ (strict subset) or Ɖfoo? Is there a general rule? Later: Ruby-core is already considering some of the mathematical operators. For example module Kernel def √(num)... end def ∑(*args)... end end would allow x = √2 y = ∑(1, 45,...) I would love to see my_proc = λ { |...|... } x ∈ my_enumerable # same as my_enumerable.include?(x) my_infinite_range = (1..∞) return 'foo' if x ≠ y 2.21 ≈ 2.2
TITLE: How does Ruby 1.9 handle character cases in source code? QUESTION: In Ruby 1.8 and earlier, Foo is a constant (a Class, a Module, or another constant). Whereas foo is a variable. The key difference is as follows: module Foo bar = 7 BAZ = 8 end Foo::BAZ # => 8 Foo::bar # NoMethodError: undefined method 'bar' for Foo:Module That's all well and good, but Ruby 1.9 allows UTF-8 source code. So is ℃ "uppercase" or "lowecase" as far as this is concerned? What about ⊂ (strict subset) or Ɖfoo? Is there a general rule? Later: Ruby-core is already considering some of the mathematical operators. For example module Kernel def √(num)... end def ∑(*args)... end end would allow x = √2 y = ∑(1, 45,...) I would love to see my_proc = λ { |...|... } x ∈ my_enumerable # same as my_enumerable.include?(x) my_infinite_range = (1..∞) return 'foo' if x ≠ y 2.21 ≈ 2.2 ANSWER: I can't get IRB to accept UTF-8 characters, so I used a test script ( /tmp/utf_test.rb ). "λ" works fine as a variable name: # encoding: UTF-8 λ = 'foo' puts λ # from the command line: > ruby -KU /tmp/utf_test.rb foo "λ" also works fine as a method name: # encoding: UTF-8 Kernel.class_eval do alias_method:λ,:lambda end (λ { puts 'hi' }).call # from the command line: > ruby -KU /tmp/utf_test.rb: hi It doesn't work as a constant, though: # encoding: UTF-8 Object.const_set:λ, 'bar' # from the command line: > ruby -KU /tmp/utf_test.rb: utf_test.rb:2:in `const_set': wrong constant name λ (NameError) Nor does the capitalized version: # encoding: UTF-8 Object.const_set:Λ, 'bar' # from the command line: > ruby -KU /tmp/utf_test.rb: utf_test.rb:2:in `const_set': wrong constant name Λ (NameError) My suspicion is that constant names must start with a capital ASCII letter (must match /^[A-Z]/ ).
[ "ruby", "encoding", "utf-8" ]
5
0
1,788
5
0
2008-08-22T16:09:50.070000
2009-09-16T18:54:35.850000
22,779
22,800
Is GDI+ actually still a "usable" technology?
I just wonder a bit whether or not GDI+ is still a technology worth using, especially in a.net sense. Granted, GDI+ is still THE technology to handle Images in Windows, but it is also unmanaged code (obviously). Now, after discovering that GDI+ is actually not supported on ASP.net¹, I just wonder: Is it actually feasible to have Image Manipulation Libraries that run completely in Managed Code? XNA does it if i remember correctly, albeit it uses the graphics card for it. Is there maybe even any.net Image Library that implements a sort of managed GDI+? ¹ Source, also Microsoft just offered something for ASP.net that uses GDI+.
It's still a technology worth using. There are lots of Windows Forms and unmanaged apps around that use GDI+ that either won't be upgraded, or that will be upgraded, but that don't need more advanced rendering capabilities. GDI+ is a good bolt-on solution for older applications, and for new applications written in Windows Forsm. That's the primary reason GDI+ wasn't axed in Vista in favour of a totally DirectX solution. There's not specifically anything wrong with GDI/GDI+. True, it's not as advanced as Aero et al, but that doesn't always matter. Particularly in LOB applications (in companies that probably don't even have machines capable of running Vista - mine certainly doesn't), GDI+ is an extremely important technology. The fact that it's not supported (for drawing, at least... you CAN still use it for image manipulation) in ASP.NET is a red herring, since other drawing technologies are not supported for web applications either (plugin-based "applications" notwithstanding).
Is GDI+ actually still a "usable" technology? I just wonder a bit whether or not GDI+ is still a technology worth using, especially in a.net sense. Granted, GDI+ is still THE technology to handle Images in Windows, but it is also unmanaged code (obviously). Now, after discovering that GDI+ is actually not supported on ASP.net¹, I just wonder: Is it actually feasible to have Image Manipulation Libraries that run completely in Managed Code? XNA does it if i remember correctly, albeit it uses the graphics card for it. Is there maybe even any.net Image Library that implements a sort of managed GDI+? ¹ Source, also Microsoft just offered something for ASP.net that uses GDI+.
TITLE: Is GDI+ actually still a "usable" technology? QUESTION: I just wonder a bit whether or not GDI+ is still a technology worth using, especially in a.net sense. Granted, GDI+ is still THE technology to handle Images in Windows, but it is also unmanaged code (obviously). Now, after discovering that GDI+ is actually not supported on ASP.net¹, I just wonder: Is it actually feasible to have Image Manipulation Libraries that run completely in Managed Code? XNA does it if i remember correctly, albeit it uses the graphics card for it. Is there maybe even any.net Image Library that implements a sort of managed GDI+? ¹ Source, also Microsoft just offered something for ASP.net that uses GDI+. ANSWER: It's still a technology worth using. There are lots of Windows Forms and unmanaged apps around that use GDI+ that either won't be upgraded, or that will be upgraded, but that don't need more advanced rendering capabilities. GDI+ is a good bolt-on solution for older applications, and for new applications written in Windows Forsm. That's the primary reason GDI+ wasn't axed in Vista in favour of a totally DirectX solution. There's not specifically anything wrong with GDI/GDI+. True, it's not as advanced as Aero et al, but that doesn't always matter. Particularly in LOB applications (in companies that probably don't even have machines capable of running Vista - mine certainly doesn't), GDI+ is an extremely important technology. The fact that it's not supported (for drawing, at least... you CAN still use it for image manipulation) in ASP.NET is a red herring, since other drawing technologies are not supported for web applications either (plugin-based "applications" notwithstanding).
[ ".net", "gdi+" ]
4
5
1,652
5
0
2008-08-22T16:20:55.287000
2008-08-22T16:32:04.557000
22,792
546,633
Is there an open source SQL Server DB compare tool?
I'm working on an open source project that uses SQL Server 2005 as the data store. We need a DB compare tool to generate diff scripts to be able to upgrade a DB from one version to another. Is there an open source or free SQL Server DB diff tool out there that generates a convert script?
I think that Open DBiff does a good job. It's simple and I works with SQL Server 2005/2008. But only generate the change script. Nothing more and nothing less.
Is there an open source SQL Server DB compare tool? I'm working on an open source project that uses SQL Server 2005 as the data store. We need a DB compare tool to generate diff scripts to be able to upgrade a DB from one version to another. Is there an open source or free SQL Server DB diff tool out there that generates a convert script?
TITLE: Is there an open source SQL Server DB compare tool? QUESTION: I'm working on an open source project that uses SQL Server 2005 as the data store. We need a DB compare tool to generate diff scripts to be able to upgrade a DB from one version to another. Is there an open source or free SQL Server DB diff tool out there that generates a convert script? ANSWER: I think that Open DBiff does a good job. It's simple and I works with SQL Server 2005/2008. But only generate the change script. Nothing more and nothing less.
[ "sql-server", "sql-server-2005", "compare" ]
42
17
25,579
12
0
2008-08-22T16:26:31.170000
2009-02-13T16:36:40.773000
22,798
4,788,050
Drag and Drop an Email from MS Outlook to Eclipse RCP
Has anyone got a working solution without some Java/COM-bridge? E.g. process the Email as a file (.msg) rather than locating the data that is referenced in the Clipboard?
Maybe this is a solution for your problem: http://sourceforge.net/projects/javaoutlookdd/ It allows to handle outlook items like File objects during drag&drop.
Drag and Drop an Email from MS Outlook to Eclipse RCP Has anyone got a working solution without some Java/COM-bridge? E.g. process the Email as a file (.msg) rather than locating the data that is referenced in the Clipboard?
TITLE: Drag and Drop an Email from MS Outlook to Eclipse RCP QUESTION: Has anyone got a working solution without some Java/COM-bridge? E.g. process the Email as a file (.msg) rather than locating the data that is referenced in the Clipboard? ANSWER: Maybe this is a solution for your problem: http://sourceforge.net/projects/javaoutlookdd/ It allows to handle outlook items like File objects during drag&drop.
[ "java", "eclipse", "ms-office", "integration", "desktop" ]
4
2
3,408
3
0
2008-08-22T16:30:20.117000
2011-01-24T22:39:12.187000
22,801
23,835
The difference between loops
It's about PHP but I've no doubt many of the same comments will apply to other languages. Simply put, what are the differences in the different types of loop for PHP? Is one faster/better than the others or should I simply put in the most readable loop? for ($i = 0; $i < 10; $i++) { # code... } foreach ($array as $index => $value) { # code... } do { # code... } while ($flag == false);
For loop and While loops are entry condition loops. They evaluate condition first, so the statement block associated with the loop won't run even once if the condition fails to meet The statements inside this for loop block will run 10 times, the value of $i will be 0 to 9; for ($i = 0; $i < 10; $i++) { # code... } Same thing done with while loop: $i = 0; while ($i < 10) { # code... $i++ } Do-while loop is exit-condition loop. It's guaranteed to execute once, then it will evaluate condition before repeating the block do { # code... } while ($flag == false); foreach is used to access array elements from start to end. At the beginning of foreach loop, the internal pointer of the array is set to the first element of the array, in next step it is set to the 2nd element of the array and so on till the array ends. In the loop block The value of current array item is available as $value and the key of current item is available as $index. foreach ($array as $index => $value) { # code... } You could do the same thing with while loop, like this while (current($array)) { $index = key($array); // to get key of the current element $value = $array[$index]; // to get value of current element # code... next($array); // advance the internal array pointer of $array } And lastly: The PHP Manual is your friend:)
The difference between loops It's about PHP but I've no doubt many of the same comments will apply to other languages. Simply put, what are the differences in the different types of loop for PHP? Is one faster/better than the others or should I simply put in the most readable loop? for ($i = 0; $i < 10; $i++) { # code... } foreach ($array as $index => $value) { # code... } do { # code... } while ($flag == false);
TITLE: The difference between loops QUESTION: It's about PHP but I've no doubt many of the same comments will apply to other languages. Simply put, what are the differences in the different types of loop for PHP? Is one faster/better than the others or should I simply put in the most readable loop? for ($i = 0; $i < 10; $i++) { # code... } foreach ($array as $index => $value) { # code... } do { # code... } while ($flag == false); ANSWER: For loop and While loops are entry condition loops. They evaluate condition first, so the statement block associated with the loop won't run even once if the condition fails to meet The statements inside this for loop block will run 10 times, the value of $i will be 0 to 9; for ($i = 0; $i < 10; $i++) { # code... } Same thing done with while loop: $i = 0; while ($i < 10) { # code... $i++ } Do-while loop is exit-condition loop. It's guaranteed to execute once, then it will evaluate condition before repeating the block do { # code... } while ($flag == false); foreach is used to access array elements from start to end. At the beginning of foreach loop, the internal pointer of the array is set to the first element of the array, in next step it is set to the 2nd element of the array and so on till the array ends. In the loop block The value of current array item is available as $value and the key of current item is available as $index. foreach ($array as $index => $value) { # code... } You could do the same thing with while loop, like this while (current($array)) { $index = key($array); // to get key of the current element $value = $array[$index]; // to get value of current element # code... next($array); // advance the internal array pointer of $array } And lastly: The PHP Manual is your friend:)
[ "php", "loops" ]
6
11
2,323
11
0
2008-08-22T16:32:33.153000
2008-08-23T01:44:16.553000
22,814
22,819
How to decode viewstate
I need to see the contents of the viewstate of an asp.net page. I looked for a viewstate decoder, found Fridz Onion's ViewState Decoder but it asks for the url of a page to get its viewstate. Since my viewstate is formed after a postback and comes as a result of an operation in an update panel, I cannot provide a url. I need to copy & paste the viewstate string and see what's inside. Is there a tool or a website exist that can help viewing the contents of viewstate?
Use Fiddler and grab the view state in the response and paste it into the bottom left text box then decode.
How to decode viewstate I need to see the contents of the viewstate of an asp.net page. I looked for a viewstate decoder, found Fridz Onion's ViewState Decoder but it asks for the url of a page to get its viewstate. Since my viewstate is formed after a postback and comes as a result of an operation in an update panel, I cannot provide a url. I need to copy & paste the viewstate string and see what's inside. Is there a tool or a website exist that can help viewing the contents of viewstate?
TITLE: How to decode viewstate QUESTION: I need to see the contents of the viewstate of an asp.net page. I looked for a viewstate decoder, found Fridz Onion's ViewState Decoder but it asks for the url of a page to get its viewstate. Since my viewstate is formed after a postback and comes as a result of an operation in an update panel, I cannot provide a url. I need to copy & paste the viewstate string and see what's inside. Is there a tool or a website exist that can help viewing the contents of viewstate? ANSWER: Use Fiddler and grab the view state in the response and paste it into the bottom left text box then decode.
[ "asp.net", "viewstate" ]
63
40
121,244
11
0
2008-08-22T16:38:49.407000
2008-08-22T16:40:16.457000
22,816
43,112
Libraries for pretty charts in SWT?
I know the following libraries for drawing charts in an SWT/Eclipse RCP application: Eclipse BIRT Chart Engine (Links to an article on how to use it) JFreeChart Which other libraries are there for drawing pretty charts with SWT? Or charts in Java generally? After all, you can always display an image...
I have not used BIRT or JGraph, however I use JFreeChart in my SWT application. I have found the best way to use JFreeChart in SWT is by making a composite an AWT frame and using the AWT functionality for JFreeChart. The way to do this is by creating a composite Composite comp = new Composite(parent, SWT.NONE | SWT.EMBEDDED); Frame frame = SWT_AWT.new_Frame(comp); JFreeChart chart = createChart(); ChartPanel chartPanel = new ChartPanel(chart); frame.add(chartPanel); There are several problems in regards to implementations across different platforms as well as the SWT code in it is very poor (in its defense Mr. Gilbert does not know SWT well and it is made for AWT). My two biggest problems are as AWT events bubble up through SWT there are some erroneous events fired and due to wrapping the AWT frame JFreeChart becomes substantially slower. @zvikico The idea of putting the chart into a web page is probably not a great way to go. There are a few problems first being how Eclipse handles integrating the web browser on different platforms is inconsistent. Also from my understanding of a few graphing packages for the web they are server side requiring that setup, also many companies including mine use proxy servers and sometimes this creates issues with the Eclipse web browsing.
Libraries for pretty charts in SWT? I know the following libraries for drawing charts in an SWT/Eclipse RCP application: Eclipse BIRT Chart Engine (Links to an article on how to use it) JFreeChart Which other libraries are there for drawing pretty charts with SWT? Or charts in Java generally? After all, you can always display an image...
TITLE: Libraries for pretty charts in SWT? QUESTION: I know the following libraries for drawing charts in an SWT/Eclipse RCP application: Eclipse BIRT Chart Engine (Links to an article on how to use it) JFreeChart Which other libraries are there for drawing pretty charts with SWT? Or charts in Java generally? After all, you can always display an image... ANSWER: I have not used BIRT or JGraph, however I use JFreeChart in my SWT application. I have found the best way to use JFreeChart in SWT is by making a composite an AWT frame and using the AWT functionality for JFreeChart. The way to do this is by creating a composite Composite comp = new Composite(parent, SWT.NONE | SWT.EMBEDDED); Frame frame = SWT_AWT.new_Frame(comp); JFreeChart chart = createChart(); ChartPanel chartPanel = new ChartPanel(chart); frame.add(chartPanel); There are several problems in regards to implementations across different platforms as well as the SWT code in it is very poor (in its defense Mr. Gilbert does not know SWT well and it is made for AWT). My two biggest problems are as AWT events bubble up through SWT there are some erroneous events fired and due to wrapping the AWT frame JFreeChart becomes substantially slower. @zvikico The idea of putting the chart into a web page is probably not a great way to go. There are a few problems first being how Eclipse handles integrating the web browser on different platforms is inconsistent. Also from my understanding of a few graphing packages for the web they are server side requiring that setup, also many companies including mine use proxy servers and sometimes this creates issues with the Eclipse web browsing.
[ "java", "eclipse", "charts", "swt" ]
18
11
17,099
11
0
2008-08-22T16:39:15.927000
2008-09-04T02:59:33.220000
22,836
22,896
How do I perform a Perl substitution on a string while keeping the original?
In Perl, what is a good way to perform a replacement on a string using a regular expression and store the value in a different variable, without changing the original? I usually just copy the string to a new variable then bind it to the s/// regex that does the replacement on the new string, but I was wondering if there is a better way to do this? $newstring = $oldstring; $newstring =~ s/foo/bar/g;
This is the idiom I've always used to get a modified copy of a string without changing the original: (my $newstring = $oldstring) =~ s/foo/bar/g; In perl 5.14.0 or later, you can use the new /r non-destructive substitution modifier: my $newstring = $oldstring =~ s/foo/bar/gr; NOTE: The above solutions work without g too. They also work with any other modifiers. SEE ALSO: perldoc perlrequick: Perl regular expressions quick start
How do I perform a Perl substitution on a string while keeping the original? In Perl, what is a good way to perform a replacement on a string using a regular expression and store the value in a different variable, without changing the original? I usually just copy the string to a new variable then bind it to the s/// regex that does the replacement on the new string, but I was wondering if there is a better way to do this? $newstring = $oldstring; $newstring =~ s/foo/bar/g;
TITLE: How do I perform a Perl substitution on a string while keeping the original? QUESTION: In Perl, what is a good way to perform a replacement on a string using a regular expression and store the value in a different variable, without changing the original? I usually just copy the string to a new variable then bind it to the s/// regex that does the replacement on the new string, but I was wondering if there is a better way to do this? $newstring = $oldstring; $newstring =~ s/foo/bar/g; ANSWER: This is the idiom I've always used to get a modified copy of a string without changing the original: (my $newstring = $oldstring) =~ s/foo/bar/g; In perl 5.14.0 or later, you can use the new /r non-destructive substitution modifier: my $newstring = $oldstring =~ s/foo/bar/gr; NOTE: The above solutions work without g too. They also work with any other modifiers. SEE ALSO: perldoc perlrequick: Perl regular expressions quick start
[ "regex", "perl", "replace" ]
212
300
248,371
8
0
2008-08-22T16:47:55.597000
2008-08-22T17:08:29.197000
22,869
22,966
ASP.NET - Building your own routing system
In a recent project, I built my own MVC framework in PHP. One of the things I implemented was a routing system. I used Apache's mod_rewrite to send all requests to index.php, and then parsed the URI to extract information and route the request. I'm dabbling in ASP.NET now, and I'm wondering if/how I might perform something similar. Is there a way to route all requests (similar to the way WordPress does it) to one page where central route processing is performed? I'm aware of the MVC framework for ASP.NET, but I'd like to take a stab at this myself as I'm tinkering around and learning. EDIT: BTW, my hosting provider runs IIS 6
This is going to be a long answer, because I want to make sure you are fully aware of all the ways you can accomplish what you want to do. The routing engine that powers the ASP.NET MVC Framework will work with the traditional ASP.NET Framework. You can take advantage of using the RouteTable and assigning routes, just like you would in an ASP.NET MVC application. You just don't get the MVC portion in traditional ASP.NET sites. That was a huge enhancement for the ASP.NET Framework and it was great to see them reuse that code and make it work in both frameworks. If you want to learn more about this, check out ScottGu's post and scroll down to URL Routing Improvements. Also here is a reference on how to use the System.Web.Routing in WebForms by Phil Haack. Now, if you still want to write you own. You will need to learn the ASP.NET HTTP pipeline and how to implement the IHttpModule and the IHttpHandler interfaces to create your own HttpModule or HttpHandler class to handle your routing. These interfaces are the key in writing your own routing engine. To help put those interfaces in a working example, I couldn't recommend this MSDN article enough. It shows you how to with either interface and explains the differences when creating your own routing/url rewriting engine. Now, if you find out that this might be to much for you. There are third party libraries you can use of people who already wrote a routing/url rewriting engine in.NET. Here is a question that I saw not to long ago asking " What Url rewriter do you use for ASP.Net? " right here on SO.
ASP.NET - Building your own routing system In a recent project, I built my own MVC framework in PHP. One of the things I implemented was a routing system. I used Apache's mod_rewrite to send all requests to index.php, and then parsed the URI to extract information and route the request. I'm dabbling in ASP.NET now, and I'm wondering if/how I might perform something similar. Is there a way to route all requests (similar to the way WordPress does it) to one page where central route processing is performed? I'm aware of the MVC framework for ASP.NET, but I'd like to take a stab at this myself as I'm tinkering around and learning. EDIT: BTW, my hosting provider runs IIS 6
TITLE: ASP.NET - Building your own routing system QUESTION: In a recent project, I built my own MVC framework in PHP. One of the things I implemented was a routing system. I used Apache's mod_rewrite to send all requests to index.php, and then parsed the URI to extract information and route the request. I'm dabbling in ASP.NET now, and I'm wondering if/how I might perform something similar. Is there a way to route all requests (similar to the way WordPress does it) to one page where central route processing is performed? I'm aware of the MVC framework for ASP.NET, but I'd like to take a stab at this myself as I'm tinkering around and learning. EDIT: BTW, my hosting provider runs IIS 6 ANSWER: This is going to be a long answer, because I want to make sure you are fully aware of all the ways you can accomplish what you want to do. The routing engine that powers the ASP.NET MVC Framework will work with the traditional ASP.NET Framework. You can take advantage of using the RouteTable and assigning routes, just like you would in an ASP.NET MVC application. You just don't get the MVC portion in traditional ASP.NET sites. That was a huge enhancement for the ASP.NET Framework and it was great to see them reuse that code and make it work in both frameworks. If you want to learn more about this, check out ScottGu's post and scroll down to URL Routing Improvements. Also here is a reference on how to use the System.Web.Routing in WebForms by Phil Haack. Now, if you still want to write you own. You will need to learn the ASP.NET HTTP pipeline and how to implement the IHttpModule and the IHttpHandler interfaces to create your own HttpModule or HttpHandler class to handle your routing. These interfaces are the key in writing your own routing engine. To help put those interfaces in a working example, I couldn't recommend this MSDN article enough. It shows you how to with either interface and explains the differences when creating your own routing/url rewriting engine. Now, if you find out that this might be to much for you. There are third party libraries you can use of people who already wrote a routing/url rewriting engine in.NET. Here is a question that I saw not to long ago asking " What Url rewriter do you use for ASP.Net? " right here on SO.
[ "asp.net", "routes", "url-rewriting" ]
2
6
1,563
1
0
2008-08-22T16:58:07.193000
2008-08-22T17:31:20.873000
22,879
22,908
How do you prevent leading zeros from being stripped when importing an excel doc using c#
I'm able to connect to and read an excel file no problem. But when importing data such as zipcodes that have leading zeros, how do you prevent excel from guessing the datatype and in the process stripping out leading zeros?
I believe you have to set the option in your connect string to force textual import rather than auto-detecting it. Provider=Microsoft.ACE.OLEDB.12.0; Data Source=c:\path\to\myfile.xlsx; Extended Properties=\"Excel 12.0 Xml;IMEX=1\"; Your milage may vary depending on the version you have installed. The IMEX=1 extended property tells Excel to treat intermixed data as text.
How do you prevent leading zeros from being stripped when importing an excel doc using c# I'm able to connect to and read an excel file no problem. But when importing data such as zipcodes that have leading zeros, how do you prevent excel from guessing the datatype and in the process stripping out leading zeros?
TITLE: How do you prevent leading zeros from being stripped when importing an excel doc using c# QUESTION: I'm able to connect to and read an excel file no problem. But when importing data such as zipcodes that have leading zeros, how do you prevent excel from guessing the datatype and in the process stripping out leading zeros? ANSWER: I believe you have to set the option in your connect string to force textual import rather than auto-detecting it. Provider=Microsoft.ACE.OLEDB.12.0; Data Source=c:\path\to\myfile.xlsx; Extended Properties=\"Excel 12.0 Xml;IMEX=1\"; Your milage may vary depending on the version you have installed. The IMEX=1 extended property tells Excel to treat intermixed data as text.
[ "c#", "asp.net", "excel", "ado.net" ]
8
8
7,184
8
0
2008-08-22T17:02:14.483000
2008-08-22T17:10:57.210000
22,880
22,913
What is the best way to prevent session hijacking?
Specifically this is regarding when using a client session cookie to identify a session on the server. Is the best answer to use SSL/HTTPS encryption for the entire web site, and you have the best guarantee that no man in the middle attacks will be able to sniff an existing client session cookie? And perhaps second best to use some sort of encryption on the session value itself that is stored in your session cookie? If a malicious user has physical access to a machine, they can still look at the filesystem to retrieve a valid session cookie and use that to hijack a session?
Encrypting the session value will have zero effect. The session cookie is already an arbitrary value, encrypting it will just generate another arbitrary value that can be sniffed. The only real solution is HTTPS. If you don't want to do SSL on your whole site (maybe you have performance concerns), you might be able to get away with only SSL protecting the sensitive areas. To do that, first make sure your login page is HTTPS. When a user logs in, set a secure cookie (meaning the browser will only transmit it over an SSL link) in addition to the regular session cookie. Then, when a user visits one of your "sensitive" areas, redirect them to HTTPS, and check for the presence of that secure cookie. A real user will have it, a session hijacker will not. EDIT: This answer was originally written in 2008. It's 2016 now, and there's no reason not to have SSL across your entire site. No more plaintext HTTP!
What is the best way to prevent session hijacking? Specifically this is regarding when using a client session cookie to identify a session on the server. Is the best answer to use SSL/HTTPS encryption for the entire web site, and you have the best guarantee that no man in the middle attacks will be able to sniff an existing client session cookie? And perhaps second best to use some sort of encryption on the session value itself that is stored in your session cookie? If a malicious user has physical access to a machine, they can still look at the filesystem to retrieve a valid session cookie and use that to hijack a session?
TITLE: What is the best way to prevent session hijacking? QUESTION: Specifically this is regarding when using a client session cookie to identify a session on the server. Is the best answer to use SSL/HTTPS encryption for the entire web site, and you have the best guarantee that no man in the middle attacks will be able to sniff an existing client session cookie? And perhaps second best to use some sort of encryption on the session value itself that is stored in your session cookie? If a malicious user has physical access to a machine, they can still look at the filesystem to retrieve a valid session cookie and use that to hijack a session? ANSWER: Encrypting the session value will have zero effect. The session cookie is already an arbitrary value, encrypting it will just generate another arbitrary value that can be sniffed. The only real solution is HTTPS. If you don't want to do SSL on your whole site (maybe you have performance concerns), you might be able to get away with only SSL protecting the sensitive areas. To do that, first make sure your login page is HTTPS. When a user logs in, set a secure cookie (meaning the browser will only transmit it over an SSL link) in addition to the regular session cookie. Then, when a user visits one of your "sensitive" areas, redirect them to HTTPS, and check for the presence of that secure cookie. A real user will have it, a session hijacker will not. EDIT: This answer was originally written in 2008. It's 2016 now, and there's no reason not to have SSL across your entire site. No more plaintext HTTP!
[ "security", "session", "cookies" ]
136
146
157,318
14
0
2008-08-22T17:02:26.763000
2008-08-22T17:11:46.723000