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
30,074
30,090
Monitoring files - how to know when a file is complete
We have several.NET applications that monitor a directory for new files, using FileSystemWatcher. The files are copied from another location, uploaded via FTP, etc. When they come in, the files are processed in one way or another. However, one problem that I have never seen a satisfactory answer for is: for large files, how does one know when the files being monitored are still being written to? Obviously, we need to wait until the files are complete and closed before we begin processing them. The event args in the FileSystemWatcher events do not seem to address this.
Have you tried getting a write lock on the file? If it's being written to, that should fail, and you know to leave it alone for a bit...
Monitoring files - how to know when a file is complete We have several.NET applications that monitor a directory for new files, using FileSystemWatcher. The files are copied from another location, uploaded via FTP, etc. When they come in, the files are processed in one way or another. However, one problem that I have never seen a satisfactory answer for is: for large files, how does one know when the files being monitored are still being written to? Obviously, we need to wait until the files are complete and closed before we begin processing them. The event args in the FileSystemWatcher events do not seem to address this.
TITLE: Monitoring files - how to know when a file is complete QUESTION: We have several.NET applications that monitor a directory for new files, using FileSystemWatcher. The files are copied from another location, uploaded via FTP, etc. When they come in, the files are processed in one way or another. However, one problem that I have never seen a satisfactory answer for is: for large files, how does one know when the files being monitored are still being written to? Obviously, we need to wait until the files are complete and closed before we begin processing them. The event args in the FileSystemWatcher events do not seem to address this. ANSWER: Have you tried getting a write lock on the file? If it's being written to, that should fail, and you know to leave it alone for a bit...
[ ".net", "filesystems" ]
13
1
5,857
9
0
2008-08-27T13:23:35.763000
2008-08-27T13:28:47.933000
30,080
30,109
How to know if a line intersects a plane in C#?
I have two points (a line segment) and a rectangle. I would like to know how to calculate if the line segment intersects the rectangle.
From my "Geometry" class: public struct Line { public static Line Empty; private PointF p1; private PointF p2; public Line(PointF p1, PointF p2) { this.p1 = p1; this.p2 = p2; } public PointF P1 { get { return p1; } set { p1 = value; } } public PointF P2 { get { return p2; } set { p2 = value; } } public float X1 { get { return p1.X; } set { p1.X = value; } } public float X2 { get { return p2.X; } set { p2.X = value; } } public float Y1 { get { return p1.Y; } set { p1.Y = value; } } public float Y2 { get { return p2.Y; } set { p2.Y = value; } } } public struct Polygon: IEnumerable { private PointF[] points; public Polygon(PointF[] points) { this.points = points; } public PointF[] Points { get { return points; } set { points = value; } } public int Length { get { return points.Length; } } public PointF this[int index] { get { return points[index]; } set { points[index] = value; } } public static implicit operator PointF[](Polygon polygon) { return polygon.points; } public static implicit operator Polygon(PointF[] points) { return new Polygon(points); } IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator )points.GetEnumerator(); } public IEnumerator GetEnumerator() { return points.GetEnumerator(); } } public enum Intersection { None, Tangent, Intersection, Containment } public static class Geometry { public static Intersection IntersectionOf(Line line, Polygon polygon) { if (polygon.Length == 0) { return Intersection.None; } if (polygon.Length == 1) { return IntersectionOf(polygon[0], line); } bool tangent = false; for (int index = 0; index < polygon.Length; index++) { int index2 = (index + 1)%polygon.Length; Intersection intersection = IntersectionOf(line, new Line(polygon[index], polygon[index2])); if (intersection == Intersection.Intersection) { return intersection; } if (intersection == Intersection.Tangent) { tangent = true; } } return tangent? Intersection.Tangent: IntersectionOf(line.P1, polygon); } public static Intersection IntersectionOf(PointF point, Polygon polygon) { switch (polygon.Length) { case 0: return Intersection.None; case 1: if (polygon[0].X == point.X && polygon[0].Y == point.Y) { return Intersection.Tangent; } else { return Intersection.None; } case 2: return IntersectionOf(point, new Line(polygon[0], polygon[1])); } int counter = 0; int i; PointF p1; int n = polygon.Length; p1 = polygon[0]; if (point == p1) { return Intersection.Tangent; } for (i = 1; i <= n; i++) { PointF p2 = polygon[i % n]; if (point == p2) { return Intersection.Tangent; } if (point.Y > Math.Min(p1.Y, p2.Y)) { if (point.Y <= Math.Max(p1.Y, p2.Y)) { if (point.X <= Math.Max(p1.X, p2.X)) { if (p1.Y!= p2.Y) { double xinters = (point.Y - p1.Y) * (p2.X - p1.X) / (p2.Y - p1.Y) + p1.X; if (p1.X == p2.X || point.X <= xinters) counter++; } } } } p1 = p2; } return (counter % 2 == 1)? Intersection.Containment: Intersection.None; } public static Intersection IntersectionOf(PointF point, Line line) { float bottomY = Math.Min(line.Y1, line.Y2); float topY = Math.Max(line.Y1, line.Y2); bool heightIsRight = point.Y >= bottomY && point.Y <= topY; //Vertical line, slope is divideByZero error! if (line.X1 == line.X2) { if (point.X == line.X1 && heightIsRight) { return Intersection.Tangent; } else { return Intersection.None; } } float slope = (line.X2 - line.X1)/(line.Y2 - line.Y1); bool onLine = (line.Y1 - point.Y) == (slope*(line.X1 - point.X)); if (onLine && heightIsRight) { return Intersection.Tangent; } else { return Intersection.None; } } }
How to know if a line intersects a plane in C#? I have two points (a line segment) and a rectangle. I would like to know how to calculate if the line segment intersects the rectangle.
TITLE: How to know if a line intersects a plane in C#? QUESTION: I have two points (a line segment) and a rectangle. I would like to know how to calculate if the line segment intersects the rectangle. ANSWER: From my "Geometry" class: public struct Line { public static Line Empty; private PointF p1; private PointF p2; public Line(PointF p1, PointF p2) { this.p1 = p1; this.p2 = p2; } public PointF P1 { get { return p1; } set { p1 = value; } } public PointF P2 { get { return p2; } set { p2 = value; } } public float X1 { get { return p1.X; } set { p1.X = value; } } public float X2 { get { return p2.X; } set { p2.X = value; } } public float Y1 { get { return p1.Y; } set { p1.Y = value; } } public float Y2 { get { return p2.Y; } set { p2.Y = value; } } } public struct Polygon: IEnumerable { private PointF[] points; public Polygon(PointF[] points) { this.points = points; } public PointF[] Points { get { return points; } set { points = value; } } public int Length { get { return points.Length; } } public PointF this[int index] { get { return points[index]; } set { points[index] = value; } } public static implicit operator PointF[](Polygon polygon) { return polygon.points; } public static implicit operator Polygon(PointF[] points) { return new Polygon(points); } IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator )points.GetEnumerator(); } public IEnumerator GetEnumerator() { return points.GetEnumerator(); } } public enum Intersection { None, Tangent, Intersection, Containment } public static class Geometry { public static Intersection IntersectionOf(Line line, Polygon polygon) { if (polygon.Length == 0) { return Intersection.None; } if (polygon.Length == 1) { return IntersectionOf(polygon[0], line); } bool tangent = false; for (int index = 0; index < polygon.Length; index++) { int index2 = (index + 1)%polygon.Length; Intersection intersection = IntersectionOf(line, new Line(polygon[index], polygon[index2])); if (intersection == Intersection.Intersection) { return intersection; } if (intersection == Intersection.Tangent) { tangent = true; } } return tangent? Intersection.Tangent: IntersectionOf(line.P1, polygon); } public static Intersection IntersectionOf(PointF point, Polygon polygon) { switch (polygon.Length) { case 0: return Intersection.None; case 1: if (polygon[0].X == point.X && polygon[0].Y == point.Y) { return Intersection.Tangent; } else { return Intersection.None; } case 2: return IntersectionOf(point, new Line(polygon[0], polygon[1])); } int counter = 0; int i; PointF p1; int n = polygon.Length; p1 = polygon[0]; if (point == p1) { return Intersection.Tangent; } for (i = 1; i <= n; i++) { PointF p2 = polygon[i % n]; if (point == p2) { return Intersection.Tangent; } if (point.Y > Math.Min(p1.Y, p2.Y)) { if (point.Y <= Math.Max(p1.Y, p2.Y)) { if (point.X <= Math.Max(p1.X, p2.X)) { if (p1.Y!= p2.Y) { double xinters = (point.Y - p1.Y) * (p2.X - p1.X) / (p2.Y - p1.Y) + p1.X; if (p1.X == p2.X || point.X <= xinters) counter++; } } } } p1 = p2; } return (counter % 2 == 1)? Intersection.Containment: Intersection.None; } public static Intersection IntersectionOf(PointF point, Line line) { float bottomY = Math.Min(line.Y1, line.Y2); float topY = Math.Max(line.Y1, line.Y2); bool heightIsRight = point.Y >= bottomY && point.Y <= topY; //Vertical line, slope is divideByZero error! if (line.X1 == line.X2) { if (point.X == line.X1 && heightIsRight) { return Intersection.Tangent; } else { return Intersection.None; } } float slope = (line.X2 - line.X1)/(line.Y2 - line.Y1); bool onLine = (line.Y1 - point.Y) == (slope*(line.X1 - point.X)); if (onLine && heightIsRight) { return Intersection.Tangent; } else { return Intersection.None; } } }
[ "c#", "geometry", "2d", "computational-geometry" ]
36
22
18,106
7
0
2008-08-27T13:26:56.113000
2008-08-27T13:33:19.687000
30,099
30,186
C++ - What does "Stack automatic" mean?
In my browsings amongst the Internet, I came across this post, which includes this "(Well written) C++ goes to great lengths to make stack automatic objects work "just like" primitives, as reflected in Stroustrup's advice to "do as the ints do". This requires a much greater adherence to the principles of Object Oriented development: your class isn't right until it "works like" an int, following the "Rule of Three" that guarantees it can (just like an int) be created, copied, and correctly destroyed as a stack automatic." I've done a little C, and C++ code, but just in passing, never anything serious, but I'm just curious, what it means exactly? Can someone give an example?
Stack objects are handled automatically by the compiler. When the scope is left, it is deleted. { obj a; } // a is destroyed here When you do the same with a 'newed' object you get a memory leak: { obj* b = new obj; } b is not destroyed, so we lost the ability to reclaim the memory b owns. And maybe worse, the object cannot clean itself up. In C the following is common: { FILE* pF = fopen(... ); //... do sth with pF fclose( pF ); } In C++ we write this: { std::fstream f(... ); // do sth with f } // here f gets auto magically destroyed and the destructor frees the file When we forget to call fclose in the C sample the file is not closed and may not be used by other programs. (e.g. it cannot be deleted). Another example, demonstrating the object string, which can be constructed, assigned to and which is destroyed on exiting the scope. { string v( "bob" ); string k; v = k // v now contains "bob" } // v + k are destroyed here, and any memory used by v + k is freed
C++ - What does "Stack automatic" mean? In my browsings amongst the Internet, I came across this post, which includes this "(Well written) C++ goes to great lengths to make stack automatic objects work "just like" primitives, as reflected in Stroustrup's advice to "do as the ints do". This requires a much greater adherence to the principles of Object Oriented development: your class isn't right until it "works like" an int, following the "Rule of Three" that guarantees it can (just like an int) be created, copied, and correctly destroyed as a stack automatic." I've done a little C, and C++ code, but just in passing, never anything serious, but I'm just curious, what it means exactly? Can someone give an example?
TITLE: C++ - What does "Stack automatic" mean? QUESTION: In my browsings amongst the Internet, I came across this post, which includes this "(Well written) C++ goes to great lengths to make stack automatic objects work "just like" primitives, as reflected in Stroustrup's advice to "do as the ints do". This requires a much greater adherence to the principles of Object Oriented development: your class isn't right until it "works like" an int, following the "Rule of Three" that guarantees it can (just like an int) be created, copied, and correctly destroyed as a stack automatic." I've done a little C, and C++ code, but just in passing, never anything serious, but I'm just curious, what it means exactly? Can someone give an example? ANSWER: Stack objects are handled automatically by the compiler. When the scope is left, it is deleted. { obj a; } // a is destroyed here When you do the same with a 'newed' object you get a memory leak: { obj* b = new obj; } b is not destroyed, so we lost the ability to reclaim the memory b owns. And maybe worse, the object cannot clean itself up. In C the following is common: { FILE* pF = fopen(... ); //... do sth with pF fclose( pF ); } In C++ we write this: { std::fstream f(... ); // do sth with f } // here f gets auto magically destroyed and the destructor frees the file When we forget to call fclose in the C sample the file is not closed and may not be used by other programs. (e.g. it cannot be deleted). Another example, demonstrating the object string, which can be constructed, assigned to and which is destroyed on exiting the scope. { string v( "bob" ); string k; v = k // v now contains "bob" } // v + k are destroyed here, and any memory used by v + k is freed
[ "c++", "oop" ]
4
12
953
5
0
2008-08-27T13:31:21.687000
2008-08-27T13:59:22.387000
30,101
30,114
Is there an automatic code formatter for C#?
In my work I deal mostly with C# code nowadays, with a sprinkle of java from time to time. What I absolutely love about Eclipse (and I know people using it daily love it even more) is a sophisticated code formatter, able to mould code into any coding standard one might imagine. Is there such a tool for C#? Visual Studio code formatting (Crtl+K, Crtl+D) is subpar and StyleCop only checks the source without fixing it. My dream tool would run from console (for easy inclusion in automated builds or pre-commit hooks and for execution on Linux + Mono), have text-file based configuration easy to store in a project repository and a graphical rule editor with preview - just like the Eclipse Code Formatter does.
For Visual Studio, take a look at ReSharper. It's an awesome tool and a definite must-have. Versions after 4.0 have the code formatting and clean-up feature that you are looking for. There's also plugin integration with StyleCop, including formatting settings file. You'll probably want Agent Smith plugin as well, for spell-checking the identifiers and comments. ReSharper supports per-solution formatting setting files, which can be checked into version control system and shared by the whole team. The keyboard shortcut for code cleanup is Ctrl + E, C. In 'vanilla' Visual Studio, the current file can be automatically formatted with Ctrl + K, Ctrl + D, and Ctrl + K, Ctrl + F formats the selected text. As for a runs-everywhere command line tool to be used with commit hooks, try NArrange. It's free, can process whole directories at once and runs on Mono as well as on Microsoft.NET. Some people also use the Artistic Style command line tool, although it requires Perl and works better with C/C++ code than with C#.
Is there an automatic code formatter for C#? In my work I deal mostly with C# code nowadays, with a sprinkle of java from time to time. What I absolutely love about Eclipse (and I know people using it daily love it even more) is a sophisticated code formatter, able to mould code into any coding standard one might imagine. Is there such a tool for C#? Visual Studio code formatting (Crtl+K, Crtl+D) is subpar and StyleCop only checks the source without fixing it. My dream tool would run from console (for easy inclusion in automated builds or pre-commit hooks and for execution on Linux + Mono), have text-file based configuration easy to store in a project repository and a graphical rule editor with preview - just like the Eclipse Code Formatter does.
TITLE: Is there an automatic code formatter for C#? QUESTION: In my work I deal mostly with C# code nowadays, with a sprinkle of java from time to time. What I absolutely love about Eclipse (and I know people using it daily love it even more) is a sophisticated code formatter, able to mould code into any coding standard one might imagine. Is there such a tool for C#? Visual Studio code formatting (Crtl+K, Crtl+D) is subpar and StyleCop only checks the source without fixing it. My dream tool would run from console (for easy inclusion in automated builds or pre-commit hooks and for execution on Linux + Mono), have text-file based configuration easy to store in a project repository and a graphical rule editor with preview - just like the Eclipse Code Formatter does. ANSWER: For Visual Studio, take a look at ReSharper. It's an awesome tool and a definite must-have. Versions after 4.0 have the code formatting and clean-up feature that you are looking for. There's also plugin integration with StyleCop, including formatting settings file. You'll probably want Agent Smith plugin as well, for spell-checking the identifiers and comments. ReSharper supports per-solution formatting setting files, which can be checked into version control system and shared by the whole team. The keyboard shortcut for code cleanup is Ctrl + E, C. In 'vanilla' Visual Studio, the current file can be automatically formatted with Ctrl + K, Ctrl + D, and Ctrl + K, Ctrl + F formats the selected text. As for a runs-everywhere command line tool to be used with commit hooks, try NArrange. It's free, can process whole directories at once and runs on Mono as well as on Microsoft.NET. Some people also use the Artistic Style command line tool, although it requires Perl and works better with C/C++ code than with C#.
[ "c#", "formatting", "build-automation" ]
65
49
69,319
14
0
2008-08-27T13:31:24.747000
2008-08-27T13:34:46.983000
30,121
30,129
Making a JavaScript regex equivalent to a PHP regex
After my web form is submitted, a regex will be applied to user input on the server side (via PHP). I'd like to have the identical regex running in real-time on the client side to show the user what the real input will be. This will be pretty much the same as the Preview section on the Ask Question pages on Stack Overflow except with PHP on the back-end instead of.NET. What do I need to keep in mind in order to have my PHP and JavaScript regular expressions act exactly the same as each other?
Hehe this was sort of asked moments ago and Jeff pointed out: http://www.regular-expressions.info/refflavors.html. There is a comparison of regular expression capabilities across tools and languages.
Making a JavaScript regex equivalent to a PHP regex After my web form is submitted, a regex will be applied to user input on the server side (via PHP). I'd like to have the identical regex running in real-time on the client side to show the user what the real input will be. This will be pretty much the same as the Preview section on the Ask Question pages on Stack Overflow except with PHP on the back-end instead of.NET. What do I need to keep in mind in order to have my PHP and JavaScript regular expressions act exactly the same as each other?
TITLE: Making a JavaScript regex equivalent to a PHP regex QUESTION: After my web form is submitted, a regex will be applied to user input on the server side (via PHP). I'd like to have the identical regex running in real-time on the client side to show the user what the real input will be. This will be pretty much the same as the Preview section on the Ask Question pages on Stack Overflow except with PHP on the back-end instead of.NET. What do I need to keep in mind in order to have my PHP and JavaScript regular expressions act exactly the same as each other? ANSWER: Hehe this was sort of asked moments ago and Jeff pointed out: http://www.regular-expressions.info/refflavors.html. There is a comparison of regular expression capabilities across tools and languages.
[ "php", "javascript", "regex" ]
10
12
8,282
5
0
2008-08-27T13:36:51.317000
2008-08-27T13:39:38.987000
30,145
30,223
Ethernet MAC address as activation code for an appliance?
Let's suppose you deploy a network-attached appliances (small form factor PCs) in the field. You want to allow these to call home after being powered on, then be identified and activated by end users. Our current plan involves the user entering the MAC address into an activation page on our web site. Later our software (running on the box) will read the address from the interface and transmit this in a "call home" packet. If it matches, the server response with customer information and the box is activated. We like this approach because it's easy to access, and usually printed on external labels (FCC requirement?). Any problems to watch out for? (The hardware in use is small form factor so all NICs, etc are embedded and would be very hard to change. Customers don't normally have direct acccess to the OS in any way). I know Microsoft does some crazy fuzzy-hashing function for Windows activation using PCI device IDs, memory size, etc. But that seems overkill for our needs. -- @Neall Basically, calling into our server, for purposes of this discussion you could call us the manufacturer. Neall is correct, we're just using the address as a constant. We will read it and transmit it within another packet (let's say HTTP POST), not depending on getting it somehow from Ethernet frames.
I don't think there's anything magic about what you're doing here - couldn't what you're doing be described as: "At production we burn a unique number into each of our devices which is both readable by the end user (it's on the label) and accessible to the internal processor. Our users have to enter this number into our website along with their credit-card details, and the box subsequently contacts to the website for permission to operate" " Coincidentally we also use this number as the MAC address for network packets as we have to uniquely assign that during production anyway, so it saved us duplicating this bit of work" I would say the two obvious hazards are: People hack around with your device and change this address to one which someone else has already activated. Whether this is likely to happen depends on some relationship between how hard it is and how expensive whatever they get to steal is. You might want to think about how easily they can take a firmware upgrade file and get the code out of it. Someone uses a combination of firewall/router rules and a bit of custom software to generate a server which replicates the operation of your 'auth server' and grants permission to the device to proceed. You could make this harder with some combination of hashing/PKE as part of the protocol. As ever, some tedious, expensive one-off hack is largely irrelevant, what you don't want is a class-break which can be distributed over the internet to every thieving dweep.
Ethernet MAC address as activation code for an appliance? Let's suppose you deploy a network-attached appliances (small form factor PCs) in the field. You want to allow these to call home after being powered on, then be identified and activated by end users. Our current plan involves the user entering the MAC address into an activation page on our web site. Later our software (running on the box) will read the address from the interface and transmit this in a "call home" packet. If it matches, the server response with customer information and the box is activated. We like this approach because it's easy to access, and usually printed on external labels (FCC requirement?). Any problems to watch out for? (The hardware in use is small form factor so all NICs, etc are embedded and would be very hard to change. Customers don't normally have direct acccess to the OS in any way). I know Microsoft does some crazy fuzzy-hashing function for Windows activation using PCI device IDs, memory size, etc. But that seems overkill for our needs. -- @Neall Basically, calling into our server, for purposes of this discussion you could call us the manufacturer. Neall is correct, we're just using the address as a constant. We will read it and transmit it within another packet (let's say HTTP POST), not depending on getting it somehow from Ethernet frames.
TITLE: Ethernet MAC address as activation code for an appliance? QUESTION: Let's suppose you deploy a network-attached appliances (small form factor PCs) in the field. You want to allow these to call home after being powered on, then be identified and activated by end users. Our current plan involves the user entering the MAC address into an activation page on our web site. Later our software (running on the box) will read the address from the interface and transmit this in a "call home" packet. If it matches, the server response with customer information and the box is activated. We like this approach because it's easy to access, and usually printed on external labels (FCC requirement?). Any problems to watch out for? (The hardware in use is small form factor so all NICs, etc are embedded and would be very hard to change. Customers don't normally have direct acccess to the OS in any way). I know Microsoft does some crazy fuzzy-hashing function for Windows activation using PCI device IDs, memory size, etc. But that seems overkill for our needs. -- @Neall Basically, calling into our server, for purposes of this discussion you could call us the manufacturer. Neall is correct, we're just using the address as a constant. We will read it and transmit it within another packet (let's say HTTP POST), not depending on getting it somehow from Ethernet frames. ANSWER: I don't think there's anything magic about what you're doing here - couldn't what you're doing be described as: "At production we burn a unique number into each of our devices which is both readable by the end user (it's on the label) and accessible to the internal processor. Our users have to enter this number into our website along with their credit-card details, and the box subsequently contacts to the website for permission to operate" " Coincidentally we also use this number as the MAC address for network packets as we have to uniquely assign that during production anyway, so it saved us duplicating this bit of work" I would say the two obvious hazards are: People hack around with your device and change this address to one which someone else has already activated. Whether this is likely to happen depends on some relationship between how hard it is and how expensive whatever they get to steal is. You might want to think about how easily they can take a firmware upgrade file and get the code out of it. Someone uses a combination of firewall/router rules and a bit of custom software to generate a server which replicates the operation of your 'auth server' and grants permission to the device to proceed. You could make this harder with some combination of hashing/PKE as part of the protocol. As ever, some tedious, expensive one-off hack is largely irrelevant, what you don't want is a class-break which can be distributed over the internet to every thieving dweep.
[ "licensing", "ethernet", "drm", "activation" ]
7
2
2,944
4
0
2008-08-27T13:43:08.040000
2008-08-27T14:10:52.827000
30,148
30,169
Manual steps to upgrade VS.NET solution and target .NET framework?
After you've let the VS.NET (2008 in this case) wizard upgrade your solution, do you perform any manual steps to upgrade specific properties of your solution and projects? For instance, you have to go to each project and target a new version of the framework (from 2.0 to 3.5 in this case). Even after targeting a new version of the framework, I find assembly references still point to the assemblies from the old version (2.0 rather than 3.5 even after changing the target). Does this mean I lose out on the performance benefits of assemblies in the new version of the framework?
All versions of the.Net Framework from 2.0 onwards (i.e. 3.0 and 3.5) use exactly the same core framework files (i.e. the CLR, you'll notice there are no directories relating to 3.0 or 3.5 in the C:\Windows\Microsoft.Net\Framework directory) therefore you shouldn't worry too much about any performance issues. The Core parts are referred to in Microsoft Speak as the 'Red Bits' and the rest as the 'Green Bits'.
Manual steps to upgrade VS.NET solution and target .NET framework? After you've let the VS.NET (2008 in this case) wizard upgrade your solution, do you perform any manual steps to upgrade specific properties of your solution and projects? For instance, you have to go to each project and target a new version of the framework (from 2.0 to 3.5 in this case). Even after targeting a new version of the framework, I find assembly references still point to the assemblies from the old version (2.0 rather than 3.5 even after changing the target). Does this mean I lose out on the performance benefits of assemblies in the new version of the framework?
TITLE: Manual steps to upgrade VS.NET solution and target .NET framework? QUESTION: After you've let the VS.NET (2008 in this case) wizard upgrade your solution, do you perform any manual steps to upgrade specific properties of your solution and projects? For instance, you have to go to each project and target a new version of the framework (from 2.0 to 3.5 in this case). Even after targeting a new version of the framework, I find assembly references still point to the assemblies from the old version (2.0 rather than 3.5 even after changing the target). Does this mean I lose out on the performance benefits of assemblies in the new version of the framework? ANSWER: All versions of the.Net Framework from 2.0 onwards (i.e. 3.0 and 3.5) use exactly the same core framework files (i.e. the CLR, you'll notice there are no directories relating to 3.0 or 3.5 in the C:\Windows\Microsoft.Net\Framework directory) therefore you shouldn't worry too much about any performance issues. The Core parts are referred to in Microsoft Speak as the 'Red Bits' and the rest as the 'Green Bits'.
[ ".net", "visual-studio" ]
2
3
1,115
4
0
2008-08-27T13:46:18.297000
2008-08-27T13:53:46.207000
30,152
30,204
How does WinXP's "Send to Compressed (zipped) Folder" decide what to include in zip file?
I'm not going to be too surprised if I get shot-down for asking a "non programming" question, but maybe somebody knows... I was zipping the contents of my subversion sandbox using WinXP's inbuilt "Send to Compressed (zipped) Folder" capability and was surprised to find that the.zip file created did not contain the.svn directories and their contents. I had always assumed that all files were included and I can't locate which property/option/attribute controls inclusion or otherwise. Can anybody help? Thanks, Tom EDIT: So, isnt there a smart way to handle the problem? The real problem (show hidden files set to true..svn folders are not compressed because windows does not consider them as valid folders) is still un-answered. Thanks...
Send to zipped Folder does not traverse into folders without names before dot (like ".svn"). If you had other folders that begin with dots, those would not be included either. Files without names are not excluded. Hidden attribute does not come into play. Might be a bug, might be by design. Remember that Windows explorer does not allow creating folders beginning with dot, even though the underlying system can handle them.
How does WinXP's "Send to Compressed (zipped) Folder" decide what to include in zip file? I'm not going to be too surprised if I get shot-down for asking a "non programming" question, but maybe somebody knows... I was zipping the contents of my subversion sandbox using WinXP's inbuilt "Send to Compressed (zipped) Folder" capability and was surprised to find that the.zip file created did not contain the.svn directories and their contents. I had always assumed that all files were included and I can't locate which property/option/attribute controls inclusion or otherwise. Can anybody help? Thanks, Tom EDIT: So, isnt there a smart way to handle the problem? The real problem (show hidden files set to true..svn folders are not compressed because windows does not consider them as valid folders) is still un-answered. Thanks...
TITLE: How does WinXP's "Send to Compressed (zipped) Folder" decide what to include in zip file? QUESTION: I'm not going to be too surprised if I get shot-down for asking a "non programming" question, but maybe somebody knows... I was zipping the contents of my subversion sandbox using WinXP's inbuilt "Send to Compressed (zipped) Folder" capability and was surprised to find that the.zip file created did not contain the.svn directories and their contents. I had always assumed that all files were included and I can't locate which property/option/attribute controls inclusion or otherwise. Can anybody help? Thanks, Tom EDIT: So, isnt there a smart way to handle the problem? The real problem (show hidden files set to true..svn folders are not compressed because windows does not consider them as valid folders) is still un-answered. Thanks... ANSWER: Send to zipped Folder does not traverse into folders without names before dot (like ".svn"). If you had other folders that begin with dots, those would not be included either. Files without names are not excluded. Hidden attribute does not come into play. Might be a bug, might be by design. Remember that Windows explorer does not allow creating folders beginning with dot, even though the underlying system can handle them.
[ "zip", "windows-xp" ]
5
4
7,278
7
0
2008-08-27T13:47:19.340000
2008-08-27T14:05:18.207000
30,160
30,402
Is there a Java Console/Editor similar to the GroovyConsole?
I'm giving a presentation to a Java User's Group on Groovy and I'm going to be doing some coding during the presentation to show some side-by-side Java/Groovy. I really like the GroovyConsole as it's simple and I can resize the text easily. I'm wondering if there is anything similar for Java? I know I could just use Eclipse but I'd rather have a smaller app to use without having to customize a view. What's the community got? Screen shot of GroovyConsole:
DrJava is your best bet. It also has an Eclipse plugin to use the interactions pane like GroovyConsole.
Is there a Java Console/Editor similar to the GroovyConsole? I'm giving a presentation to a Java User's Group on Groovy and I'm going to be doing some coding during the presentation to show some side-by-side Java/Groovy. I really like the GroovyConsole as it's simple and I can resize the text easily. I'm wondering if there is anything similar for Java? I know I could just use Eclipse but I'd rather have a smaller app to use without having to customize a view. What's the community got? Screen shot of GroovyConsole:
TITLE: Is there a Java Console/Editor similar to the GroovyConsole? QUESTION: I'm giving a presentation to a Java User's Group on Groovy and I'm going to be doing some coding during the presentation to show some side-by-side Java/Groovy. I really like the GroovyConsole as it's simple and I can resize the text easily. I'm wondering if there is anything similar for Java? I know I could just use Eclipse but I'd rather have a smaller app to use without having to customize a view. What's the community got? Screen shot of GroovyConsole: ANSWER: DrJava is your best bet. It also has an Eclipse plugin to use the interactions pane like GroovyConsole.
[ "java", "editor" ]
5
2
1,459
4
0
2008-08-27T13:50:26.090000
2008-08-27T15:12:42.693000
30,171
30,172
Why won't .NET deserialize my primitive array from a web service?
Help! I have an Axis web service that is being consumed by a C# application. Everything works great, except that arrays of long values always come across as [0,0,0,0] - the right length, but the values aren't deserialized. I have tried with other primitives (ints, doubles) and the same thing happens. What do I do? I don't want to change the semantics of my service.
Here's what I ended up with. I have never found another solution out there for this, so if you have something better, by all means, contribute. First, the long array definition in the wsdl:types area: Next, we create a SoapExtensionAttribute that will perform the fix. It seems that the problem was that.NET wasn't following the multiref id to the element containing the double value. So, we process the array item, go find the value, and then insert it the value into the element: [AttributeUsage(AttributeTargets.Method)] public class LongArrayHelperAttribute: SoapExtensionAttribute { private int priority = 0; public override Type ExtensionType { get { return typeof (LongArrayHelper); } } public override int Priority { get { return priority; } set { priority = value; } } } public class LongArrayHelper: SoapExtension { private static ILog log = LogManager.GetLogger(typeof (LongArrayHelper)); public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute) { return null; } public override object GetInitializer(Type serviceType) { return null; } public override void Initialize(object initializer) { } private Stream originalStream; private Stream newStream; public override void ProcessMessage(SoapMessage m) { switch (m.Stage) { case SoapMessageStage.AfterSerialize: newStream.Position = 0; //need to reset stream CopyStream(newStream, originalStream); break; case SoapMessageStage.BeforeDeserialize: XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = false; settings.NewLineOnAttributes = false; settings.NewLineHandling = NewLineHandling.None; settings.NewLineChars = ""; XmlWriter writer = XmlWriter.Create(newStream, settings); XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(originalStream); List longArrayItems = new List (); Dictionary multiRefs = new Dictionary (); FindImportantNodes(xmlDocument.DocumentElement, longArrayItems, multiRefs); FixLongArrays(longArrayItems, multiRefs); xmlDocument.Save(writer); newStream.Position = 0; break; } } private static void FindImportantNodes(XmlElement element, List longArrayItems, Dictionary multiRefs) { string val = element.GetAttribute("soapenc:arrayType"); if (val!= null && val.Contains(":long[")) { longArrayItems.Add(element); } if (element.Name == "multiRef") { multiRefs[element.GetAttribute("id")] = element; } foreach (XmlNode node in element.ChildNodes) { XmlElement child = node as XmlElement; if (child!= null) { FindImportantNodes(child, longArrayItems, multiRefs); } } } private static void FixLongArrays(List longArrayItems, Dictionary multiRefs) { foreach (XmlElement element in longArrayItems) { foreach (XmlNode node in element.ChildNodes) { XmlElement child = node as XmlElement; if (child!= null) { string href = child.GetAttribute("href"); if (href == null || href.Length == 0) { continue; } if (href.StartsWith("#")) { href = href.Remove(0, 1); } XmlElement multiRef = multiRefs[href]; if (multiRef == null) { continue; } child.RemoveAttribute("href"); child.InnerXml = multiRef.InnerXml; if (log.IsDebugEnabled) { log.Debug("Replaced multiRef id '" + href + "' with value: " + multiRef.InnerXml); } } } } } public override Stream ChainStream(Stream s) { originalStream = s; newStream = new MemoryStream(); return newStream; } private static void CopyStream(Stream from, Stream to) { TextReader reader = new StreamReader(from); TextWriter writer = new StreamWriter(to); writer.WriteLine(reader.ReadToEnd()); writer.Flush(); } } Finally, we tag all methods in the Reference.cs file that will be deserializing a long array with our attribute: [SoapRpcMethod("", RequestNamespace="http://some.service.provider", ResponseNamespace="http://some.service.provider")] [return: SoapElement("getFooReturn")] [LongArrayHelper] public Foo getFoo() { object[] results = Invoke("getFoo", new object[0]); return ((Foo) (results[0])); } This fix is long-specific, but it could probably be generalized to handle any primitive type having this problem.
Why won't .NET deserialize my primitive array from a web service? Help! I have an Axis web service that is being consumed by a C# application. Everything works great, except that arrays of long values always come across as [0,0,0,0] - the right length, but the values aren't deserialized. I have tried with other primitives (ints, doubles) and the same thing happens. What do I do? I don't want to change the semantics of my service.
TITLE: Why won't .NET deserialize my primitive array from a web service? QUESTION: Help! I have an Axis web service that is being consumed by a C# application. Everything works great, except that arrays of long values always come across as [0,0,0,0] - the right length, but the values aren't deserialized. I have tried with other primitives (ints, doubles) and the same thing happens. What do I do? I don't want to change the semantics of my service. ANSWER: Here's what I ended up with. I have never found another solution out there for this, so if you have something better, by all means, contribute. First, the long array definition in the wsdl:types area: Next, we create a SoapExtensionAttribute that will perform the fix. It seems that the problem was that.NET wasn't following the multiref id to the element containing the double value. So, we process the array item, go find the value, and then insert it the value into the element: [AttributeUsage(AttributeTargets.Method)] public class LongArrayHelperAttribute: SoapExtensionAttribute { private int priority = 0; public override Type ExtensionType { get { return typeof (LongArrayHelper); } } public override int Priority { get { return priority; } set { priority = value; } } } public class LongArrayHelper: SoapExtension { private static ILog log = LogManager.GetLogger(typeof (LongArrayHelper)); public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute) { return null; } public override object GetInitializer(Type serviceType) { return null; } public override void Initialize(object initializer) { } private Stream originalStream; private Stream newStream; public override void ProcessMessage(SoapMessage m) { switch (m.Stage) { case SoapMessageStage.AfterSerialize: newStream.Position = 0; //need to reset stream CopyStream(newStream, originalStream); break; case SoapMessageStage.BeforeDeserialize: XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = false; settings.NewLineOnAttributes = false; settings.NewLineHandling = NewLineHandling.None; settings.NewLineChars = ""; XmlWriter writer = XmlWriter.Create(newStream, settings); XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(originalStream); List longArrayItems = new List (); Dictionary multiRefs = new Dictionary (); FindImportantNodes(xmlDocument.DocumentElement, longArrayItems, multiRefs); FixLongArrays(longArrayItems, multiRefs); xmlDocument.Save(writer); newStream.Position = 0; break; } } private static void FindImportantNodes(XmlElement element, List longArrayItems, Dictionary multiRefs) { string val = element.GetAttribute("soapenc:arrayType"); if (val!= null && val.Contains(":long[")) { longArrayItems.Add(element); } if (element.Name == "multiRef") { multiRefs[element.GetAttribute("id")] = element; } foreach (XmlNode node in element.ChildNodes) { XmlElement child = node as XmlElement; if (child!= null) { FindImportantNodes(child, longArrayItems, multiRefs); } } } private static void FixLongArrays(List longArrayItems, Dictionary multiRefs) { foreach (XmlElement element in longArrayItems) { foreach (XmlNode node in element.ChildNodes) { XmlElement child = node as XmlElement; if (child!= null) { string href = child.GetAttribute("href"); if (href == null || href.Length == 0) { continue; } if (href.StartsWith("#")) { href = href.Remove(0, 1); } XmlElement multiRef = multiRefs[href]; if (multiRef == null) { continue; } child.RemoveAttribute("href"); child.InnerXml = multiRef.InnerXml; if (log.IsDebugEnabled) { log.Debug("Replaced multiRef id '" + href + "' with value: " + multiRef.InnerXml); } } } } } public override Stream ChainStream(Stream s) { originalStream = s; newStream = new MemoryStream(); return newStream; } private static void CopyStream(Stream from, Stream to) { TextReader reader = new StreamReader(from); TextWriter writer = new StreamWriter(to); writer.WriteLine(reader.ReadToEnd()); writer.Flush(); } } Finally, we tag all methods in the Reference.cs file that will be deserializing a long array with our attribute: [SoapRpcMethod("", RequestNamespace="http://some.service.provider", ResponseNamespace="http://some.service.provider")] [return: SoapElement("getFooReturn")] [LongArrayHelper] public Foo getFoo() { object[] results = Invoke("getFoo", new object[0]); return ((Foo) (results[0])); } This fix is long-specific, but it could probably be generalized to handle any primitive type having this problem.
[ "java", ".net", "service", "primitive" ]
5
7
7,002
3
0
2008-08-27T13:53:58.840000
2008-08-27T13:54:06.453000
30,183
30,545
How do I enable Edit and Continue on a 64-bit application and VB2008 Express?
When I try to do that I get the following error: Changes to 64-bit applications are not allowed. @Wilka: That option wasn't available until I selected Tools > Options > Projects and Solutions > General and check "Show advanced build configurations". Though I found this hint from your MSDN link. So if you edit your comment, I can make it the accepted answer... Thanks everybody! Please see my first comment on this question, it's not there... Somehow... I can select Target framework though (2.0, 3.0 and 3.5), not that I see any use of that for this particular problem... It doesn't have to be a 64bit program, actually, I rather prefer it to be 32bit anyway since it is more like a utility and it should work on 32bit systems. Also, I'm running Vista at 64bit. Maybe that has something to do with it? @Rob Cooper: Now I think of it, I never had the chance of selecting either a 64bit or a 32bit application when creating the solution/project/application... And according to your link "64-Bit Debugging (X64)" is possible with MS VB2008 express edition. Oh btw, I found the following: If you are debugging a 64-bit application and want to use Edit and Continue, you must change the target platform and compile the application as a 32-bit application. You can change this setting by opening the Project Properties and going to the Compile page. On that page, click Advanced Compile Options and change the Target CPU setting to x86 in the Advanced Compiler Settings dialog box. Link But I dont see the Target CPU setting...
You could try: In Visual Basic 2008 Express Edition: Build menu > Configuration Manager... Change Active solution platform: to "...", choose "x86", save the new platform. Now the "x86" option is available in the Compile settings. You may need to enable "Show advanced build configurations" first, in Tools > Options > Projects and Solutions > General (from this post on MSDN forums)
How do I enable Edit and Continue on a 64-bit application and VB2008 Express? When I try to do that I get the following error: Changes to 64-bit applications are not allowed. @Wilka: That option wasn't available until I selected Tools > Options > Projects and Solutions > General and check "Show advanced build configurations". Though I found this hint from your MSDN link. So if you edit your comment, I can make it the accepted answer... Thanks everybody! Please see my first comment on this question, it's not there... Somehow... I can select Target framework though (2.0, 3.0 and 3.5), not that I see any use of that for this particular problem... It doesn't have to be a 64bit program, actually, I rather prefer it to be 32bit anyway since it is more like a utility and it should work on 32bit systems. Also, I'm running Vista at 64bit. Maybe that has something to do with it? @Rob Cooper: Now I think of it, I never had the chance of selecting either a 64bit or a 32bit application when creating the solution/project/application... And according to your link "64-Bit Debugging (X64)" is possible with MS VB2008 express edition. Oh btw, I found the following: If you are debugging a 64-bit application and want to use Edit and Continue, you must change the target platform and compile the application as a 32-bit application. You can change this setting by opening the Project Properties and going to the Compile page. On that page, click Advanced Compile Options and change the Target CPU setting to x86 in the Advanced Compiler Settings dialog box. Link But I dont see the Target CPU setting...
TITLE: How do I enable Edit and Continue on a 64-bit application and VB2008 Express? QUESTION: When I try to do that I get the following error: Changes to 64-bit applications are not allowed. @Wilka: That option wasn't available until I selected Tools > Options > Projects and Solutions > General and check "Show advanced build configurations". Though I found this hint from your MSDN link. So if you edit your comment, I can make it the accepted answer... Thanks everybody! Please see my first comment on this question, it's not there... Somehow... I can select Target framework though (2.0, 3.0 and 3.5), not that I see any use of that for this particular problem... It doesn't have to be a 64bit program, actually, I rather prefer it to be 32bit anyway since it is more like a utility and it should work on 32bit systems. Also, I'm running Vista at 64bit. Maybe that has something to do with it? @Rob Cooper: Now I think of it, I never had the chance of selecting either a 64bit or a 32bit application when creating the solution/project/application... And according to your link "64-Bit Debugging (X64)" is possible with MS VB2008 express edition. Oh btw, I found the following: If you are debugging a 64-bit application and want to use Edit and Continue, you must change the target platform and compile the application as a 32-bit application. You can change this setting by opening the Project Properties and going to the Compile page. On that page, click Advanced Compile Options and change the Target CPU setting to x86 in the Advanced Compiler Settings dialog box. Link But I dont see the Target CPU setting... ANSWER: You could try: In Visual Basic 2008 Express Edition: Build menu > Configuration Manager... Change Active solution platform: to "...", choose "x86", save the new platform. Now the "x86" option is available in the Compile settings. You may need to enable "Show advanced build configurations" first, in Tools > Options > Projects and Solutions > General (from this post on MSDN forums)
[ "vb.net", "visual-studio-2008", "64-bit" ]
29
16
22,782
4
0
2008-08-27T13:58:44.913000
2008-08-27T16:06:06.857000
30,184
30,241
Winforms - Click/drag anywhere in the form to move it as if clicked in the form caption
I am creating a small modal form that is used in Winforms application. It is basically a progress bar of sorts. But I would like the user to be able to click anywhere in the form and drag it to move it around on the desktop while it is still being displayed. How can I implement this behavior?
Microsoft KB Article 320687 has a detailed answer to this question. Basically, you override the WndProc method to return HTCAPTION to the WM_NCHITTEST message when the point being tested is in the client area of the form -- which is, in effect, telling Windows to treat the click exactly the same as if it had occured on the caption of the form. private const int WM_NCHITTEST = 0x84; private const int HTCLIENT = 0x1; private const int HTCAPTION = 0x2; protected override void WndProc(ref Message m) { switch(m.Msg) { case WM_NCHITTEST: base.WndProc(ref m); if ((int)m.Result == HTCLIENT) m.Result = (IntPtr)HTCAPTION; return; } base.WndProc(ref m); }
Winforms - Click/drag anywhere in the form to move it as if clicked in the form caption I am creating a small modal form that is used in Winforms application. It is basically a progress bar of sorts. But I would like the user to be able to click anywhere in the form and drag it to move it around on the desktop while it is still being displayed. How can I implement this behavior?
TITLE: Winforms - Click/drag anywhere in the form to move it as if clicked in the form caption QUESTION: I am creating a small modal form that is used in Winforms application. It is basically a progress bar of sorts. But I would like the user to be able to click anywhere in the form and drag it to move it around on the desktop while it is still being displayed. How can I implement this behavior? ANSWER: Microsoft KB Article 320687 has a detailed answer to this question. Basically, you override the WndProc method to return HTCAPTION to the WM_NCHITTEST message when the point being tested is in the client area of the form -- which is, in effect, telling Windows to treat the click exactly the same as if it had occured on the caption of the form. private const int WM_NCHITTEST = 0x84; private const int HTCLIENT = 0x1; private const int HTCAPTION = 0x2; protected override void WndProc(ref Message m) { switch(m.Msg) { case WM_NCHITTEST: base.WndProc(ref m); if ((int)m.Result == HTCLIENT) m.Result = (IntPtr)HTCAPTION; return; } base.WndProc(ref m); }
[ ".net", "winforms" ]
20
27
14,324
5
0
2008-08-27T13:59:01.170000
2008-08-27T14:16:50.533000
30,188
30,231
How can I format a javascript date to be serialized by jQuery
I am trying to set a javascript date so that it can be submitted via JSON to a.NET type, but when attempting to do this, jQuery sets the date to a full string, what format does it have to be in to be converted to a.NET type? var regDate = student.RegistrationDate.getMonth() + "/" + student.RegistrationDate.getDate() + "/" + student.RegistrationDate.getFullYear(); j("#student_registrationdate").val(regDate); // value to serialize I am using MonoRail on the server to perform the binding to a.NET type, that aside I need to know what to set the form hidden field value to, to get properly sent to.NET code.
This MSDN article has some example Date strings that are parse-able is that what you're looking for? string dateString = "5/1/2008 8:30:52 AM"; DateTime date1 = DateTime.Parse(dateString, CultureInfo.InvariantCulture);
How can I format a javascript date to be serialized by jQuery I am trying to set a javascript date so that it can be submitted via JSON to a.NET type, but when attempting to do this, jQuery sets the date to a full string, what format does it have to be in to be converted to a.NET type? var regDate = student.RegistrationDate.getMonth() + "/" + student.RegistrationDate.getDate() + "/" + student.RegistrationDate.getFullYear(); j("#student_registrationdate").val(regDate); // value to serialize I am using MonoRail on the server to perform the binding to a.NET type, that aside I need to know what to set the form hidden field value to, to get properly sent to.NET code.
TITLE: How can I format a javascript date to be serialized by jQuery QUESTION: I am trying to set a javascript date so that it can be submitted via JSON to a.NET type, but when attempting to do this, jQuery sets the date to a full string, what format does it have to be in to be converted to a.NET type? var regDate = student.RegistrationDate.getMonth() + "/" + student.RegistrationDate.getDate() + "/" + student.RegistrationDate.getFullYear(); j("#student_registrationdate").val(regDate); // value to serialize I am using MonoRail on the server to perform the binding to a.NET type, that aside I need to know what to set the form hidden field value to, to get properly sent to.NET code. ANSWER: This MSDN article has some example Date strings that are parse-able is that what you're looking for? string dateString = "5/1/2008 8:30:52 AM"; DateTime date1 = DateTime.Parse(dateString, CultureInfo.InvariantCulture);
[ "c#", "json", "serialization", "date", "castle-monorail" ]
6
2
3,197
3
0
2008-08-27T14:00:18.123000
2008-08-27T14:12:48.780000
30,209
30,221
TFS Lifecycle Management for Build Environment
How would you manage the lifecycle and automated build process when some of the projects ( C#.csproj projects) are part of the actual build system? Example: A.csproj is a project that uses MSBuild tasks that are implemented in BuildEnv.csproj. Both projects are part of the same product (meaning, BuildEnv.csproj frequently changes as the product is being developed and not a 3rd party that is rarely updated)
You must factor this out into two separate "projects" otherwise you'll spend ages chasing your tail trying to find out if a broken build is due to changes in the build system or chages in the code being developed. Previously we've factored the two systems out into separate projects in CVS. You want to be able to vary one thing while keeping the other constant to limit what you would have to look at when performing forensic analysis. Hope that helps.
TFS Lifecycle Management for Build Environment How would you manage the lifecycle and automated build process when some of the projects ( C#.csproj projects) are part of the actual build system? Example: A.csproj is a project that uses MSBuild tasks that are implemented in BuildEnv.csproj. Both projects are part of the same product (meaning, BuildEnv.csproj frequently changes as the product is being developed and not a 3rd party that is rarely updated)
TITLE: TFS Lifecycle Management for Build Environment QUESTION: How would you manage the lifecycle and automated build process when some of the projects ( C#.csproj projects) are part of the actual build system? Example: A.csproj is a project that uses MSBuild tasks that are implemented in BuildEnv.csproj. Both projects are part of the same product (meaning, BuildEnv.csproj frequently changes as the product is being developed and not a 3rd party that is rarely updated) ANSWER: You must factor this out into two separate "projects" otherwise you'll spend ages chasing your tail trying to find out if a broken build is due to changes in the build system or chages in the code being developed. Previously we've factored the two systems out into separate projects in CVS. You want to be able to vary one thing while keeping the other constant to limit what you would have to look at when performing forensic analysis. Hope that helps.
[ "tfs", "msbuild" ]
0
2
502
1
0
2008-08-27T14:06:35.410000
2008-08-27T14:10:44.917000
30,211
30,473
Can Windows' built-in ZIP compression be scripted?
Is the ZIP compression that is built into Windows XP/Vista/2003/2008 able to be scripted at all? What executable would I have to call from a BAT/CMD file? or is it possible to do it with VBScript? I realize that this is possible using WinZip, 7-Zip and other external applications, but I'm looking for something that requires no external applications to be installed.
There are VBA methods to zip and unzip using the windows built in compression as well, which should give some insight as to how the system operates. You may be able to build these methods into a scripting language of your choice. The basic principle is that within windows you can treat a zip file as a directory, and copy into and out of it. So to create a new zip file, you simply make a file with the extension.zip that has the right header for an empty zip file. Then you close it, and tell windows you want to copy files into it as though it were another directory. Unzipping is easier - just treat it as a directory. In case the web pages are lost again, here are a few of the relevant code snippets: ZIP Sub NewZip(sPath) 'Create empty Zip File 'Changed by keepITcool Dec-12-2005 If Len(Dir(sPath)) > 0 Then Kill sPath Open sPath For Output As #1 Print #1, Chr$(80) & Chr$(75) & Chr$(5) & Chr$(6) & String(18, 0) Close #1 End Sub Function bIsBookOpen(ByRef szBookName As String) As Boolean ' Rob Bovey On Error Resume Next bIsBookOpen = Not (Application.Workbooks(szBookName) Is Nothing) End Function Function Split97(sStr As Variant, sdelim As String) As Variant 'Tom Ogilvy Split97 = Evaluate("{""" & _ Application.Substitute(sStr, sdelim, """,""") & """}") End Function Sub Zip_File_Or_Files() Dim strDate As String, DefPath As String, sFName As String Dim oApp As Object, iCtr As Long, I As Integer Dim FName, vArr, FileNameZip DefPath = Application.DefaultFilePath If Right(DefPath, 1) <> "\" Then DefPath = DefPath & "\" End If strDate = Format(Now, " dd-mmm-yy h-mm-ss") FileNameZip = DefPath & "MyFilesZip " & strDate & ".zip" 'Browse to the file(s), use the Ctrl key to select more files FName = Application.GetOpenFilename(filefilter:="Excel Files (*.xl*), *.xl*", _ MultiSelect:=True, Title:="Select the files you want to zip") If IsArray(FName) = False Then 'do nothing Else 'Create empty Zip File NewZip (FileNameZip) Set oApp = CreateObject("Shell.Application") I = 0 For iCtr = LBound(FName) To UBound(FName) vArr = Split97(FName(iCtr), "\") sFName = vArr(UBound(vArr)) If bIsBookOpen(sFName) Then MsgBox "You can't zip a file that is open!" & vbLf & _ "Please close it and try again: " & FName(iCtr) Else 'Copy the file to the compressed folder I = I + 1 oApp.Namespace(FileNameZip).CopyHere FName(iCtr) 'Keep script waiting until Compressing is done On Error Resume Next Do Until oApp.Namespace(FileNameZip).items.Count = I Application.Wait (Now + TimeValue("0:00:01")) Loop On Error GoTo 0 End If Next iCtr MsgBox "You find the zipfile here: " & FileNameZip End If End Sub UNZIP Sub Unzip1() Dim FSO As Object Dim oApp As Object Dim Fname As Variant Dim FileNameFolder As Variant Dim DefPath As String Dim strDate As String Fname = Application.GetOpenFilename(filefilter:="Zip Files (*.zip), *.zip", _ MultiSelect:=False) If Fname = False Then 'Do nothing Else 'Root folder for the new folder. 'You can also use DefPath = "C:\Users\Ron\test\" DefPath = Application.DefaultFilePath If Right(DefPath, 1) <> "\" Then DefPath = DefPath & "\" End If 'Create the folder name strDate = Format(Now, " dd-mm-yy h-mm-ss") FileNameFolder = DefPath & "MyUnzipFolder " & strDate & "\" 'Make the normal folder in DefPath MkDir FileNameFolder 'Extract the files into the newly created folder Set oApp = CreateObject("Shell.Application") oApp.Namespace(FileNameFolder).CopyHere oApp.Namespace(Fname).items 'If you want to extract only one file you can use this: 'oApp.Namespace(FileNameFolder).CopyHere _ 'oApp.Namespace(Fname).items.Item("test.txt") MsgBox "You find the files here: " & FileNameFolder On Error Resume Next Set FSO = CreateObject("scripting.filesystemobject") FSO.deletefolder Environ("Temp") & "\Temporary Directory*", True End If End Sub
Can Windows' built-in ZIP compression be scripted? Is the ZIP compression that is built into Windows XP/Vista/2003/2008 able to be scripted at all? What executable would I have to call from a BAT/CMD file? or is it possible to do it with VBScript? I realize that this is possible using WinZip, 7-Zip and other external applications, but I'm looking for something that requires no external applications to be installed.
TITLE: Can Windows' built-in ZIP compression be scripted? QUESTION: Is the ZIP compression that is built into Windows XP/Vista/2003/2008 able to be scripted at all? What executable would I have to call from a BAT/CMD file? or is it possible to do it with VBScript? I realize that this is possible using WinZip, 7-Zip and other external applications, but I'm looking for something that requires no external applications to be installed. ANSWER: There are VBA methods to zip and unzip using the windows built in compression as well, which should give some insight as to how the system operates. You may be able to build these methods into a scripting language of your choice. The basic principle is that within windows you can treat a zip file as a directory, and copy into and out of it. So to create a new zip file, you simply make a file with the extension.zip that has the right header for an empty zip file. Then you close it, and tell windows you want to copy files into it as though it were another directory. Unzipping is easier - just treat it as a directory. In case the web pages are lost again, here are a few of the relevant code snippets: ZIP Sub NewZip(sPath) 'Create empty Zip File 'Changed by keepITcool Dec-12-2005 If Len(Dir(sPath)) > 0 Then Kill sPath Open sPath For Output As #1 Print #1, Chr$(80) & Chr$(75) & Chr$(5) & Chr$(6) & String(18, 0) Close #1 End Sub Function bIsBookOpen(ByRef szBookName As String) As Boolean ' Rob Bovey On Error Resume Next bIsBookOpen = Not (Application.Workbooks(szBookName) Is Nothing) End Function Function Split97(sStr As Variant, sdelim As String) As Variant 'Tom Ogilvy Split97 = Evaluate("{""" & _ Application.Substitute(sStr, sdelim, """,""") & """}") End Function Sub Zip_File_Or_Files() Dim strDate As String, DefPath As String, sFName As String Dim oApp As Object, iCtr As Long, I As Integer Dim FName, vArr, FileNameZip DefPath = Application.DefaultFilePath If Right(DefPath, 1) <> "\" Then DefPath = DefPath & "\" End If strDate = Format(Now, " dd-mmm-yy h-mm-ss") FileNameZip = DefPath & "MyFilesZip " & strDate & ".zip" 'Browse to the file(s), use the Ctrl key to select more files FName = Application.GetOpenFilename(filefilter:="Excel Files (*.xl*), *.xl*", _ MultiSelect:=True, Title:="Select the files you want to zip") If IsArray(FName) = False Then 'do nothing Else 'Create empty Zip File NewZip (FileNameZip) Set oApp = CreateObject("Shell.Application") I = 0 For iCtr = LBound(FName) To UBound(FName) vArr = Split97(FName(iCtr), "\") sFName = vArr(UBound(vArr)) If bIsBookOpen(sFName) Then MsgBox "You can't zip a file that is open!" & vbLf & _ "Please close it and try again: " & FName(iCtr) Else 'Copy the file to the compressed folder I = I + 1 oApp.Namespace(FileNameZip).CopyHere FName(iCtr) 'Keep script waiting until Compressing is done On Error Resume Next Do Until oApp.Namespace(FileNameZip).items.Count = I Application.Wait (Now + TimeValue("0:00:01")) Loop On Error GoTo 0 End If Next iCtr MsgBox "You find the zipfile here: " & FileNameZip End If End Sub UNZIP Sub Unzip1() Dim FSO As Object Dim oApp As Object Dim Fname As Variant Dim FileNameFolder As Variant Dim DefPath As String Dim strDate As String Fname = Application.GetOpenFilename(filefilter:="Zip Files (*.zip), *.zip", _ MultiSelect:=False) If Fname = False Then 'Do nothing Else 'Root folder for the new folder. 'You can also use DefPath = "C:\Users\Ron\test\" DefPath = Application.DefaultFilePath If Right(DefPath, 1) <> "\" Then DefPath = DefPath & "\" End If 'Create the folder name strDate = Format(Now, " dd-mm-yy h-mm-ss") FileNameFolder = DefPath & "MyUnzipFolder " & strDate & "\" 'Make the normal folder in DefPath MkDir FileNameFolder 'Extract the files into the newly created folder Set oApp = CreateObject("Shell.Application") oApp.Namespace(FileNameFolder).CopyHere oApp.Namespace(Fname).items 'If you want to extract only one file you can use this: 'oApp.Namespace(FileNameFolder).CopyHere _ 'oApp.Namespace(Fname).items.Item("test.txt") MsgBox "You find the files here: " & FileNameFolder On Error Resume Next Set FSO = CreateObject("scripting.filesystemobject") FSO.deletefolder Environ("Temp") & "\Temporary Directory*", True End If End Sub
[ "windows", "vbscript", "batch-file", "zip", "scripting" ]
62
33
111,572
6
0
2008-08-27T14:06:52.133000
2008-08-27T15:38:14.677000
30,222
30,229
SQL Server: Get data for only the past year
I am writing a query in which I have to get the data for only the last year. What is the best way to do this? SELECT... FROM... WHERE date > '8/27/2007 12:00:00 AM'
The following adds -1 years to the current date: SELECT... From... WHERE date > DATEADD(year,-1,GETDATE())
SQL Server: Get data for only the past year I am writing a query in which I have to get the data for only the last year. What is the best way to do this? SELECT... FROM... WHERE date > '8/27/2007 12:00:00 AM'
TITLE: SQL Server: Get data for only the past year QUESTION: I am writing a query in which I have to get the data for only the last year. What is the best way to do this? SELECT... FROM... WHERE date > '8/27/2007 12:00:00 AM' ANSWER: The following adds -1 years to the current date: SELECT... From... WHERE date > DATEADD(year,-1,GETDATE())
[ "sql", "sql-server", "database", "t-sql" ]
134
259
461,962
16
0
2008-08-27T14:10:49.720000
2008-08-27T14:12:28.437000
30,230
32,358
enter key to insert newline in asp.net multiline textbox control
I have some C# / asp.net code I inherited which has a textbox which I want to make multiline. I did so by adding textmode="multiline" but when I try to insert a newline, the enter key instead submits the form:P I googled around and it seems like the default behavior should be for enter (or control-enter) to insert a newline. Like I said I inherited the code so I'm not sure if there's javascript monkeying around or if there's just a simple asp.net thing I have to do.
It turns out this is a bug with Firefox + ASP.NET where the generated javascript for the defaultButton stuff doesn't work in Firefox. I had to put a replacement for the WebForm_FireDefatultButton function as described here: function WebForm_FireDefaultButton(event, target) { var element = event.target || event.srcElement; if (event.keyCode == 13 &&!(element && element.tagName.toLowerCase() == "textarea")) { var defaultButton; if (__nonMSDOMBrowser) { defaultButton = document.getElementById(target); } else { defaultButton = document.all[target]; } if (defaultButton && typeof defaultButton.click!= "undefined") { defaultButton.click(); event.cancelBubble = true; if (event.stopPropagation) { event.stopPropagation(); } return false; } } return true; }
enter key to insert newline in asp.net multiline textbox control I have some C# / asp.net code I inherited which has a textbox which I want to make multiline. I did so by adding textmode="multiline" but when I try to insert a newline, the enter key instead submits the form:P I googled around and it seems like the default behavior should be for enter (or control-enter) to insert a newline. Like I said I inherited the code so I'm not sure if there's javascript monkeying around or if there's just a simple asp.net thing I have to do.
TITLE: enter key to insert newline in asp.net multiline textbox control QUESTION: I have some C# / asp.net code I inherited which has a textbox which I want to make multiline. I did so by adding textmode="multiline" but when I try to insert a newline, the enter key instead submits the form:P I googled around and it seems like the default behavior should be for enter (or control-enter) to insert a newline. Like I said I inherited the code so I'm not sure if there's javascript monkeying around or if there's just a simple asp.net thing I have to do. ANSWER: It turns out this is a bug with Firefox + ASP.NET where the generated javascript for the defaultButton stuff doesn't work in Firefox. I had to put a replacement for the WebForm_FireDefatultButton function as described here: function WebForm_FireDefaultButton(event, target) { var element = event.target || event.srcElement; if (event.keyCode == 13 &&!(element && element.tagName.toLowerCase() == "textarea")) { var defaultButton; if (__nonMSDOMBrowser) { defaultButton = document.getElementById(target); } else { defaultButton = document.all[target]; } if (defaultButton && typeof defaultButton.click!= "undefined") { defaultButton.click(); event.cancelBubble = true; if (event.stopPropagation) { event.stopPropagation(); } return false; } } return true; }
[ "asp.net" ]
3
4
22,393
9
0
2008-08-27T14:12:30.717000
2008-08-28T14:16:01.743000
30,239
30,285
WPF setting a MenuItem.Icon in code
I have an images folder with a png in it. I would like to set a MenuItem's icon to that png. How do I write this in procedural code?
menutItem.Icon = new System.Windows.Controls.Image { Source = new BitmapImage(new Uri("images/sample.png", UriKind.Relative)) };
WPF setting a MenuItem.Icon in code I have an images folder with a png in it. I would like to set a MenuItem's icon to that png. How do I write this in procedural code?
TITLE: WPF setting a MenuItem.Icon in code QUESTION: I have an images folder with a png in it. I would like to set a MenuItem's icon to that png. How do I write this in procedural code? ANSWER: menutItem.Icon = new System.Windows.Controls.Image { Source = new BitmapImage(new Uri("images/sample.png", UriKind.Relative)) };
[ "c#", "wpf", "icons", "menuitem" ]
40
68
61,049
8
0
2008-08-27T14:16:08.133000
2008-08-27T14:31:47.487000
30,251
30,271
Tables instead of DIVs
Possible Duplicate: Why not use tables for layout in HTML? Under what conditions should you choose tables instead of DIVs in HTML coding?
The whole "Tables vs Divs" thing just barely misses the mark. It's not "table" or "div". It's about using semantic html. Even the div tag plays only a small part in a well laid out page. Don't overuse it. You shouldn't need that many if you put your html together correctly. Things like lists, field sets, legends, labels, paragraphs, etc can replace much of what a div or span is often used to accomplish. Div should be used primarily when it makes sense to indicate a logical div ision, and only appropriated for extra layout when absolutely necessary. The same is true for table; use it when you have tabular data, but not otherwise. Then you have a more semantic page and you don't need quite as many classes defined in your CSS; you can target the tags directly instead. Possibly most importantly, you have a page that will score much better with Google (anecdotally) than the equivalent table or div-heavy page. Most of all it will help you better connect with a portion of your audience. So if we go back and look at it in terms of table vs div, it's my opinion that we've actually come to the point where div is over-used and table is under-used. Why? Because when you really think about it, there are a lot of things out there that fall into the category of "tabular data" that tend to be overlooked. Answers and comments on this very web page, for example. They consist of multiple records, each with the same set of fields. They're even stored in a sql server table, for crying out loud. This is the exact definition of tabular data. This means an html table tag would absolutely be a good semantic choice to layout something like the posts here on Stack Overflow. The same principle applies to many other things as well. It may not be a good idea to use a table tag to set up a three column layout, but it's certainly just fine to use it for grids and lists... except, of course, when you can actually use the ol or ul (list) tags.
Tables instead of DIVs Possible Duplicate: Why not use tables for layout in HTML? Under what conditions should you choose tables instead of DIVs in HTML coding?
TITLE: Tables instead of DIVs QUESTION: Possible Duplicate: Why not use tables for layout in HTML? Under what conditions should you choose tables instead of DIVs in HTML coding? ANSWER: The whole "Tables vs Divs" thing just barely misses the mark. It's not "table" or "div". It's about using semantic html. Even the div tag plays only a small part in a well laid out page. Don't overuse it. You shouldn't need that many if you put your html together correctly. Things like lists, field sets, legends, labels, paragraphs, etc can replace much of what a div or span is often used to accomplish. Div should be used primarily when it makes sense to indicate a logical div ision, and only appropriated for extra layout when absolutely necessary. The same is true for table; use it when you have tabular data, but not otherwise. Then you have a more semantic page and you don't need quite as many classes defined in your CSS; you can target the tags directly instead. Possibly most importantly, you have a page that will score much better with Google (anecdotally) than the equivalent table or div-heavy page. Most of all it will help you better connect with a portion of your audience. So if we go back and look at it in terms of table vs div, it's my opinion that we've actually come to the point where div is over-used and table is under-used. Why? Because when you really think about it, there are a lot of things out there that fall into the category of "tabular data" that tend to be overlooked. Answers and comments on this very web page, for example. They consist of multiple records, each with the same set of fields. They're even stored in a sql server table, for crying out loud. This is the exact definition of tabular data. This means an html table tag would absolutely be a good semantic choice to layout something like the posts here on Stack Overflow. The same principle applies to many other things as well. It may not be a good idea to use a table tag to set up a three column layout, but it's certainly just fine to use it for grids and lists... except, of course, when you can actually use the ol or ul (list) tags.
[ "html", "css" ]
116
198
19,682
24
0
2008-08-27T14:19:44.583000
2008-08-27T14:25:11.543000
30,281
32,303
How Popular is the Seam Framework
I'm using JBoss Seam Framework, but it's seems to me isn't very popular among java developers. I want to know how many java programmers here are using it, and in what kind of projects. Is as good as django, or RoR?
In our JBoss Seam in Action presentation at the Javapolis conference last year, my colleague and I said that 'Seam is the next Struts'. This needed some explanation, which I later wrote-up as Seam is the new Struts. Needless to say, we like Seam. One indication of Seam's popularity is the level of traffic on the Seam Users Forum.
How Popular is the Seam Framework I'm using JBoss Seam Framework, but it's seems to me isn't very popular among java developers. I want to know how many java programmers here are using it, and in what kind of projects. Is as good as django, or RoR?
TITLE: How Popular is the Seam Framework QUESTION: I'm using JBoss Seam Framework, but it's seems to me isn't very popular among java developers. I want to know how many java programmers here are using it, and in what kind of projects. Is as good as django, or RoR? ANSWER: In our JBoss Seam in Action presentation at the Javapolis conference last year, my colleague and I said that 'Seam is the next Struts'. This needed some explanation, which I later wrote-up as Seam is the new Struts. Needless to say, we like Seam. One indication of Seam's popularity is the level of traffic on the Seam Users Forum.
[ "java", "frameworks", "seam" ]
21
15
11,236
12
0
2008-08-27T14:30:29.987000
2008-08-28T13:41:16.070000
30,286
30,301
NullReferenceException on User Control handle
I have an Asp.NET application (VS2008, Framework 2.0). When I try to set a property on one of the user controls like myUserControl.SomeProperty = someValue; I get a NullReferenceException. When I debug, I found out that myUserControl is null. How is it possible that a user control handle is null? How do I fix this or how do I find what causes this?
Where are you trying to access the property? If you are in onInit, the control may not be loaded yet.
NullReferenceException on User Control handle I have an Asp.NET application (VS2008, Framework 2.0). When I try to set a property on one of the user controls like myUserControl.SomeProperty = someValue; I get a NullReferenceException. When I debug, I found out that myUserControl is null. How is it possible that a user control handle is null? How do I fix this or how do I find what causes this?
TITLE: NullReferenceException on User Control handle QUESTION: I have an Asp.NET application (VS2008, Framework 2.0). When I try to set a property on one of the user controls like myUserControl.SomeProperty = someValue; I get a NullReferenceException. When I debug, I found out that myUserControl is null. How is it possible that a user control handle is null? How do I fix this or how do I find what causes this? ANSWER: Where are you trying to access the property? If you are in onInit, the control may not be loaded yet.
[ "asp.net", "user-controls" ]
2
5
2,000
4
0
2008-08-27T14:31:57.707000
2008-08-27T14:38:02.573000
30,288
130,971
How can you test to see if two arrays are the same using CFML?
Using CFML (ColdFusion Markup Langauge, aka ColdFusion), how can you compare if two single dimension arrays are the same?
Assuming all of the values in the array are simple values, the easiest thing might be to convert the arrays to lists and just do string compares. Arrays are equal! Not as elegant as other solutions offered, but dead simple.
How can you test to see if two arrays are the same using CFML? Using CFML (ColdFusion Markup Langauge, aka ColdFusion), how can you compare if two single dimension arrays are the same?
TITLE: How can you test to see if two arrays are the same using CFML? QUESTION: Using CFML (ColdFusion Markup Langauge, aka ColdFusion), how can you compare if two single dimension arrays are the same? ANSWER: Assuming all of the values in the array are simple values, the easiest thing might be to convert the arrays to lists and just do string compares. Arrays are equal! Not as elegant as other solutions offered, but dead simple.
[ "coldfusion" ]
5
2
5,596
7
0
2008-08-27T14:32:52.743000
2008-09-25T01:24:35.910000
30,302
30,551
Asp.Net Routing: How do I ignore multiple wildcard routes?
I'd like to ignore multiple wildcard routes. With asp.net mvc preview 4, they ship with: RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); I'd also like to add something like: RouteTable.Routes.IgnoreRoute("Content/{*pathInfo}"); but that seems to break some of the helpers that generate urls in my program. Thoughts?
There are two possible solutions here. Add a constraint to the ignore route to make sure that only requests that should be ignored would match that route. Kinda kludgy, but it should work. RouteTable.Routes.IgnoreRoute("{folder}/{*pathInfo}", new {folder="content"}); What is in your content directory? By default, Routing does not route files that exist on disk (actually checks the VirtualPathProvider). So if you are putting static content in the Content directory, you might not need the ignore route.
Asp.Net Routing: How do I ignore multiple wildcard routes? I'd like to ignore multiple wildcard routes. With asp.net mvc preview 4, they ship with: RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); I'd also like to add something like: RouteTable.Routes.IgnoreRoute("Content/{*pathInfo}"); but that seems to break some of the helpers that generate urls in my program. Thoughts?
TITLE: Asp.Net Routing: How do I ignore multiple wildcard routes? QUESTION: I'd like to ignore multiple wildcard routes. With asp.net mvc preview 4, they ship with: RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); I'd also like to add something like: RouteTable.Routes.IgnoreRoute("Content/{*pathInfo}"); but that seems to break some of the helpers that generate urls in my program. Thoughts? ANSWER: There are two possible solutions here. Add a constraint to the ignore route to make sure that only requests that should be ignored would match that route. Kinda kludgy, but it should work. RouteTable.Routes.IgnoreRoute("{folder}/{*pathInfo}", new {folder="content"}); What is in your content directory? By default, Routing does not route files that exist on disk (actually checks the VirtualPathProvider). So if you are putting static content in the Content directory, you might not need the ignore route.
[ "c#", "asp.net", "asp.net-mvc", "routes" ]
12
15
10,860
2
0
2008-08-27T14:38:39.327000
2008-08-27T16:07:54.293000
30,310
540,583
Asp.Net MVC: How do I enable dashes in my urls?
I'd like to have dashes separate words in my URLs. So instead of: /MyController/MyAction I'd like: /My-Controller/My-Action Is this possible?
You can use the ActionName attribute like so: [ActionName("My-Action")] public ActionResult MyAction() { return View(); } Note that you will then need to call your View file "My-Action.cshtml" (or appropriate extension). You will also need to reference "my-action" in any Html.ActionLink methods. There isn't such a simple solution for controllers. Edit: Update for MVC5 Enable the routes globally: public static void RegisterRoutes(RouteCollection routes) { routes.MapMvcAttributeRoutes(); // routes.MapRoute... } Now with MVC5, Attribute Routing has been absorbed into the project. You can now use: [Route("My-Action")] On Action Methods. For controllers, you can apply a RoutePrefix attribute which will be applied to all action methods in that controller: [RoutePrefix("my-controller")] One of the benefits of using RoutePrefix is URL parameters will also be passed down to any action methods. [RoutePrefix("clients/{clientId:int}")] public class ClientsController: Controller..... Snip.. [Route("edit-client")] public ActionResult Edit(int clientId) // will match /clients/123/edit-client
Asp.Net MVC: How do I enable dashes in my urls? I'd like to have dashes separate words in my URLs. So instead of: /MyController/MyAction I'd like: /My-Controller/My-Action Is this possible?
TITLE: Asp.Net MVC: How do I enable dashes in my urls? QUESTION: I'd like to have dashes separate words in my URLs. So instead of: /MyController/MyAction I'd like: /My-Controller/My-Action Is this possible? ANSWER: You can use the ActionName attribute like so: [ActionName("My-Action")] public ActionResult MyAction() { return View(); } Note that you will then need to call your View file "My-Action.cshtml" (or appropriate extension). You will also need to reference "my-action" in any Html.ActionLink methods. There isn't such a simple solution for controllers. Edit: Update for MVC5 Enable the routes globally: public static void RegisterRoutes(RouteCollection routes) { routes.MapMvcAttributeRoutes(); // routes.MapRoute... } Now with MVC5, Attribute Routing has been absorbed into the project. You can now use: [Route("My-Action")] On Action Methods. For controllers, you can apply a RoutePrefix attribute which will be applied to all action methods in that controller: [RoutePrefix("my-controller")] One of the benefits of using RoutePrefix is URL parameters will also be passed down to any action methods. [RoutePrefix("clients/{clientId:int}")] public class ClientsController: Controller..... Snip.. [Route("edit-client")] public ActionResult Edit(int clientId) // will match /clients/123/edit-client
[ "asp.net-mvc" ]
78
157
26,024
9
0
2008-08-27T14:41:31.443000
2009-02-12T09:17:01.183000
30,318
4,155,764
Where can I find a graphical command shell?
Terminals and shells are very powerful but can be complicated to learn, especially to get the best out of them. Does anyone know of a more GUI based command shell that helps a user or displays answers in a more friendly way? I'm aware of IPython, but even the syntax of that is somewhat convoluted, although it's a step in the right direction. Further to this, results could be presented graphically, e.g. wouldn't it be nice to be able to pipe file sizes into a pie chart?
I found POSH, a GUI for MS PowerShell. This is pretty much what I intended. You have a command-line backend with a WPF GUI frontend. You can pipe results from command to the next and show graphical output.
Where can I find a graphical command shell? Terminals and shells are very powerful but can be complicated to learn, especially to get the best out of them. Does anyone know of a more GUI based command shell that helps a user or displays answers in a more friendly way? I'm aware of IPython, but even the syntax of that is somewhat convoluted, although it's a step in the right direction. Further to this, results could be presented graphically, e.g. wouldn't it be nice to be able to pipe file sizes into a pie chart?
TITLE: Where can I find a graphical command shell? QUESTION: Terminals and shells are very powerful but can be complicated to learn, especially to get the best out of them. Does anyone know of a more GUI based command shell that helps a user or displays answers in a more friendly way? I'm aware of IPython, but even the syntax of that is somewhat convoluted, although it's a step in the right direction. Further to this, results could be presented graphically, e.g. wouldn't it be nice to be able to pipe file sizes into a pie chart? ANSWER: I found POSH, a GUI for MS PowerShell. This is pretty much what I intended. You have a command-line backend with a WPF GUI frontend. You can pipe results from command to the next and show graphical output.
[ "user-interface", "shell", "terminal" ]
9
0
3,880
13
0
2008-08-27T14:43:31.983000
2010-11-11T15:03:37.090000
30,319
30,324
Is there a HTML opposite to <noscript>?
Is there a tag in HTML that will only display its content if JavaScript is enabled? I know works the opposite way around, displaying its HTML content when JavaScript is turned off. But I would like to only display a form on a site if JavaScript is available, telling them why they can't use the form if they don't have it. The only way I know how to do this is with the document.write(); method in a script tag, and it seems a bit messy for large amounts of HTML.
You could have an invisible div that gets shown via JavaScript when the page loads.
Is there a HTML opposite to <noscript>? Is there a tag in HTML that will only display its content if JavaScript is enabled? I know works the opposite way around, displaying its HTML content when JavaScript is turned off. But I would like to only display a form on a site if JavaScript is available, telling them why they can't use the form if they don't have it. The only way I know how to do this is with the document.write(); method in a script tag, and it seems a bit messy for large amounts of HTML.
TITLE: Is there a HTML opposite to <noscript>? QUESTION: Is there a tag in HTML that will only display its content if JavaScript is enabled? I know works the opposite way around, displaying its HTML content when JavaScript is turned off. But I would like to only display a form on a site if JavaScript is available, telling them why they can't use the form if they don't have it. The only way I know how to do this is with the document.write(); method in a script tag, and it seems a bit messy for large amounts of HTML. ANSWER: You could have an invisible div that gets shown via JavaScript when the page loads.
[ "javascript", "html", "noscript" ]
128
63
22,823
12
0
2008-08-27T14:44:02.373000
2008-08-27T14:46:09.527000
30,321
30,326
How to store Application Messages for a .NET Website
I am looking for a method of storing Application Messages, such as "You have logged in successfully" "An error has occurred, please call the helpdesk on x100" "You do not have the authority to reset all system passwords" etc So that "when" the users decide they don't like the wording of messages I don't have to change the source code, recompile then redeploy - instead I just change the message store. I really like the way that I can easily access strings in the web.config using keys and values. ConfigurationManager.AppSettings("LOGINSUCCESS"); However as I could have a large number of application messages I didn't want to use the web.config directly. I was going to add a 2nd web config file and use that but of course you can only have one per virtual directory. Does anyone have any suggestions on how to do this without writing much custom code?
In your Web.config, under appSettings, change it to: Then, create your StringKeys.config file and have all your keys in it. You can still use the AppSettings area in the main web.config for any real application related keys.
How to store Application Messages for a .NET Website I am looking for a method of storing Application Messages, such as "You have logged in successfully" "An error has occurred, please call the helpdesk on x100" "You do not have the authority to reset all system passwords" etc So that "when" the users decide they don't like the wording of messages I don't have to change the source code, recompile then redeploy - instead I just change the message store. I really like the way that I can easily access strings in the web.config using keys and values. ConfigurationManager.AppSettings("LOGINSUCCESS"); However as I could have a large number of application messages I didn't want to use the web.config directly. I was going to add a 2nd web config file and use that but of course you can only have one per virtual directory. Does anyone have any suggestions on how to do this without writing much custom code?
TITLE: How to store Application Messages for a .NET Website QUESTION: I am looking for a method of storing Application Messages, such as "You have logged in successfully" "An error has occurred, please call the helpdesk on x100" "You do not have the authority to reset all system passwords" etc So that "when" the users decide they don't like the wording of messages I don't have to change the source code, recompile then redeploy - instead I just change the message store. I really like the way that I can easily access strings in the web.config using keys and values. ConfigurationManager.AppSettings("LOGINSUCCESS"); However as I could have a large number of application messages I didn't want to use the web.config directly. I was going to add a 2nd web config file and use that but of course you can only have one per virtual directory. Does anyone have any suggestions on how to do this without writing much custom code? ANSWER: In your Web.config, under appSettings, change it to: Then, create your StringKeys.config file and have all your keys in it. You can still use the AppSettings area in the main web.config for any real application related keys.
[ "vb.net", "resources" ]
2
6
317
3
0
2008-08-27T14:44:25.240000
2008-08-27T14:46:16.750000
30,328
30,685
OCR with the Tesseract interface
How do you OCR an tiff file using Tesseract's interface in c#? Currently I only know how to do it using the executable.
The source code seemed to be geared for an executable, you might need to rewire stuffs a bit so it would build as a DLL instead. I don't have much experience with Visual C++ but I think it shouldn't be too hard with some research. My guess is that someone might have had made a library version already, you should try Google. Once you have tesseract-ocr code in a DLL file, you can then import the file into your C# project via Visual Studio and have it create wrapper classes and do all the marshaling stuffs for you. If you can't import then DllImport will let you call the functions in the DLL from C# code. Then you can take a look at the original executable to find clues on what functions to call to properly OCR a tiff image.
OCR with the Tesseract interface How do you OCR an tiff file using Tesseract's interface in c#? Currently I only know how to do it using the executable.
TITLE: OCR with the Tesseract interface QUESTION: How do you OCR an tiff file using Tesseract's interface in c#? Currently I only know how to do it using the executable. ANSWER: The source code seemed to be geared for an executable, you might need to rewire stuffs a bit so it would build as a DLL instead. I don't have much experience with Visual C++ but I think it shouldn't be too hard with some research. My guess is that someone might have had made a library version already, you should try Google. Once you have tesseract-ocr code in a DLL file, you can then import the file into your C# project via Visual Studio and have it create wrapper classes and do all the marshaling stuffs for you. If you can't import then DllImport will let you call the functions in the DLL from C# code. Then you can take a look at the original executable to find clues on what functions to call to properly OCR a tiff image.
[ "c#", "ocr", "tesseract" ]
33
10
59,702
5
0
2008-08-27T14:46:28.043000
2008-08-27T17:26:42.807000
30,342
31,734
Why do I receive a q[num] error when aborting a jQuery queue pipeline?
When creating and executing a ajax request queue with $.manageAjax, I call ajaxManager.abort();, to abort the entire queue due to error, at which time I get an error stating: q[num] has no properties (jquery.ajaxmanager.js line 75) Here is the calling code: var ajaxManager = $.manageAjax({manageType:'sync', maxReq:0}); // setup code calling ajaxManager.add(...) // in success callback of first request ajaxManager.abort(); <-- causes error in jquery.ajaxManager.js There are 4 requests in the queue, this is being called in the success of the first request, if certain criteria is met, the queue needs to be aborted. Any ideas?
It looks like you've got fewer items in q than you were expecting when you started iterating. Your script may be trying to access q[q.length], i.e. the element after the last element. Could it be that your successful request has been popped from the queue, and you have a race condition? Are you trying to abort a request that has already completed its life cycle? Alternatively, have you made a silly mistake as people sometimes do, and got your loop termination condition wrong? Just a few thoughts, I hope they help.
Why do I receive a q[num] error when aborting a jQuery queue pipeline? When creating and executing a ajax request queue with $.manageAjax, I call ajaxManager.abort();, to abort the entire queue due to error, at which time I get an error stating: q[num] has no properties (jquery.ajaxmanager.js line 75) Here is the calling code: var ajaxManager = $.manageAjax({manageType:'sync', maxReq:0}); // setup code calling ajaxManager.add(...) // in success callback of first request ajaxManager.abort(); <-- causes error in jquery.ajaxManager.js There are 4 requests in the queue, this is being called in the success of the first request, if certain criteria is met, the queue needs to be aborted. Any ideas?
TITLE: Why do I receive a q[num] error when aborting a jQuery queue pipeline? QUESTION: When creating and executing a ajax request queue with $.manageAjax, I call ajaxManager.abort();, to abort the entire queue due to error, at which time I get an error stating: q[num] has no properties (jquery.ajaxmanager.js line 75) Here is the calling code: var ajaxManager = $.manageAjax({manageType:'sync', maxReq:0}); // setup code calling ajaxManager.add(...) // in success callback of first request ajaxManager.abort(); <-- causes error in jquery.ajaxManager.js There are 4 requests in the queue, this is being called in the success of the first request, if certain criteria is met, the queue needs to be aborted. Any ideas? ANSWER: It looks like you've got fewer items in q than you were expecting when you started iterating. Your script may be trying to access q[q.length], i.e. the element after the last element. Could it be that your successful request has been popped from the queue, and you have a race condition? Are you trying to abort a request that has already completed its life cycle? Alternatively, have you made a silly mistake as people sometimes do, and got your loop termination condition wrong? Just a few thoughts, I hope they help.
[ "jquery", "ajax" ]
2
1
568
1
0
2008-08-27T14:49:44.747000
2008-08-28T06:46:26.397000
30,346
30,360
Fixed page layout in IE6
Header, footer and sidebars have fixed position. In the center a content area with both scroll bars. No outer scroll bars on the browser. I have a layout that works in IE7 and FF. I need to add IE6 support. How can I make this work? Here is an approximation of my current CSS. Layout
Might be overkill for your project, but Dean Edwards' IE7 javascript adds support for fixed positioning to IE6.
Fixed page layout in IE6 Header, footer and sidebars have fixed position. In the center a content area with both scroll bars. No outer scroll bars on the browser. I have a layout that works in IE7 and FF. I need to add IE6 support. How can I make this work? Here is an approximation of my current CSS. Layout
TITLE: Fixed page layout in IE6 QUESTION: Header, footer and sidebars have fixed position. In the center a content area with both scroll bars. No outer scroll bars on the browser. I have a layout that works in IE7 and FF. I need to add IE6 support. How can I make this work? Here is an approximation of my current CSS. Layout ANSWER: Might be overkill for your project, but Dean Edwards' IE7 javascript adds support for fixed positioning to IE6.
[ "html", "css", "xhtml", "internet-explorer-6" ]
4
5
1,814
5
0
2008-08-27T14:50:58.643000
2008-08-27T14:56:46.193000
30,354
30,679
When must I set a variable to "Nothing" in VB6?
In one of my VB6 forms, I create several other Form objects and store them in member variables. Private m_frm1 as MyForm Private m_frm2 as MyForm // Later... Set m_frm1 = New MyForm Set m_frm2 = New MyForm I notice that I'm leaking memory whenever this (parent) form is created and destroyed. Is it necessary for me to assign these member variables to Nothing in Form_Unload()? In general, when is that required? SOLVED: This particular memory leak was fixed when I did an Unload on the forms in question, not when I set the form to Nothing. I managed to remove a few other memory leaks by explicitly setting some instances of Class Modules to Nothing, as well.
@Matt Dillard - Did setting these to nothing fix your memory leak? VB6 doesn't have a formal garbage collector, more along the lines of what @Konrad Rudolph said. Actually calling unload on your forms seems to me to be the best way to ensure that the main form is cleaned up and that each subform cleans up their actions. I tested this with a blank project and two blank forms. Private Sub Form_Load() Dim frm As Form2 Set frm = New Form2 frm.Show Set frm = Nothing End Sub After running both forms are left visible. setting frm to nothing did well... nothing. After settign frm to nothing, the only handle open to this form is via the reference. Unload Forms(1) Am I seeing the problem correctly? Josh
When must I set a variable to "Nothing" in VB6? In one of my VB6 forms, I create several other Form objects and store them in member variables. Private m_frm1 as MyForm Private m_frm2 as MyForm // Later... Set m_frm1 = New MyForm Set m_frm2 = New MyForm I notice that I'm leaking memory whenever this (parent) form is created and destroyed. Is it necessary for me to assign these member variables to Nothing in Form_Unload()? In general, when is that required? SOLVED: This particular memory leak was fixed when I did an Unload on the forms in question, not when I set the form to Nothing. I managed to remove a few other memory leaks by explicitly setting some instances of Class Modules to Nothing, as well.
TITLE: When must I set a variable to "Nothing" in VB6? QUESTION: In one of my VB6 forms, I create several other Form objects and store them in member variables. Private m_frm1 as MyForm Private m_frm2 as MyForm // Later... Set m_frm1 = New MyForm Set m_frm2 = New MyForm I notice that I'm leaking memory whenever this (parent) form is created and destroyed. Is it necessary for me to assign these member variables to Nothing in Form_Unload()? In general, when is that required? SOLVED: This particular memory leak was fixed when I did an Unload on the forms in question, not when I set the form to Nothing. I managed to remove a few other memory leaks by explicitly setting some instances of Class Modules to Nothing, as well. ANSWER: @Matt Dillard - Did setting these to nothing fix your memory leak? VB6 doesn't have a formal garbage collector, more along the lines of what @Konrad Rudolph said. Actually calling unload on your forms seems to me to be the best way to ensure that the main form is cleaned up and that each subform cleans up their actions. I tested this with a blank project and two blank forms. Private Sub Form_Load() Dim frm As Form2 Set frm = New Form2 frm.Show Set frm = Nothing End Sub After running both forms are left visible. setting frm to nothing did well... nothing. After settign frm to nothing, the only handle open to this form is via the reference. Unload Forms(1) Am I seeing the problem correctly? Josh
[ "vb6", "memory-leaks" ]
10
8
21,769
8
0
2008-08-27T14:54:52.423000
2008-08-27T17:23:30.600000
30,373
30,420
What C++ pitfalls should I avoid?
I remember first learning about vectors in the STL and after some time, I wanted to use a vector of bools for one of my projects. After seeing some strange behavior and doing some research, I learned that a vector of bools is not really a vector of bools. Are there any other common pitfalls to avoid in C++?
A short list might be: Avoid memory leaks through use shared pointers to manage memory allocation and cleanup Use the Resource Acquisition Is Initialization (RAII) idiom to manage resource cleanup - especially in the presence of exceptions Avoid calling virtual functions in constructors Employ minimalist coding techniques where possible - for example, declaring variables only when needed, scoping variables, and early-out design where possible. Truly understand the exception handling in your code - both with regard to exceptions you throw, as well as ones thrown by classes you may be using indirectly. This is especially important in the presence of templates. RAII, shared pointers and minimalist coding are of course not specific to C++, but they help avoid problems that do frequently crop up when developing in the language. Some excellent books on this subject are: Effective C++ - Scott Meyers More Effective C++ - Scott Meyers C++ Coding Standards - Sutter & Alexandrescu C++ FAQs - Cline Reading these books has helped me more than anything else to avoid the kind of pitfalls you are asking about.
What C++ pitfalls should I avoid? I remember first learning about vectors in the STL and after some time, I wanted to use a vector of bools for one of my projects. After seeing some strange behavior and doing some research, I learned that a vector of bools is not really a vector of bools. Are there any other common pitfalls to avoid in C++?
TITLE: What C++ pitfalls should I avoid? QUESTION: I remember first learning about vectors in the STL and after some time, I wanted to use a vector of bools for one of my projects. After seeing some strange behavior and doing some research, I learned that a vector of bools is not really a vector of bools. Are there any other common pitfalls to avoid in C++? ANSWER: A short list might be: Avoid memory leaks through use shared pointers to manage memory allocation and cleanup Use the Resource Acquisition Is Initialization (RAII) idiom to manage resource cleanup - especially in the presence of exceptions Avoid calling virtual functions in constructors Employ minimalist coding techniques where possible - for example, declaring variables only when needed, scoping variables, and early-out design where possible. Truly understand the exception handling in your code - both with regard to exceptions you throw, as well as ones thrown by classes you may be using indirectly. This is especially important in the presence of templates. RAII, shared pointers and minimalist coding are of course not specific to C++, but they help avoid problems that do frequently crop up when developing in the language. Some excellent books on this subject are: Effective C++ - Scott Meyers More Effective C++ - Scott Meyers C++ Coding Standards - Sutter & Alexandrescu C++ FAQs - Cline Reading these books has helped me more than anything else to avoid the kind of pitfalls you are asking about.
[ "c++", "stl" ]
76
76
18,681
29
0
2008-08-27T15:03:00.173000
2008-08-27T15:17:15.537000
30,379
30,394
How do I replicate content on a web farm
We have a Windows Server Web Edition 2003 Web Farm. What can we use that handles replication across the servers for: Content & IIS Configuration (App Pools, Virtual Directories, etc...) We will be moving to Windows 2008 in the near future, so I guess what options are there on Windows 2008 as well.
I'd look into Windows Distributed File System. It should be supported by both Windows Server 2003 & 2008.
How do I replicate content on a web farm We have a Windows Server Web Edition 2003 Web Farm. What can we use that handles replication across the servers for: Content & IIS Configuration (App Pools, Virtual Directories, etc...) We will be moving to Windows 2008 in the near future, so I guess what options are there on Windows 2008 as well.
TITLE: How do I replicate content on a web farm QUESTION: We have a Windows Server Web Edition 2003 Web Farm. What can we use that handles replication across the servers for: Content & IIS Configuration (App Pools, Virtual Directories, etc...) We will be moving to Windows 2008 in the near future, so I guess what options are there on Windows 2008 as well. ANSWER: I'd look into Windows Distributed File System. It should be supported by both Windows Server 2003 & 2008.
[ "iis", "replication", "webserver" ]
3
1
1,559
2
0
2008-08-27T15:05:51.650000
2008-08-27T15:10:21.497000
30,430
30,432
Moving from Visual Studio 2005 to 2008 and .NET 2.0
I'm currently using VS2005 Profesional and.NET 2.0, and since our project is rather large (25 projects in the solution), I'd like to try VS 2008, since its theoretically faster with larger projects. Before doing such thing, i'd like to know if what I've read is true: can I use VS2008 in ".net 2.0" mode? I don't want my customers to install.net 3.0 or.3.5, I just want to install VS2008, open my solution and start working from there. Is this possible? P.D.: the solution is a c# Window Forms project.
yes, vs2008 can " target " a framework, but i think by default, if converting from vs2005 - vs2008 it just keeps it at framework 2.0
Moving from Visual Studio 2005 to 2008 and .NET 2.0 I'm currently using VS2005 Profesional and.NET 2.0, and since our project is rather large (25 projects in the solution), I'd like to try VS 2008, since its theoretically faster with larger projects. Before doing such thing, i'd like to know if what I've read is true: can I use VS2008 in ".net 2.0" mode? I don't want my customers to install.net 3.0 or.3.5, I just want to install VS2008, open my solution and start working from there. Is this possible? P.D.: the solution is a c# Window Forms project.
TITLE: Moving from Visual Studio 2005 to 2008 and .NET 2.0 QUESTION: I'm currently using VS2005 Profesional and.NET 2.0, and since our project is rather large (25 projects in the solution), I'd like to try VS 2008, since its theoretically faster with larger projects. Before doing such thing, i'd like to know if what I've read is true: can I use VS2008 in ".net 2.0" mode? I don't want my customers to install.net 3.0 or.3.5, I just want to install VS2008, open my solution and start working from there. Is this possible? P.D.: the solution is a c# Window Forms project. ANSWER: yes, vs2008 can " target " a framework, but i think by default, if converting from vs2005 - vs2008 it just keeps it at framework 2.0
[ "c#", ".net", "visual-studio", ".net-3.5", ".net-2.0" ]
8
3
742
7
0
2008-08-27T15:22:52.590000
2008-08-27T15:24:20.887000
30,454
30,586
Parsing XML Elements & Attributes with Perl
So I wrote some perl that would parse results returned from the Amazon Web Services. I am using the XML::Simple package. For the most part, everything worked when I pulled out an element. However, the problem I ran into was when an element had an attribute as well. Then I get an error that the item is a Hash. Here's what I did if I wanted to get the Running Time for a DVD: I just created an item to hold the specific info for this one-off item. // XML DVD 90 // Perl to parse XML my $item = $xml->XMLin($content, KeyAttr => { Item => 'ASIN'}, ForceArray => ['ASIN']); $ProductGroup = $item->{Items}->{Item}->{ItemAttributes}->{ProductGroup}; if(ref($item->{Items}->{Item}->{ItemAttributes}->{RunningTime}) eq 'HASH'){ $RunningTimeXML = $xml->XMLin($content, KeyAttr => { Item => 'ASIN'}, NoAttr => 1); $RunningTime = $RunningTimeXML->{Items}->{Item}->{ItemAttributes}->{RunningTime}; } Is there a way I can access both elements and attributes from one item?
$item is a hashref that looks like this: $item = { 'RunningTime' => {'content' => '90', 'Units' => 'minutes'}, 'ProductGroup' => 'DVD' }; Therefore you can get the running time like this: $RunningTime = $item->{RunningTime}->{content}
Parsing XML Elements & Attributes with Perl So I wrote some perl that would parse results returned from the Amazon Web Services. I am using the XML::Simple package. For the most part, everything worked when I pulled out an element. However, the problem I ran into was when an element had an attribute as well. Then I get an error that the item is a Hash. Here's what I did if I wanted to get the Running Time for a DVD: I just created an item to hold the specific info for this one-off item. // XML DVD 90 // Perl to parse XML my $item = $xml->XMLin($content, KeyAttr => { Item => 'ASIN'}, ForceArray => ['ASIN']); $ProductGroup = $item->{Items}->{Item}->{ItemAttributes}->{ProductGroup}; if(ref($item->{Items}->{Item}->{ItemAttributes}->{RunningTime}) eq 'HASH'){ $RunningTimeXML = $xml->XMLin($content, KeyAttr => { Item => 'ASIN'}, NoAttr => 1); $RunningTime = $RunningTimeXML->{Items}->{Item}->{ItemAttributes}->{RunningTime}; } Is there a way I can access both elements and attributes from one item?
TITLE: Parsing XML Elements & Attributes with Perl QUESTION: So I wrote some perl that would parse results returned from the Amazon Web Services. I am using the XML::Simple package. For the most part, everything worked when I pulled out an element. However, the problem I ran into was when an element had an attribute as well. Then I get an error that the item is a Hash. Here's what I did if I wanted to get the Running Time for a DVD: I just created an item to hold the specific info for this one-off item. // XML DVD 90 // Perl to parse XML my $item = $xml->XMLin($content, KeyAttr => { Item => 'ASIN'}, ForceArray => ['ASIN']); $ProductGroup = $item->{Items}->{Item}->{ItemAttributes}->{ProductGroup}; if(ref($item->{Items}->{Item}->{ItemAttributes}->{RunningTime}) eq 'HASH'){ $RunningTimeXML = $xml->XMLin($content, KeyAttr => { Item => 'ASIN'}, NoAttr => 1); $RunningTime = $RunningTimeXML->{Items}->{Item}->{ItemAttributes}->{RunningTime}; } Is there a way I can access both elements and attributes from one item? ANSWER: $item is a hashref that looks like this: $item = { 'RunningTime' => {'content' => '90', 'Units' => 'minutes'}, 'ProductGroup' => 'DVD' }; Therefore you can get the running time like this: $RunningTime = $item->{RunningTime}->{content}
[ "xml", "perl", "amazon-web-services" ]
4
6
2,676
1
0
2008-08-27T15:31:27.517000
2008-08-27T16:26:57.617000
30,485
30,509
What is a reasonable length limit on person "Name" fields?
I have a simple webform that will allow unauthenticated users to input their information, including name. I gave the name field a limit of 50 characters to coincide with my database table where the field is varchar(50), but then I started to wonder. Is it more appropriate to use something like the Text column type or should I limit the length of the name to something reasonable? I'm using SQL Server 2005, in case that matters in your response. EDIT: I did not see this broader question regarding similar issues.
UK Government Data Standards Catalogue suggests 35 characters for each of Given Name and Family Name, or 70 characters for a single field to hold the Full Name.
What is a reasonable length limit on person "Name" fields? I have a simple webform that will allow unauthenticated users to input their information, including name. I gave the name field a limit of 50 characters to coincide with my database table where the field is varchar(50), but then I started to wonder. Is it more appropriate to use something like the Text column type or should I limit the length of the name to something reasonable? I'm using SQL Server 2005, in case that matters in your response. EDIT: I did not see this broader question regarding similar issues.
TITLE: What is a reasonable length limit on person "Name" fields? QUESTION: I have a simple webform that will allow unauthenticated users to input their information, including name. I gave the name field a limit of 50 characters to coincide with my database table where the field is varchar(50), but then I started to wonder. Is it more appropriate to use something like the Text column type or should I limit the length of the name to something reasonable? I'm using SQL Server 2005, in case that matters in your response. EDIT: I did not see this broader question regarding similar issues. ANSWER: UK Government Data Standards Catalogue suggests 35 characters for each of Given Name and Family Name, or 70 characters for a single field to hold the Full Name.
[ "html", "sql", "sql-server", "textbox", "limit" ]
171
169
169,471
12
0
2008-08-27T15:40:54.840000
2008-08-27T15:49:46.410000
30,494
30,629
Compare Version Identifiers
Here is my code, which takes two version identifiers in the form "1, 5, 0, 4" or "1.5.0.4" and determines which is the newer version. Suggestions or improvements, please! /// /// Compares two specified version strings and returns an integer that /// indicates their relationship to one another in the sort order. /// /// the first version /// the second version /// less than zero if strA is less than strB, equal to zero if /// strA equals strB, and greater than zero if strA is greater than strB public static int CompareVersions(string strA, string strB) { char[] splitTokens = new char[] {'.', ','}; string[] strAsplit = strA.Split(splitTokens, StringSplitOptions.RemoveEmptyEntries); string[] strBsplit = strB.Split(splitTokens, StringSplitOptions.RemoveEmptyEntries); int[] versionA = new int[4]; int[] versionB = new int[4]; for (int i = 0; i < 4; i++) { versionA[i] = Convert.ToInt32(strAsplit[i]); versionB[i] = Convert.ToInt32(strBsplit[i]); } // now that we have parsed the input strings, compare them return RecursiveCompareArrays(versionA, versionB, 0); } /// /// Recursive function for comparing arrays, 0-index is highest priority /// private static int RecursiveCompareArrays(int[] versionA, int[] versionB, int idx) { if (versionA[idx] < versionB[idx]) return -1; else if (versionA[idx] > versionB[idx]) return 1; else { Debug.Assert(versionA[idx] == versionB[idx]); if (idx == versionA.Length - 1) return 0; else return RecursiveCompareArrays(versionA, versionB, idx + 1); } } @ Darren Kopp: The version class does not handle versions of the format 1.0.0.5.
The System.Version class does not support versions with commas in it, so the solution presented by Darren Kopp is not sufficient. Here is a version that is as simple as possible (but no simpler). It uses System.Version but achieves compatibility with version numbers like "1, 2, 3, 4" by doing a search-replace before comparing. /// /// Compare versions of form "1,2,3,4" or "1.2.3.4". Throws FormatException /// in case of invalid version. /// /// the first version /// the second version /// less than zero if strA is less than strB, equal to zero if /// strA equals strB, and greater than zero if strA is greater than strB public static int CompareVersions(String strA, String strB) { Version vA = new Version(strA.Replace(",", ".")); Version vB = new Version(strB.Replace(",", ".")); return vA.CompareTo(vB); } The code has been tested with: static void Main(string[] args) { Test("1.0.0.0", "1.0.0.1", -1); Test("1.0.0.1", "1.0.0.0", 1); Test("1.0.0.0", "1.0.0.0", 0); Test("1, 0.0.0", "1.0.0.0", 0); Test("9, 5, 1, 44", "3.4.5.6", 1); Test("1, 5, 1, 44", "3.4.5.6", -1); Test("6,5,4,3", "6.5.4.3", 0); try { CompareVersions("2, 3, 4 - 4", "1,2,3,4"); Console.WriteLine("Exception should have been thrown"); } catch (FormatException e) { Console.WriteLine("Got exception as expected."); } Console.ReadLine(); } private static void Test(string lhs, string rhs, int expected) { int result = CompareVersions(lhs, rhs); Console.WriteLine("Test(\"" + lhs + "\", \"" + rhs + "\", " + expected + (result.Equals(expected)? " succeeded.": " failed.")); }
Compare Version Identifiers Here is my code, which takes two version identifiers in the form "1, 5, 0, 4" or "1.5.0.4" and determines which is the newer version. Suggestions or improvements, please! /// /// Compares two specified version strings and returns an integer that /// indicates their relationship to one another in the sort order. /// /// the first version /// the second version /// less than zero if strA is less than strB, equal to zero if /// strA equals strB, and greater than zero if strA is greater than strB public static int CompareVersions(string strA, string strB) { char[] splitTokens = new char[] {'.', ','}; string[] strAsplit = strA.Split(splitTokens, StringSplitOptions.RemoveEmptyEntries); string[] strBsplit = strB.Split(splitTokens, StringSplitOptions.RemoveEmptyEntries); int[] versionA = new int[4]; int[] versionB = new int[4]; for (int i = 0; i < 4; i++) { versionA[i] = Convert.ToInt32(strAsplit[i]); versionB[i] = Convert.ToInt32(strBsplit[i]); } // now that we have parsed the input strings, compare them return RecursiveCompareArrays(versionA, versionB, 0); } /// /// Recursive function for comparing arrays, 0-index is highest priority /// private static int RecursiveCompareArrays(int[] versionA, int[] versionB, int idx) { if (versionA[idx] < versionB[idx]) return -1; else if (versionA[idx] > versionB[idx]) return 1; else { Debug.Assert(versionA[idx] == versionB[idx]); if (idx == versionA.Length - 1) return 0; else return RecursiveCompareArrays(versionA, versionB, idx + 1); } } @ Darren Kopp: The version class does not handle versions of the format 1.0.0.5.
TITLE: Compare Version Identifiers QUESTION: Here is my code, which takes two version identifiers in the form "1, 5, 0, 4" or "1.5.0.4" and determines which is the newer version. Suggestions or improvements, please! /// /// Compares two specified version strings and returns an integer that /// indicates their relationship to one another in the sort order. /// /// the first version /// the second version /// less than zero if strA is less than strB, equal to zero if /// strA equals strB, and greater than zero if strA is greater than strB public static int CompareVersions(string strA, string strB) { char[] splitTokens = new char[] {'.', ','}; string[] strAsplit = strA.Split(splitTokens, StringSplitOptions.RemoveEmptyEntries); string[] strBsplit = strB.Split(splitTokens, StringSplitOptions.RemoveEmptyEntries); int[] versionA = new int[4]; int[] versionB = new int[4]; for (int i = 0; i < 4; i++) { versionA[i] = Convert.ToInt32(strAsplit[i]); versionB[i] = Convert.ToInt32(strBsplit[i]); } // now that we have parsed the input strings, compare them return RecursiveCompareArrays(versionA, versionB, 0); } /// /// Recursive function for comparing arrays, 0-index is highest priority /// private static int RecursiveCompareArrays(int[] versionA, int[] versionB, int idx) { if (versionA[idx] < versionB[idx]) return -1; else if (versionA[idx] > versionB[idx]) return 1; else { Debug.Assert(versionA[idx] == versionB[idx]); if (idx == versionA.Length - 1) return 0; else return RecursiveCompareArrays(versionA, versionB, idx + 1); } } @ Darren Kopp: The version class does not handle versions of the format 1.0.0.5. ANSWER: The System.Version class does not support versions with commas in it, so the solution presented by Darren Kopp is not sufficient. Here is a version that is as simple as possible (but no simpler). It uses System.Version but achieves compatibility with version numbers like "1, 2, 3, 4" by doing a search-replace before comparing. /// /// Compare versions of form "1,2,3,4" or "1.2.3.4". Throws FormatException /// in case of invalid version. /// /// the first version /// the second version /// less than zero if strA is less than strB, equal to zero if /// strA equals strB, and greater than zero if strA is greater than strB public static int CompareVersions(String strA, String strB) { Version vA = new Version(strA.Replace(",", ".")); Version vB = new Version(strB.Replace(",", ".")); return vA.CompareTo(vB); } The code has been tested with: static void Main(string[] args) { Test("1.0.0.0", "1.0.0.1", -1); Test("1.0.0.1", "1.0.0.0", 1); Test("1.0.0.0", "1.0.0.0", 0); Test("1, 0.0.0", "1.0.0.0", 0); Test("9, 5, 1, 44", "3.4.5.6", 1); Test("1, 5, 1, 44", "3.4.5.6", -1); Test("6,5,4,3", "6.5.4.3", 0); try { CompareVersions("2, 3, 4 - 4", "1,2,3,4"); Console.WriteLine("Exception should have been thrown"); } catch (FormatException e) { Console.WriteLine("Got exception as expected."); } Console.ReadLine(); } private static void Test(string lhs, string rhs, int expected) { int result = CompareVersions(lhs, rhs); Console.WriteLine("Test(\"" + lhs + "\", \"" + rhs + "\", " + expected + (result.Equals(expected)? " succeeded.": " failed.")); }
[ "c#", ".net", "compare", "versions" ]
27
32
20,682
4
0
2008-08-27T15:43:27.190000
2008-08-27T16:56:31.320000
30,504
30,512
Programmatically retrieve Visual Studio install directory
I know there is a registry key indicating the install directory, but I don't remember what it is off-hand. I am currently interested in Visual Studio 2008 install directory, though it wouldn't hurt to list others for future reference.
I'm sure there's a registry entry as well but I couldn't easily locate it. There is the VS90COMNTOOLS environment variable that you could use as well.
Programmatically retrieve Visual Studio install directory I know there is a registry key indicating the install directory, but I don't remember what it is off-hand. I am currently interested in Visual Studio 2008 install directory, though it wouldn't hurt to list others for future reference.
TITLE: Programmatically retrieve Visual Studio install directory QUESTION: I know there is a registry key indicating the install directory, but I don't remember what it is off-hand. I am currently interested in Visual Studio 2008 install directory, though it wouldn't hurt to list others for future reference. ANSWER: I'm sure there's a registry entry as well but I couldn't easily locate it. There is the VS90COMNTOOLS environment variable that you could use as well.
[ "visual-studio" ]
26
9
29,980
17
0
2008-08-27T15:47:17.027000
2008-08-27T15:51:08.450000
30,505
30,532
Display solution/file path in the Visual Studio IDE
I frequently work with multiple instances of Visual Studio, often working on different branches of the same solution. Visual C++ 6.0 used to display the full path of the current source file in its title bar, but Visual Studio 2005 doesn't appear to do this. This makes it slightly more awkward than it should be to work out which branch of the solution I'm currently looking at (the quickest way I know of is to hover over a tab so you get the source file's path as a tooltip). Is there a way to get the full solution or file path into the title bar, or at least somewhere that's always visible, so I can quickly tell which branch is loaded into each instance?
There is not a native way to do it, but you can achieve it with a macro. The details are described here in full: How To Show Full File Path (or Anything Else) in VS 2005 Title Bar You just have to add a little Visual Basic macro to the EvironmentEvents macro section and restart Visual Studio. Note: The path will not show up when you first load Visual Studio, but it will whenever you change which file you are viewing. There is probably a way to fix this, but it doesn't seem like a big deal.
Display solution/file path in the Visual Studio IDE I frequently work with multiple instances of Visual Studio, often working on different branches of the same solution. Visual C++ 6.0 used to display the full path of the current source file in its title bar, but Visual Studio 2005 doesn't appear to do this. This makes it slightly more awkward than it should be to work out which branch of the solution I'm currently looking at (the quickest way I know of is to hover over a tab so you get the source file's path as a tooltip). Is there a way to get the full solution or file path into the title bar, or at least somewhere that's always visible, so I can quickly tell which branch is loaded into each instance?
TITLE: Display solution/file path in the Visual Studio IDE QUESTION: I frequently work with multiple instances of Visual Studio, often working on different branches of the same solution. Visual C++ 6.0 used to display the full path of the current source file in its title bar, but Visual Studio 2005 doesn't appear to do this. This makes it slightly more awkward than it should be to work out which branch of the solution I'm currently looking at (the quickest way I know of is to hover over a tab so you get the source file's path as a tooltip). Is there a way to get the full solution or file path into the title bar, or at least somewhere that's always visible, so I can quickly tell which branch is loaded into each instance? ANSWER: There is not a native way to do it, but you can achieve it with a macro. The details are described here in full: How To Show Full File Path (or Anything Else) in VS 2005 Title Bar You just have to add a little Visual Basic macro to the EvironmentEvents macro section and restart Visual Studio. Note: The path will not show up when you first load Visual Studio, but it will whenever you change which file you are viewing. There is probably a way to fix this, but it doesn't seem like a big deal.
[ "visual-studio", "projects-and-solutions" ]
86
25
51,067
14
0
2008-08-27T15:47:35.840000
2008-08-27T15:58:47.090000
30,521
30,597
Qt Child Window Placement
Is there a way to specify a child's initial window position in Qt? I have an application that runs on Linux and Windows and it looks like the default behavior of Qt lets the Window Manager determine the placement of the child windows. On Windows, this is in the center of the screen the parent is on which seems reasonable. On Linux, in GNOME (metacity) it is always in the upper left-hand corner which is annoying. I can't find any window manager preferences for metacity that allow me to control window placement so I would like to override that behavior.
Qt Widget Geometry Call the move(x, y) method on the child window before show(). The default values for x and y are 0 so that's why it appears in the upper left-hand corner. You can also use the position of the parent window to compute a relative position for the child.
Qt Child Window Placement Is there a way to specify a child's initial window position in Qt? I have an application that runs on Linux and Windows and it looks like the default behavior of Qt lets the Window Manager determine the placement of the child windows. On Windows, this is in the center of the screen the parent is on which seems reasonable. On Linux, in GNOME (metacity) it is always in the upper left-hand corner which is annoying. I can't find any window manager preferences for metacity that allow me to control window placement so I would like to override that behavior.
TITLE: Qt Child Window Placement QUESTION: Is there a way to specify a child's initial window position in Qt? I have an application that runs on Linux and Windows and it looks like the default behavior of Qt lets the Window Manager determine the placement of the child windows. On Windows, this is in the center of the screen the parent is on which seems reasonable. On Linux, in GNOME (metacity) it is always in the upper left-hand corner which is annoying. I can't find any window manager preferences for metacity that allow me to control window placement so I would like to override that behavior. ANSWER: Qt Widget Geometry Call the move(x, y) method on the child window before show(). The default values for x and y are 0 so that's why it appears in the upper left-hand corner. You can also use the position of the parent window to compute a relative position for the child.
[ "c++", "qt", "user-interface", "qtgui" ]
2
3
4,677
2
0
2008-08-27T15:54:07.943000
2008-08-27T16:34:56.693000
30,529
40,650
How to implement Type-safe COM enumerations?
How could i implement Type-Safe Enumerations in Delphi in a COM scenario? Basically, i'd like to replace a set of primitive constants of a enumeration with a set of static final object references encapsulated in a class?. In Java, we can do something like: public final class Enum { public static final Enum ENUMITEM1 = new Enum (); public static final Enum ENUMITEM2 = new Enum (); //... private Enum () {} } and make comparisons using the customized enumeration type: if (anObject!= Enum.ENUMITEM1)... I am currently using the old Delphi 5 and i would like to declare some enums parameters on the interfaces, not allowing that client objects to pass integers (or long) types in the place of the required enumeration type. Do you have a better way of implementing enums other than using the native delphi enums?
Now you have provided us with some more clues about the nature of your question, namely mentioning COM, I think I understand what you mean. COM can marshal only a subset of the types Delphi knows between a COM server and client. You can define enums in the TLB editor, but these are all of the type TOleEnum which basically is an integer type (LongWord). You can have a variable of the type TOleEnum any integer value you want and assign values of different enum types to each other. Not really type safe. I can not think of a reason why Delphi's COM can't use the type safe enums instead, but it doesn't. I am afraid nothing much can be done about that. Maybe the changes in the TLB editor in the upcoming Delphi 2009 version might change that. For the record: When the TLB editor is not used, Delphi is perfectly able to have interface with methods who have type safe enums as parameters.
How to implement Type-safe COM enumerations? How could i implement Type-Safe Enumerations in Delphi in a COM scenario? Basically, i'd like to replace a set of primitive constants of a enumeration with a set of static final object references encapsulated in a class?. In Java, we can do something like: public final class Enum { public static final Enum ENUMITEM1 = new Enum (); public static final Enum ENUMITEM2 = new Enum (); //... private Enum () {} } and make comparisons using the customized enumeration type: if (anObject!= Enum.ENUMITEM1)... I am currently using the old Delphi 5 and i would like to declare some enums parameters on the interfaces, not allowing that client objects to pass integers (or long) types in the place of the required enumeration type. Do you have a better way of implementing enums other than using the native delphi enums?
TITLE: How to implement Type-safe COM enumerations? QUESTION: How could i implement Type-Safe Enumerations in Delphi in a COM scenario? Basically, i'd like to replace a set of primitive constants of a enumeration with a set of static final object references encapsulated in a class?. In Java, we can do something like: public final class Enum { public static final Enum ENUMITEM1 = new Enum (); public static final Enum ENUMITEM2 = new Enum (); //... private Enum () {} } and make comparisons using the customized enumeration type: if (anObject!= Enum.ENUMITEM1)... I am currently using the old Delphi 5 and i would like to declare some enums parameters on the interfaces, not allowing that client objects to pass integers (or long) types in the place of the required enumeration type. Do you have a better way of implementing enums other than using the native delphi enums? ANSWER: Now you have provided us with some more clues about the nature of your question, namely mentioning COM, I think I understand what you mean. COM can marshal only a subset of the types Delphi knows between a COM server and client. You can define enums in the TLB editor, but these are all of the type TOleEnum which basically is an integer type (LongWord). You can have a variable of the type TOleEnum any integer value you want and assign values of different enum types to each other. Not really type safe. I can not think of a reason why Delphi's COM can't use the type safe enums instead, but it doesn't. I am afraid nothing much can be done about that. Maybe the changes in the TLB editor in the upcoming Delphi 2009 version might change that. For the record: When the TLB editor is not used, Delphi is perfectly able to have interface with methods who have type safe enums as parameters.
[ "delphi", "com", "delphi-5" ]
2
1
2,117
4
0
2008-08-27T15:57:50.090000
2008-09-02T20:59:59.410000
30,539
30,596
Best way to enumerate all available video codecs on Windows?
I'm looking for a good way to enumerate all the Video codecs on a Windows XP/Vista machine. I need present the user with a set of video codecs, including the compressors and decompressors. The output would look something like Available Decoders DiVX Version 6.0 XVID Motion JPEG CompanyX's MPEG-2 Decoder Windows Media Video **Available Encoders** DiVX Version 6.0 Windows Media Video The problem that I am running into is that there is no reliable way to to capture all of the decoders available to the system. For instance: You can enumerate all the decompressors using DirectShow, but this tells you nothing about the compressors (encoders). You can enumerate all the Video For Windows components, but you get no indication if these are encoders or decoders. There are DirectShow filters that may do the job for you perfectly well (Motion JPEG filter for example), but there is no indication that a particular DirectShow filter is a "video decoder". Has anyone found a generalizes solution for this problem using any of the Windows APIs? Does the Windows Vista Media Foundation API solve any of these issues?
This is best handled by DirectShow. DirectShow is currently a part of the platform SDK. HRESULT extractFriendlyName( IMoniker* pMk, std::wstring& str ) { assert( pMk!= 0 ); IPropertyBag* pBag = 0; HRESULT hr = pMk->BindToStorage(0, 0, IID_IPropertyBag, (void **)&pBag ); if( FAILED( hr ) || pBag == 0 ) { return hr; } VARIANT var; var.vt = VT_BSTR; hr = pBag->Read(L"FriendlyName", &var, NULL); if( SUCCEEDED( hr ) && var.bstrVal!= 0 ) { str = reinterpret_cast ( var.bstrVal ); SysFreeString(var.bstrVal); } pBag->Release(); return hr; } HRESULT enumerateDShowFilterList( const CLSID& category ) { HRESULT rval = S_OK; HRESULT hr; ICreateDevEnum* pCreateDevEnum = 0; // volatile, will be destroyed at the end hr =::CoCreateInstance( CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER, IID_ICreateDevEnum, reinterpret_cast ( &pCreateDevEnum ) ); assert( SUCCEEDED( hr ) && pCreateDevEnum!= 0 ); if( FAILED( hr ) || pCreateDevEnum == 0 ) { return hr; } IEnumMoniker* pEm = 0; hr = pCreateDevEnum->CreateClassEnumerator( category, &pEm, 0 ); // If hr == S_FALSE, no error is occured. In this case pEm is NULL, because // a filter does not exist e.g no video capture devives are connected to // the computer or no codecs are installed. assert( SUCCEEDED( hr ) && ((hr == S_OK && pEm!= 0 ) || hr == S_FALSE) ); if( FAILED( hr ) ) { pCreateDevEnum->Release(); return hr; } if( hr == S_OK && pEm!= 0 ) // In this case pEm is!= NULL { pEm->Reset(); ULONG cFetched; IMoniker* pM = 0; while( pEm->Next(1, &pM, &cFetched) == S_OK && pM!= 0 ) { std::wstring str; if( SUCCEEDED( extractFriendlyName( pM, str ) ) { // str contains the friendly name of the filter // pM->BindToObject creates the filter std::wcout << str << std::endl; } pM->Release(); } pEm->Release(); } pCreateDevEnum->Release(); return rval; } The following call enumerates all video compressors to the console: enumerateDShowFilterList( CLSID_VideoCompressorCategory ); The MSDN page Filter Categories lists all other 'official' categories. I hope that is a good starting point for you.
Best way to enumerate all available video codecs on Windows? I'm looking for a good way to enumerate all the Video codecs on a Windows XP/Vista machine. I need present the user with a set of video codecs, including the compressors and decompressors. The output would look something like Available Decoders DiVX Version 6.0 XVID Motion JPEG CompanyX's MPEG-2 Decoder Windows Media Video **Available Encoders** DiVX Version 6.0 Windows Media Video The problem that I am running into is that there is no reliable way to to capture all of the decoders available to the system. For instance: You can enumerate all the decompressors using DirectShow, but this tells you nothing about the compressors (encoders). You can enumerate all the Video For Windows components, but you get no indication if these are encoders or decoders. There are DirectShow filters that may do the job for you perfectly well (Motion JPEG filter for example), but there is no indication that a particular DirectShow filter is a "video decoder". Has anyone found a generalizes solution for this problem using any of the Windows APIs? Does the Windows Vista Media Foundation API solve any of these issues?
TITLE: Best way to enumerate all available video codecs on Windows? QUESTION: I'm looking for a good way to enumerate all the Video codecs on a Windows XP/Vista machine. I need present the user with a set of video codecs, including the compressors and decompressors. The output would look something like Available Decoders DiVX Version 6.0 XVID Motion JPEG CompanyX's MPEG-2 Decoder Windows Media Video **Available Encoders** DiVX Version 6.0 Windows Media Video The problem that I am running into is that there is no reliable way to to capture all of the decoders available to the system. For instance: You can enumerate all the decompressors using DirectShow, but this tells you nothing about the compressors (encoders). You can enumerate all the Video For Windows components, but you get no indication if these are encoders or decoders. There are DirectShow filters that may do the job for you perfectly well (Motion JPEG filter for example), but there is no indication that a particular DirectShow filter is a "video decoder". Has anyone found a generalizes solution for this problem using any of the Windows APIs? Does the Windows Vista Media Foundation API solve any of these issues? ANSWER: This is best handled by DirectShow. DirectShow is currently a part of the platform SDK. HRESULT extractFriendlyName( IMoniker* pMk, std::wstring& str ) { assert( pMk!= 0 ); IPropertyBag* pBag = 0; HRESULT hr = pMk->BindToStorage(0, 0, IID_IPropertyBag, (void **)&pBag ); if( FAILED( hr ) || pBag == 0 ) { return hr; } VARIANT var; var.vt = VT_BSTR; hr = pBag->Read(L"FriendlyName", &var, NULL); if( SUCCEEDED( hr ) && var.bstrVal!= 0 ) { str = reinterpret_cast ( var.bstrVal ); SysFreeString(var.bstrVal); } pBag->Release(); return hr; } HRESULT enumerateDShowFilterList( const CLSID& category ) { HRESULT rval = S_OK; HRESULT hr; ICreateDevEnum* pCreateDevEnum = 0; // volatile, will be destroyed at the end hr =::CoCreateInstance( CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER, IID_ICreateDevEnum, reinterpret_cast ( &pCreateDevEnum ) ); assert( SUCCEEDED( hr ) && pCreateDevEnum!= 0 ); if( FAILED( hr ) || pCreateDevEnum == 0 ) { return hr; } IEnumMoniker* pEm = 0; hr = pCreateDevEnum->CreateClassEnumerator( category, &pEm, 0 ); // If hr == S_FALSE, no error is occured. In this case pEm is NULL, because // a filter does not exist e.g no video capture devives are connected to // the computer or no codecs are installed. assert( SUCCEEDED( hr ) && ((hr == S_OK && pEm!= 0 ) || hr == S_FALSE) ); if( FAILED( hr ) ) { pCreateDevEnum->Release(); return hr; } if( hr == S_OK && pEm!= 0 ) // In this case pEm is!= NULL { pEm->Reset(); ULONG cFetched; IMoniker* pM = 0; while( pEm->Next(1, &pM, &cFetched) == S_OK && pM!= 0 ) { std::wstring str; if( SUCCEEDED( extractFriendlyName( pM, str ) ) { // str contains the friendly name of the filter // pM->BindToObject creates the filter std::wcout << str << std::endl; } pM->Release(); } pEm->Release(); } pCreateDevEnum->Release(); return rval; } The following call enumerates all video compressors to the console: enumerateDShowFilterList( CLSID_VideoCompressorCategory ); The MSDN page Filter Categories lists all other 'official' categories. I hope that is a good starting point for you.
[ "video", "directshow", "media", "codec" ]
5
7
6,604
3
0
2008-08-27T16:01:57.613000
2008-08-27T16:34:45.290000
30,540
30,561
What does this javascript error mean? Permission denied to call method to Location.toString
This error just started popping up all over our site. Permission denied to call method to Location.toString I'm seeing google posts that suggest that this is related to flash and our crossdomain.xml. What caused this to occur and how do you fix?
Are you using javascript to communicate between frames/iframes which point to different domains? This is not permitted by the JS "same origin/domain" security policy. Ie, if you have And the script on bar.com tries to access window["foo"].Location.toString, you will get this (or similar) exceptions. Please also note that the same origin policy can also kick in if you have content from different subdomains. Here you can find a short and to the point explanation of it with examples.
What does this javascript error mean? Permission denied to call method to Location.toString This error just started popping up all over our site. Permission denied to call method to Location.toString I'm seeing google posts that suggest that this is related to flash and our crossdomain.xml. What caused this to occur and how do you fix?
TITLE: What does this javascript error mean? Permission denied to call method to Location.toString QUESTION: This error just started popping up all over our site. Permission denied to call method to Location.toString I'm seeing google posts that suggest that this is related to flash and our crossdomain.xml. What caused this to occur and how do you fix? ANSWER: Are you using javascript to communicate between frames/iframes which point to different domains? This is not permitted by the JS "same origin/domain" security policy. Ie, if you have And the script on bar.com tries to access window["foo"].Location.toString, you will get this (or similar) exceptions. Please also note that the same origin policy can also kick in if you have content from different subdomains. Here you can find a short and to the point explanation of it with examples.
[ "javascript", "flash" ]
9
9
6,720
4
0
2008-08-27T16:02:00.873000
2008-08-27T16:14:34.293000
30,541
30,556
Using MVP - How to use Events Properly for Testing
I've just started using the MVP pattern in the large ASP.NET application that I'm building (re-building actually) and I am having a hard time figuring out how I should be using Events applied to the view. Say I have 2 drop down lists in a User Control, where one is dependent on the other's value: <%@ Control Language="vb" AutoEventWireup="false" CodeBehind="ucTestMVP.ascx.vb" Inherits=".ucTestMVP" %> How should the AutoPostBack Event be defined in the interface? Should it be an event that is handled by the User Control like this: Public Partial Class ucTestMVP Inherits System.Web.UI.UserControl Implements ITestMVPView Protected Sub PageLoad(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then Dim presenter As New TestMVPPresenter(Me) presenter.InitView() End If End Sub Private Sub ddlCountrySelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlCountry.SelectedIndexChanged Dim presenter as New TestMVPPresenter(Me) presenter.CountryDDLIndexChanged() End Sub End Class Or should there be an event defined at the Interface? If this is the preferred pattern, how do I add events to be handled and used?
I don't know if there's a universally preferred pattern. I tend to prefer adding the event to the view interface and having the presenter respond to the view. I described this pattern in more detail here.
Using MVP - How to use Events Properly for Testing I've just started using the MVP pattern in the large ASP.NET application that I'm building (re-building actually) and I am having a hard time figuring out how I should be using Events applied to the view. Say I have 2 drop down lists in a User Control, where one is dependent on the other's value: <%@ Control Language="vb" AutoEventWireup="false" CodeBehind="ucTestMVP.ascx.vb" Inherits=".ucTestMVP" %> How should the AutoPostBack Event be defined in the interface? Should it be an event that is handled by the User Control like this: Public Partial Class ucTestMVP Inherits System.Web.UI.UserControl Implements ITestMVPView Protected Sub PageLoad(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then Dim presenter As New TestMVPPresenter(Me) presenter.InitView() End If End Sub Private Sub ddlCountrySelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlCountry.SelectedIndexChanged Dim presenter as New TestMVPPresenter(Me) presenter.CountryDDLIndexChanged() End Sub End Class Or should there be an event defined at the Interface? If this is the preferred pattern, how do I add events to be handled and used?
TITLE: Using MVP - How to use Events Properly for Testing QUESTION: I've just started using the MVP pattern in the large ASP.NET application that I'm building (re-building actually) and I am having a hard time figuring out how I should be using Events applied to the view. Say I have 2 drop down lists in a User Control, where one is dependent on the other's value: <%@ Control Language="vb" AutoEventWireup="false" CodeBehind="ucTestMVP.ascx.vb" Inherits=".ucTestMVP" %> How should the AutoPostBack Event be defined in the interface? Should it be an event that is handled by the User Control like this: Public Partial Class ucTestMVP Inherits System.Web.UI.UserControl Implements ITestMVPView Protected Sub PageLoad(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then Dim presenter As New TestMVPPresenter(Me) presenter.InitView() End If End Sub Private Sub ddlCountrySelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlCountry.SelectedIndexChanged Dim presenter as New TestMVPPresenter(Me) presenter.CountryDDLIndexChanged() End Sub End Class Or should there be an event defined at the Interface? If this is the preferred pattern, how do I add events to be handled and used? ANSWER: I don't know if there's a universally preferred pattern. I tend to prefer adding the event to the view interface and having the presenter respond to the view. I described this pattern in more detail here.
[ "asp.net", "design-patterns", "mvp" ]
0
2
506
1
0
2008-08-27T16:02:23.260000
2008-08-27T16:10:37.127000
30,543
30,643
Is code written in Vista 64 compatible on 32 bit os?
We are getting new dev machines and moving up to Vista 64 Ultimate to take advantage of our 8gb ram. Our manager wants us to do all dev in 32bit virtual machines to make sure there will be no problems with our code moving into production. Is there any way to guarantee the resultant programs will work on 32bit os's? I don't mind using virtual machines, but I don't like how they force you back into a "Single" monitor type view. I like moving my VS toolbars off to my other monitor. EDIT: We are using Visual Studio 2005 and 2008, VB.NET and/or C# EDIT: Using Harpreet's answer, these are the steps I used to set my Visual Studio IDE to compile x86 / 32bit: Click Build and open Configuration Manager Select Active Solution Platform drop down list Select x86 if it is in the list and skip to step 5, if not Select > In the New Solution Platform dialog, select x86 and press OK Verify the selected platform for all of your projects is x86 Click Close. Enjoy. Thank you, Keith
I do development on 64 bit machines for 32 bit Windows. It's not a problem. You should make sure that your projects are set to compile in x86 mode in order to be conservative. You'll want to go through each project in the solution and double check this. You could also use the AnyCPU setting but that's a little riskier since it will run differently on your dev machine than a 32 bit machine. You want to avoid the 64bit mode, of course. The problems I've run into are drivers that don't work when the app is compiled for 64 bit (explicitly 64 bit or AnyCPU compiled and running on 64 bit Windows). Those problems are completely avoidable by sticking with x86 compilation. That should reveal all flaws on your dev machines. Ideally, you could set up a build and test environment that could be executed against frequently on a 32 bit machine. That should reassure your management and let you avoid the VM as your desktop.
Is code written in Vista 64 compatible on 32 bit os? We are getting new dev machines and moving up to Vista 64 Ultimate to take advantage of our 8gb ram. Our manager wants us to do all dev in 32bit virtual machines to make sure there will be no problems with our code moving into production. Is there any way to guarantee the resultant programs will work on 32bit os's? I don't mind using virtual machines, but I don't like how they force you back into a "Single" monitor type view. I like moving my VS toolbars off to my other monitor. EDIT: We are using Visual Studio 2005 and 2008, VB.NET and/or C# EDIT: Using Harpreet's answer, these are the steps I used to set my Visual Studio IDE to compile x86 / 32bit: Click Build and open Configuration Manager Select Active Solution Platform drop down list Select x86 if it is in the list and skip to step 5, if not Select > In the New Solution Platform dialog, select x86 and press OK Verify the selected platform for all of your projects is x86 Click Close. Enjoy. Thank you, Keith
TITLE: Is code written in Vista 64 compatible on 32 bit os? QUESTION: We are getting new dev machines and moving up to Vista 64 Ultimate to take advantage of our 8gb ram. Our manager wants us to do all dev in 32bit virtual machines to make sure there will be no problems with our code moving into production. Is there any way to guarantee the resultant programs will work on 32bit os's? I don't mind using virtual machines, but I don't like how they force you back into a "Single" monitor type view. I like moving my VS toolbars off to my other monitor. EDIT: We are using Visual Studio 2005 and 2008, VB.NET and/or C# EDIT: Using Harpreet's answer, these are the steps I used to set my Visual Studio IDE to compile x86 / 32bit: Click Build and open Configuration Manager Select Active Solution Platform drop down list Select x86 if it is in the list and skip to step 5, if not Select > In the New Solution Platform dialog, select x86 and press OK Verify the selected platform for all of your projects is x86 Click Close. Enjoy. Thank you, Keith ANSWER: I do development on 64 bit machines for 32 bit Windows. It's not a problem. You should make sure that your projects are set to compile in x86 mode in order to be conservative. You'll want to go through each project in the solution and double check this. You could also use the AnyCPU setting but that's a little riskier since it will run differently on your dev machine than a 32 bit machine. You want to avoid the 64bit mode, of course. The problems I've run into are drivers that don't work when the app is compiled for 64 bit (explicitly 64 bit or AnyCPU compiled and running on 64 bit Windows). Those problems are completely avoidable by sticking with x86 compilation. That should reveal all flaws on your dev machines. Ideally, you could set up a build and test environment that could be executed against frequently on a 32 bit machine. That should reassure your management and let you avoid the VM as your desktop.
[ "64-bit", "development-environment", "compatibility" ]
6
9
3,345
7
0
2008-08-27T16:04:29.637000
2008-08-27T17:02:45.580000
30,563
30,578
Returning the sum of items depending on which type it is
I have one field that I need to sum lets say named items However that field can be part of group a or b In the end I need to have all of the items summed for group a and group b when I say grouped I mean there is a LEFT OUTER JOIN to another table the previous table has a type for the items and the one being joined has a group assigned for this item type Sorry guys Im a little new to sql I am going to try out what you have given me an get back to you Ok I feel like we are getting close just not yet allain's I can get them to separate but the issue I need to have both groups to sum on the same row which is difficult because I also have several LEFT OUTER JOIN's involved Tyler's looks like it might work too so I am trying to hash that out real fast Alain's seems to be the way to go but I have to tweek it a little more
Maybe I'm not understanding the complexity of what you're asking but... shouldn't this do? SELECT groupname, SUM(value) FROM items WHERE groupname IN ('a', 'b') GROUP BY groupname And if you don't care which of a or b the item belongs to then this will do: SELECT SUM(value) FROM items WHERE groupname IN ('a', 'b')
Returning the sum of items depending on which type it is I have one field that I need to sum lets say named items However that field can be part of group a or b In the end I need to have all of the items summed for group a and group b when I say grouped I mean there is a LEFT OUTER JOIN to another table the previous table has a type for the items and the one being joined has a group assigned for this item type Sorry guys Im a little new to sql I am going to try out what you have given me an get back to you Ok I feel like we are getting close just not yet allain's I can get them to separate but the issue I need to have both groups to sum on the same row which is difficult because I also have several LEFT OUTER JOIN's involved Tyler's looks like it might work too so I am trying to hash that out real fast Alain's seems to be the way to go but I have to tweek it a little more
TITLE: Returning the sum of items depending on which type it is QUESTION: I have one field that I need to sum lets say named items However that field can be part of group a or b In the end I need to have all of the items summed for group a and group b when I say grouped I mean there is a LEFT OUTER JOIN to another table the previous table has a type for the items and the one being joined has a group assigned for this item type Sorry guys Im a little new to sql I am going to try out what you have given me an get back to you Ok I feel like we are getting close just not yet allain's I can get them to separate but the issue I need to have both groups to sum on the same row which is difficult because I also have several LEFT OUTER JOIN's involved Tyler's looks like it might work too so I am trying to hash that out real fast Alain's seems to be the way to go but I have to tweek it a little more ANSWER: Maybe I'm not understanding the complexity of what you're asking but... shouldn't this do? SELECT groupname, SUM(value) FROM items WHERE groupname IN ('a', 'b') GROUP BY groupname And if you don't care which of a or b the item belongs to then this will do: SELECT SUM(value) FROM items WHERE groupname IN ('a', 'b')
[ "sql", "sql-server" ]
3
4
7,170
5
0
2008-08-27T16:14:42.997000
2008-08-27T16:21:25.587000
30,569
30,593
Resize transparent images using C#
Does anyone have the secret formula to resizing transparent images (mainly GIFs) without ANY quality loss - what so ever? I've tried a bunch of stuff, the closest I get is not good enough. Take a look at my main image: http://www.thewallcompany.dk/test/main.gif And then the scaled image: http://www.thewallcompany.dk/test/ScaledImage.gif //Internal resize for indexed colored images void IndexedRezise(int xSize, int ySize) { BitmapData sourceData; BitmapData targetData; AdjustSizes(ref xSize, ref ySize); scaledBitmap = new Bitmap(xSize, ySize, bitmap.PixelFormat); scaledBitmap.Palette = bitmap.Palette; sourceData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat); try { targetData = scaledBitmap.LockBits(new Rectangle(0, 0, xSize, ySize), ImageLockMode.WriteOnly, scaledBitmap.PixelFormat); try { xFactor = (Double)bitmap.Width / (Double)scaledBitmap.Width; yFactor = (Double)bitmap.Height / (Double)scaledBitmap.Height; sourceStride = sourceData.Stride; sourceScan0 = sourceData.Scan0; int targetStride = targetData.Stride; System.IntPtr targetScan0 = targetData.Scan0; unsafe { byte* p = (byte*)(void*)targetScan0; int nOffset = targetStride - scaledBitmap.Width; int nWidth = scaledBitmap.Width; for (int y = 0; y < scaledBitmap.Height; ++y) { for (int x = 0; x < nWidth; ++x) { p[0] = GetSourceByteAt(x, y); ++p; } p += nOffset; } } } finally { scaledBitmap.UnlockBits(targetData); } } finally { bitmap.UnlockBits(sourceData); } } I'm using the above code, to do the indexed resizing. Does anyone have improvement ideas?
If there's no requirement on preserving file type after scaling I'd recommend the following approach. using (Image src = Image.FromFile("main.gif")) using (Bitmap dst = new Bitmap(100, 129)) using (Graphics g = Graphics.FromImage(dst)) { g.SmoothingMode = SmoothingMode.AntiAlias; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(src, 0, 0, dst.Width, dst.Height); dst.Save("scale.png", ImageFormat.Png); } The result will have really nice anti aliased edges removed image shack image that had been replaced by an advert If you must export the image in gif you're in for a ride; GDI+ doesn't play well with gif. See this blog post about it for more information Edit: I forgot to dispose of the bitmaps in the example; it's been corrected
Resize transparent images using C# Does anyone have the secret formula to resizing transparent images (mainly GIFs) without ANY quality loss - what so ever? I've tried a bunch of stuff, the closest I get is not good enough. Take a look at my main image: http://www.thewallcompany.dk/test/main.gif And then the scaled image: http://www.thewallcompany.dk/test/ScaledImage.gif //Internal resize for indexed colored images void IndexedRezise(int xSize, int ySize) { BitmapData sourceData; BitmapData targetData; AdjustSizes(ref xSize, ref ySize); scaledBitmap = new Bitmap(xSize, ySize, bitmap.PixelFormat); scaledBitmap.Palette = bitmap.Palette; sourceData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat); try { targetData = scaledBitmap.LockBits(new Rectangle(0, 0, xSize, ySize), ImageLockMode.WriteOnly, scaledBitmap.PixelFormat); try { xFactor = (Double)bitmap.Width / (Double)scaledBitmap.Width; yFactor = (Double)bitmap.Height / (Double)scaledBitmap.Height; sourceStride = sourceData.Stride; sourceScan0 = sourceData.Scan0; int targetStride = targetData.Stride; System.IntPtr targetScan0 = targetData.Scan0; unsafe { byte* p = (byte*)(void*)targetScan0; int nOffset = targetStride - scaledBitmap.Width; int nWidth = scaledBitmap.Width; for (int y = 0; y < scaledBitmap.Height; ++y) { for (int x = 0; x < nWidth; ++x) { p[0] = GetSourceByteAt(x, y); ++p; } p += nOffset; } } } finally { scaledBitmap.UnlockBits(targetData); } } finally { bitmap.UnlockBits(sourceData); } } I'm using the above code, to do the indexed resizing. Does anyone have improvement ideas?
TITLE: Resize transparent images using C# QUESTION: Does anyone have the secret formula to resizing transparent images (mainly GIFs) without ANY quality loss - what so ever? I've tried a bunch of stuff, the closest I get is not good enough. Take a look at my main image: http://www.thewallcompany.dk/test/main.gif And then the scaled image: http://www.thewallcompany.dk/test/ScaledImage.gif //Internal resize for indexed colored images void IndexedRezise(int xSize, int ySize) { BitmapData sourceData; BitmapData targetData; AdjustSizes(ref xSize, ref ySize); scaledBitmap = new Bitmap(xSize, ySize, bitmap.PixelFormat); scaledBitmap.Palette = bitmap.Palette; sourceData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat); try { targetData = scaledBitmap.LockBits(new Rectangle(0, 0, xSize, ySize), ImageLockMode.WriteOnly, scaledBitmap.PixelFormat); try { xFactor = (Double)bitmap.Width / (Double)scaledBitmap.Width; yFactor = (Double)bitmap.Height / (Double)scaledBitmap.Height; sourceStride = sourceData.Stride; sourceScan0 = sourceData.Scan0; int targetStride = targetData.Stride; System.IntPtr targetScan0 = targetData.Scan0; unsafe { byte* p = (byte*)(void*)targetScan0; int nOffset = targetStride - scaledBitmap.Width; int nWidth = scaledBitmap.Width; for (int y = 0; y < scaledBitmap.Height; ++y) { for (int x = 0; x < nWidth; ++x) { p[0] = GetSourceByteAt(x, y); ++p; } p += nOffset; } } } finally { scaledBitmap.UnlockBits(targetData); } } finally { bitmap.UnlockBits(sourceData); } } I'm using the above code, to do the indexed resizing. Does anyone have improvement ideas? ANSWER: If there's no requirement on preserving file type after scaling I'd recommend the following approach. using (Image src = Image.FromFile("main.gif")) using (Bitmap dst = new Bitmap(100, 129)) using (Graphics g = Graphics.FromImage(dst)) { g.SmoothingMode = SmoothingMode.AntiAlias; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(src, 0, 0, dst.Width, dst.Height); dst.Save("scale.png", ImageFormat.Png); } The result will have really nice anti aliased edges removed image shack image that had been replaced by an advert If you must export the image in gif you're in for a ride; GDI+ doesn't play well with gif. See this blog post about it for more information Edit: I forgot to dispose of the bitmaps in the example; it's been corrected
[ "c#", ".net", "image", "resize", "image-scaling" ]
26
51
26,405
5
0
2008-08-27T16:16:47.267000
2008-08-27T16:33:43.293000
30,571
1,172,371
How do I tell Maven to use the latest version of a dependency?
In Maven, dependencies are usually set up like this: wonderful-inc dream-library 1.2.3 Now, if you are working with libraries that have frequent releases, constantly updating the tag can be somewhat annoying. Is there any way to tell Maven to always use the latest available version (from the repository)?
NOTE: The mentioned LATEST and RELEASE metaversions have been dropped for plugin dependencies in Maven 3 "for the sake of reproducible builds", over 6 years ago. (They still work perfectly fine for regular dependencies.) For plugin dependencies please refer to this Maven 3 compliant solution. If you always want to use the newest version, Maven has two keywords you can use as an alternative to version ranges. You should use these options with care as you are no longer in control of the plugins/dependencies you are using. When you depend on a plugin or a dependency, you can use the a version value of LATEST or RELEASE. LATEST refers to the latest released or snapshot version of a particular artifact, the most recently deployed artifact in a particular repository. RELEASE refers to the last non-snapshot release in the repository. In general, it is not a best practice to design software which depends on a non-specific version of an artifact. If you are developing software, you might want to use RELEASE or LATEST as a convenience so that you don't have to update version numbers when a new release of a third-party library is released. When you release software, you should always make sure that your project depends on specific versions to reduce the chances of your build or your project being affected by a software release not under your control. Use LATEST and RELEASE with caution, if at all. See the POM Syntax section of the Maven book for more details. Or see this doc on Dependency Version Ranges, where: A square bracket ( [ & ] ) means "closed" (inclusive). A parenthesis ( ( & ) ) means "open" (exclusive). Here's an example illustrating the various options. In the Maven repository, com.foo:my-foo has the following metadata: com.foo my-foo 2.0.0 1.1.1 1.0 1.0.1 1.1 1.1.1 2.0.0 20090722140000 If a dependency on that artifact is required, you have the following options (other version ranges can be specified of course, just showing the relevant ones here): Declare an exact version (will always resolve to 1.0.1): [1.0.1] Declare an explicit version (will always resolve to 1.0.1 unless a collision occurs, when Maven will select a matching version): 1.0.1 Declare a version range for all 1.x (will currently resolve to 1.1.1): [1.0.0,2.0.0) Declare an open-ended version range (will resolve to 2.0.0): [1.0.0,) Declare the version as LATEST (will resolve to 2.0.0) (removed from maven 3.x) LATEST Declare the version as RELEASE (will resolve to 1.1.1) (removed from maven 3.x): RELEASE Note that by default your own deployments will update the "latest" entry in the Maven metadata, but to update the "release" entry, you need to activate the "release-profile" from the Maven super POM. You can do this with either "-Prelease-profile" or "-DperformRelease=true" It's worth emphasising that any approach that allows Maven to pick the dependency versions (LATEST, RELEASE, and version ranges) can leave you open to build time issues, as later versions can have different behaviour (for example the dependency plugin has previously switched a default value from true to false, with confusing results). It is therefore generally a good idea to define exact versions in releases. As Tim's answer points out, the maven-versions-plugin is a handy tool for updating dependency versions, particularly the versions:use-latest-versions and versions:use-latest-releases goals.
How do I tell Maven to use the latest version of a dependency? In Maven, dependencies are usually set up like this: wonderful-inc dream-library 1.2.3 Now, if you are working with libraries that have frequent releases, constantly updating the tag can be somewhat annoying. Is there any way to tell Maven to always use the latest available version (from the repository)?
TITLE: How do I tell Maven to use the latest version of a dependency? QUESTION: In Maven, dependencies are usually set up like this: wonderful-inc dream-library 1.2.3 Now, if you are working with libraries that have frequent releases, constantly updating the tag can be somewhat annoying. Is there any way to tell Maven to always use the latest available version (from the repository)? ANSWER: NOTE: The mentioned LATEST and RELEASE metaversions have been dropped for plugin dependencies in Maven 3 "for the sake of reproducible builds", over 6 years ago. (They still work perfectly fine for regular dependencies.) For plugin dependencies please refer to this Maven 3 compliant solution. If you always want to use the newest version, Maven has two keywords you can use as an alternative to version ranges. You should use these options with care as you are no longer in control of the plugins/dependencies you are using. When you depend on a plugin or a dependency, you can use the a version value of LATEST or RELEASE. LATEST refers to the latest released or snapshot version of a particular artifact, the most recently deployed artifact in a particular repository. RELEASE refers to the last non-snapshot release in the repository. In general, it is not a best practice to design software which depends on a non-specific version of an artifact. If you are developing software, you might want to use RELEASE or LATEST as a convenience so that you don't have to update version numbers when a new release of a third-party library is released. When you release software, you should always make sure that your project depends on specific versions to reduce the chances of your build or your project being affected by a software release not under your control. Use LATEST and RELEASE with caution, if at all. See the POM Syntax section of the Maven book for more details. Or see this doc on Dependency Version Ranges, where: A square bracket ( [ & ] ) means "closed" (inclusive). A parenthesis ( ( & ) ) means "open" (exclusive). Here's an example illustrating the various options. In the Maven repository, com.foo:my-foo has the following metadata: com.foo my-foo 2.0.0 1.1.1 1.0 1.0.1 1.1 1.1.1 2.0.0 20090722140000 If a dependency on that artifact is required, you have the following options (other version ranges can be specified of course, just showing the relevant ones here): Declare an exact version (will always resolve to 1.0.1): [1.0.1] Declare an explicit version (will always resolve to 1.0.1 unless a collision occurs, when Maven will select a matching version): 1.0.1 Declare a version range for all 1.x (will currently resolve to 1.1.1): [1.0.0,2.0.0) Declare an open-ended version range (will resolve to 2.0.0): [1.0.0,) Declare the version as LATEST (will resolve to 2.0.0) (removed from maven 3.x) LATEST Declare the version as RELEASE (will resolve to 1.1.1) (removed from maven 3.x): RELEASE Note that by default your own deployments will update the "latest" entry in the Maven metadata, but to update the "release" entry, you need to activate the "release-profile" from the Maven super POM. You can do this with either "-Prelease-profile" or "-DperformRelease=true" It's worth emphasising that any approach that allows Maven to pick the dependency versions (LATEST, RELEASE, and version ranges) can leave you open to build time issues, as later versions can have different behaviour (for example the dependency plugin has previously switched a default value from true to false, with confusing results). It is therefore generally a good idea to define exact versions in releases. As Tim's answer points out, the maven-versions-plugin is a handy tool for updating dependency versions, particularly the versions:use-latest-versions and versions:use-latest-releases goals.
[ "java", "maven", "dependencies", "maven-2", "maven-metadata" ]
902
847
751,527
12
0
2008-08-27T16:17:02.633000
2009-07-23T14:58:06.890000
30,585
30,705
Can you use CruiseControl to build Cocoa/Objective-C projects?
Has anyone ever set up Cruise Control to build an OS X Cocoa/Objective-C project? If so, is there a preferred flavor of CruiseControl (CruiseControl.rb or just regular CruiseControl) that would be easier to do this with. I currently have a Ruby rake file that has steps for doing building and running tests, and wanted to automate this process after doing a checkin. Also, does CruiseControl have support for git? I couldn't find anything on the website for this.
Yes, you just run xcode builds via the command line (xcodebuild) which makes it simple to target from CC via an ant. I've been using just regular CC, not the ruby version and it works fine. Here's a barebones example: More info on xcodebuild And there does appear to be a standard git object here, but I don't use git so I can't tell you much more than that!
Can you use CruiseControl to build Cocoa/Objective-C projects? Has anyone ever set up Cruise Control to build an OS X Cocoa/Objective-C project? If so, is there a preferred flavor of CruiseControl (CruiseControl.rb or just regular CruiseControl) that would be easier to do this with. I currently have a Ruby rake file that has steps for doing building and running tests, and wanted to automate this process after doing a checkin. Also, does CruiseControl have support for git? I couldn't find anything on the website for this.
TITLE: Can you use CruiseControl to build Cocoa/Objective-C projects? QUESTION: Has anyone ever set up Cruise Control to build an OS X Cocoa/Objective-C project? If so, is there a preferred flavor of CruiseControl (CruiseControl.rb or just regular CruiseControl) that would be easier to do this with. I currently have a Ruby rake file that has steps for doing building and running tests, and wanted to automate this process after doing a checkin. Also, does CruiseControl have support for git? I couldn't find anything on the website for this. ANSWER: Yes, you just run xcode builds via the command line (xcodebuild) which makes it simple to target from CC via an ant. I've been using just regular CC, not the ruby version and it works fine. Here's a barebones example: More info on xcodebuild And there does appear to be a standard git object here, but I don't use git so I can't tell you much more than that!
[ "cocoa", "testing", "build-process", "cruisecontrol", "cruisecontrol.rb" ]
9
9
935
2
0
2008-08-27T16:26:25.043000
2008-08-27T17:43:09.757000
30,594
30,648
Is it possible to find code coverage in ColdFusion?
I am trying to be a "good" programmer and have unit tests for my ColdFusion application but haven't been able to find a code coverage tool that can tie into the test that I'm using. For those of you who do unit tests on your ColdFusion code, how have you approached this problem?
Many have asked, but to date there remains no ColdFusion code coverage tool. The latest ColdFusion features.NET integration in addition to J2EE integration, so if you require code coverage metrics (ie, customer requirements) then (aside from choosing something other than ColdFusion) you might define what parts need such coverage and break them out into.NET or J2EE objects which you can profile with readily available tools. Alternately, you can do some analysis yourself - use a parser to insert cftrace tags after every control statement and then parse the results. Lastly, ColdFusion does have some basic stack trace ability - I don't know if it goes deeper than that, but it's worth exploring to see what you can parse from that. I hope this helps! -Adam Davis
Is it possible to find code coverage in ColdFusion? I am trying to be a "good" programmer and have unit tests for my ColdFusion application but haven't been able to find a code coverage tool that can tie into the test that I'm using. For those of you who do unit tests on your ColdFusion code, how have you approached this problem?
TITLE: Is it possible to find code coverage in ColdFusion? QUESTION: I am trying to be a "good" programmer and have unit tests for my ColdFusion application but haven't been able to find a code coverage tool that can tie into the test that I'm using. For those of you who do unit tests on your ColdFusion code, how have you approached this problem? ANSWER: Many have asked, but to date there remains no ColdFusion code coverage tool. The latest ColdFusion features.NET integration in addition to J2EE integration, so if you require code coverage metrics (ie, customer requirements) then (aside from choosing something other than ColdFusion) you might define what parts need such coverage and break them out into.NET or J2EE objects which you can profile with readily available tools. Alternately, you can do some analysis yourself - use a parser to insert cftrace tags after every control statement and then parse the results. Lastly, ColdFusion does have some basic stack trace ability - I don't know if it goes deeper than that, but it's worth exploring to see what you can parse from that. I hope this helps! -Adam Davis
[ "unit-testing", "coldfusion" ]
6
0
1,059
2
0
2008-08-27T16:34:09.300000
2008-08-27T17:04:50.647000
30,627
30,697
How would you use Java to handle various XML documents?
I'm looking for the best method to parse various XML documents using a Java application. I'm currently doing this with SAX and a custom content handler and it works great - zippy and stable. I've decided to explore the option having the same program, that currently recieves a single format XML document, receive two additional XML document formats, with various XML element changes. I was hoping to just swap out the ContentHandler with an appropriate one based on the first "startElement" in the document... but, uh-duh, the ContentHandler is set and then the document is parsed!... constructor... { SAXParserFactory spf = SAXParserFactory.newInstance(); try { SAXParser sp = spf.newSAXParser(); parser = sp.getXMLReader(); parser.setErrorHandler(new MyErrorHandler()); } catch (Exception e) {}... parse StringBuffer... try { parser.setContentHandler(pP); parser.parse(new InputSource(new StringReader(xml.toString()))); return true; } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); }... So, it doesn't appear that I can do this in the way I initially thought I could. That being said, am I looking at this entirely wrong? What is the best method to parse multiple, discrete XML documents with the same XML handling code? I tried to ask in a more general post earlier... but, I think I was being too vague. For speed and efficiency purposes I never really looked at DOM because these XML documents are fairly large and the system receives about 1200 every few minutes. It's just a one way send of information To make this question too long and add to my confusion; following is a mockup of some various XML documents that I would like to have a single SAX, StAX, or?? parser cleanly deal with. products.xml: 1 Foo 2 bar stores.xml: 1 S1A CA 2 A1S NY managers.xml: 1 Fen 1 2 Diz 2
As I understand it, the problem is that you don't know what format the document is prior to parsing. You could use a delegate pattern. I'm assuming you're not validating against a DTD/XSD/etcetera and that it is OK for the DefaultHandler to have state. public class DelegatingHandler extends DefaultHandler { private Map saxHandlers; private DefaultHandler delegate = null; public DelegatingHandler(Map delegates) { saxHandlers = delegates; } @Override public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException { if(delegate == null) { delegate = saxHandlers.get(name); } delegate.startElement(uri, localName, name, attributes); } @Override public void endElement(String uri, String localName, String name) throws SAXException { delegate.endElement(uri, localName, name); } //etcetera...
How would you use Java to handle various XML documents? I'm looking for the best method to parse various XML documents using a Java application. I'm currently doing this with SAX and a custom content handler and it works great - zippy and stable. I've decided to explore the option having the same program, that currently recieves a single format XML document, receive two additional XML document formats, with various XML element changes. I was hoping to just swap out the ContentHandler with an appropriate one based on the first "startElement" in the document... but, uh-duh, the ContentHandler is set and then the document is parsed!... constructor... { SAXParserFactory spf = SAXParserFactory.newInstance(); try { SAXParser sp = spf.newSAXParser(); parser = sp.getXMLReader(); parser.setErrorHandler(new MyErrorHandler()); } catch (Exception e) {}... parse StringBuffer... try { parser.setContentHandler(pP); parser.parse(new InputSource(new StringReader(xml.toString()))); return true; } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); }... So, it doesn't appear that I can do this in the way I initially thought I could. That being said, am I looking at this entirely wrong? What is the best method to parse multiple, discrete XML documents with the same XML handling code? I tried to ask in a more general post earlier... but, I think I was being too vague. For speed and efficiency purposes I never really looked at DOM because these XML documents are fairly large and the system receives about 1200 every few minutes. It's just a one way send of information To make this question too long and add to my confusion; following is a mockup of some various XML documents that I would like to have a single SAX, StAX, or?? parser cleanly deal with. products.xml: 1 Foo 2 bar stores.xml: 1 S1A CA 2 A1S NY managers.xml: 1 Fen 1 2 Diz 2
TITLE: How would you use Java to handle various XML documents? QUESTION: I'm looking for the best method to parse various XML documents using a Java application. I'm currently doing this with SAX and a custom content handler and it works great - zippy and stable. I've decided to explore the option having the same program, that currently recieves a single format XML document, receive two additional XML document formats, with various XML element changes. I was hoping to just swap out the ContentHandler with an appropriate one based on the first "startElement" in the document... but, uh-duh, the ContentHandler is set and then the document is parsed!... constructor... { SAXParserFactory spf = SAXParserFactory.newInstance(); try { SAXParser sp = spf.newSAXParser(); parser = sp.getXMLReader(); parser.setErrorHandler(new MyErrorHandler()); } catch (Exception e) {}... parse StringBuffer... try { parser.setContentHandler(pP); parser.parse(new InputSource(new StringReader(xml.toString()))); return true; } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); }... So, it doesn't appear that I can do this in the way I initially thought I could. That being said, am I looking at this entirely wrong? What is the best method to parse multiple, discrete XML documents with the same XML handling code? I tried to ask in a more general post earlier... but, I think I was being too vague. For speed and efficiency purposes I never really looked at DOM because these XML documents are fairly large and the system receives about 1200 every few minutes. It's just a one way send of information To make this question too long and add to my confusion; following is a mockup of some various XML documents that I would like to have a single SAX, StAX, or?? parser cleanly deal with. products.xml: 1 Foo 2 bar stores.xml: 1 S1A CA 2 A1S NY managers.xml: 1 Fen 1 2 Diz 2 ANSWER: As I understand it, the problem is that you don't know what format the document is prior to parsing. You could use a delegate pattern. I'm assuming you're not validating against a DTD/XSD/etcetera and that it is OK for the DefaultHandler to have state. public class DelegatingHandler extends DefaultHandler { private Map saxHandlers; private DefaultHandler delegate = null; public DelegatingHandler(Map delegates) { saxHandlers = delegates; } @Override public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException { if(delegate == null) { delegate = saxHandlers.get(name); } delegate.startElement(uri, localName, name, attributes); } @Override public void endElement(String uri, String localName, String name) throws SAXException { delegate.endElement(uri, localName, name); } //etcetera...
[ "java", "xml", "sax", "stax" ]
2
3
1,930
9
0
2008-08-27T16:55:59.327000
2008-08-27T17:38:38.753000
30,632
30,645
Difference between the Apache HTTP Server and Apache Tomcat?
What is the difference in terms of functionality between the Apache HTTP Server and Apache Tomcat? I know that Tomcat is written in Java and the HTTP Server is in C, but other than that I do not really know how they are distinguished. Do they have different functionality?
Apache Tomcat is used to deploy your Java Servlets and JSPs. So in your Java project you can build your WAR (short for Web ARchive) file, and just drop it in the deploy directory in Tomcat. So basically Apache is an HTTP Server, serving HTTP. Tomcat is a Servlet and JSP Server serving Java technologies. Tomcat includes Catalina, which is a servlet container. A servlet, at the end, is a Java class. JSP files (which are similar to PHP, and older ASP files) are generated into Java code (HttpServlet), which is then compiled to.class files by the server and executed by the Java virtual machine.
Difference between the Apache HTTP Server and Apache Tomcat? What is the difference in terms of functionality between the Apache HTTP Server and Apache Tomcat? I know that Tomcat is written in Java and the HTTP Server is in C, but other than that I do not really know how they are distinguished. Do they have different functionality?
TITLE: Difference between the Apache HTTP Server and Apache Tomcat? QUESTION: What is the difference in terms of functionality between the Apache HTTP Server and Apache Tomcat? I know that Tomcat is written in Java and the HTTP Server is in C, but other than that I do not really know how they are distinguished. Do they have different functionality? ANSWER: Apache Tomcat is used to deploy your Java Servlets and JSPs. So in your Java project you can build your WAR (short for Web ARchive) file, and just drop it in the deploy directory in Tomcat. So basically Apache is an HTTP Server, serving HTTP. Tomcat is a Servlet and JSP Server serving Java technologies. Tomcat includes Catalina, which is a servlet container. A servlet, at the end, is a Java class. JSP files (which are similar to PHP, and older ASP files) are generated into Java code (HttpServlet), which is then compiled to.class files by the server and executed by the Java virtual machine.
[ "apache", "tomcat", "webserver" ]
685
505
605,994
8
0
2008-08-27T16:57:16.497000
2008-08-27T17:03:29.290000
30,651
30,666
Open 2 Visio diagrams in different windows
I would like to know if I can open 2 different diagrams using MS Visio and each diagram have its own window. I've tried in several ways, but I always end up with 1 Visio window... I'm using a triple monitor setup and I'd like to put one diagram to each side of my main monitor. []'s André Casteliano PS: I'm using Visio 2007 here.
Visio 2005 allows you to open visio multiple times - does this not work in 2007? Try opening a visio document, and then starting another instance of visio from the Start-->Programs menu. If not, read on... Visio is an MDI interface - you'll need to stretch the whole visio window across the two monitors in question, then choose the "Window" menu and select "Tile" after you've opened your two documents. Alternately, in the upper right hand corner just below the application minimize, restore and close buttons you'll find the document minimize, restore and close. Choose restore, and you can manipulate the windows inside the main visio app. Hope this helps! -Adam Davis
Open 2 Visio diagrams in different windows I would like to know if I can open 2 different diagrams using MS Visio and each diagram have its own window. I've tried in several ways, but I always end up with 1 Visio window... I'm using a triple monitor setup and I'd like to put one diagram to each side of my main monitor. []'s André Casteliano PS: I'm using Visio 2007 here.
TITLE: Open 2 Visio diagrams in different windows QUESTION: I would like to know if I can open 2 different diagrams using MS Visio and each diagram have its own window. I've tried in several ways, but I always end up with 1 Visio window... I'm using a triple monitor setup and I'd like to put one diagram to each side of my main monitor. []'s André Casteliano PS: I'm using Visio 2007 here. ANSWER: Visio 2005 allows you to open visio multiple times - does this not work in 2007? Try opening a visio document, and then starting another instance of visio from the Start-->Programs menu. If not, read on... Visio is an MDI interface - you'll need to stretch the whole visio window across the two monitors in question, then choose the "Window" menu and select "Tile" after you've opened your two documents. Alternately, in the upper right hand corner just below the application minimize, restore and close buttons you'll find the document minimize, restore and close. Choose restore, and you can manipulate the windows inside the main visio app. Hope this helps! -Adam Davis
[ "diagram", "visio" ]
23
8
45,274
3
0
2008-08-27T17:06:51.607000
2008-08-27T17:15:20.463000
30,653
39,106
What do I need to do to implement an "out of proc" COM server in C#?
I am trying to implement an "out of proc" COM server written in C#. How do I do this? I need the C# code to be "out of proc" from my main C++ application, because I cannot load the.NET runtime into my main process space WHY?: My C++ code is in a DLL that is loaded into many different customer EXE's, some of which use different versions of the.NET runtime. Since there can only be one runtime loaded into a single process, my best bet seems to be to put my C# code into another process.
You can create COM+ components using System.EnterpriseServices.ServicedComponent. Consequently, you'll be able to create out-of-proc and in-proc (client) component activation as well as all COM+ benefits of pooling, remoting, run as a windows service etc.
What do I need to do to implement an "out of proc" COM server in C#? I am trying to implement an "out of proc" COM server written in C#. How do I do this? I need the C# code to be "out of proc" from my main C++ application, because I cannot load the.NET runtime into my main process space WHY?: My C++ code is in a DLL that is loaded into many different customer EXE's, some of which use different versions of the.NET runtime. Since there can only be one runtime loaded into a single process, my best bet seems to be to put my C# code into another process.
TITLE: What do I need to do to implement an "out of proc" COM server in C#? QUESTION: I am trying to implement an "out of proc" COM server written in C#. How do I do this? I need the C# code to be "out of proc" from my main C++ application, because I cannot load the.NET runtime into my main process space WHY?: My C++ code is in a DLL that is loaded into many different customer EXE's, some of which use different versions of the.NET runtime. Since there can only be one runtime loaded into a single process, my best bet seems to be to put my C# code into another process. ANSWER: You can create COM+ components using System.EnterpriseServices.ServicedComponent. Consequently, you'll be able to create out-of-proc and in-proc (client) component activation as well as all COM+ benefits of pooling, remoting, run as a windows service etc.
[ "c#", "com", "interop" ]
11
7
6,297
4
0
2008-08-27T17:08:47.220000
2008-09-02T09:41:09.230000
30,660
30,889
MySQL Binary Log Replication: Can it be set to ignore errors?
I'm running a master-slave MySQL binary log replication system (phew!) that, for some data, is not in sync (meaning, the master holds more data than the slave). But the slave stops very frequently on the slightest MySQL error, can this be disabled? (perhaps a my.cnf setting for the replicating slave ignore-replicating-errors or some of the sort;) ) This is what happens, every now and then, when the slave tries to replicate an item that does not exist, the slave just dies. a quick check at SHOW SLAVE STATUS \G; gives Slave-IO-Running: Yes Slave-SQL-Running: No Replicate-Do-DB: Last-Errno: 1062 Last-Error: Error 'Duplicate entry '15218' for key 1' on query. Default database: 'db'. Query: 'INSERT INTO db.table ( FIELDS ) VALUES ( VALUES )' which I promptly fix (once I realize that the slave has been stopped) by doing the following: STOP SLAVE; RESET SLAVE; START SLAVE;... lately this has been getting kind of tiresome, and before I spit out some sort of PHP which does this for me, i was wondering if there's some my.cnf entry which will not kill the slave on the first error. Cheers, /mp
Yes, with --slave-skip-errors=xxx in my.cnf, where xxx is 'all' or a comma sep list of error codes.
MySQL Binary Log Replication: Can it be set to ignore errors? I'm running a master-slave MySQL binary log replication system (phew!) that, for some data, is not in sync (meaning, the master holds more data than the slave). But the slave stops very frequently on the slightest MySQL error, can this be disabled? (perhaps a my.cnf setting for the replicating slave ignore-replicating-errors or some of the sort;) ) This is what happens, every now and then, when the slave tries to replicate an item that does not exist, the slave just dies. a quick check at SHOW SLAVE STATUS \G; gives Slave-IO-Running: Yes Slave-SQL-Running: No Replicate-Do-DB: Last-Errno: 1062 Last-Error: Error 'Duplicate entry '15218' for key 1' on query. Default database: 'db'. Query: 'INSERT INTO db.table ( FIELDS ) VALUES ( VALUES )' which I promptly fix (once I realize that the slave has been stopped) by doing the following: STOP SLAVE; RESET SLAVE; START SLAVE;... lately this has been getting kind of tiresome, and before I spit out some sort of PHP which does this for me, i was wondering if there's some my.cnf entry which will not kill the slave on the first error. Cheers, /mp
TITLE: MySQL Binary Log Replication: Can it be set to ignore errors? QUESTION: I'm running a master-slave MySQL binary log replication system (phew!) that, for some data, is not in sync (meaning, the master holds more data than the slave). But the slave stops very frequently on the slightest MySQL error, can this be disabled? (perhaps a my.cnf setting for the replicating slave ignore-replicating-errors or some of the sort;) ) This is what happens, every now and then, when the slave tries to replicate an item that does not exist, the slave just dies. a quick check at SHOW SLAVE STATUS \G; gives Slave-IO-Running: Yes Slave-SQL-Running: No Replicate-Do-DB: Last-Errno: 1062 Last-Error: Error 'Duplicate entry '15218' for key 1' on query. Default database: 'db'. Query: 'INSERT INTO db.table ( FIELDS ) VALUES ( VALUES )' which I promptly fix (once I realize that the slave has been stopped) by doing the following: STOP SLAVE; RESET SLAVE; START SLAVE;... lately this has been getting kind of tiresome, and before I spit out some sort of PHP which does this for me, i was wondering if there's some my.cnf entry which will not kill the slave on the first error. Cheers, /mp ANSWER: Yes, with --slave-skip-errors=xxx in my.cnf, where xxx is 'all' or a comma sep list of error codes.
[ "mysql", "replication", "mysql-error-1062", "binlog" ]
12
12
19,748
6
0
2008-08-27T17:11:09.117000
2008-08-27T18:58:09.937000
30,686
30,708
Get file version in PowerShell
How can you get the version information from a.dll or.exe file in PowerShell? I am specifically interested in File Version, though other version information (that is, Company, Language, Product Name, etc.) would be helpful as well.
Since PowerShell can call.NET classes, you could do the following: [System.Diagnostics.FileVersionInfo]::GetVersionInfo("somefilepath").FileVersion Or as noted here on a list of files: get-childitem * -include *.dll,*.exe | foreach-object { "{0}`t{1}" -f $_.Name, [System.Diagnostics.FileVersionInfo]::GetVersionInfo($_).FileVersion } Or even nicer as a script: https://jtruher3.wordpress.com/2006/05/14/powershell-and-file-version-information/
Get file version in PowerShell How can you get the version information from a.dll or.exe file in PowerShell? I am specifically interested in File Version, though other version information (that is, Company, Language, Product Name, etc.) would be helpful as well.
TITLE: Get file version in PowerShell QUESTION: How can you get the version information from a.dll or.exe file in PowerShell? I am specifically interested in File Version, though other version information (that is, Company, Language, Product Name, etc.) would be helpful as well. ANSWER: Since PowerShell can call.NET classes, you could do the following: [System.Diagnostics.FileVersionInfo]::GetVersionInfo("somefilepath").FileVersion Or as noted here on a list of files: get-childitem * -include *.dll,*.exe | foreach-object { "{0}`t{1}" -f $_.Name, [System.Diagnostics.FileVersionInfo]::GetVersionInfo($_).FileVersion } Or even nicer as a script: https://jtruher3.wordpress.com/2006/05/14/powershell-and-file-version-information/
[ "file", "powershell", "versioninfo" ]
187
177
321,112
11
0
2008-08-27T17:28:48.903000
2008-08-27T17:45:54.493000
30,706
30,798
How do I create a draggable and resizable JavaScript popup window?
I want to create a draggable and resizable window in JavaScript for cross browser use, but I want to try and avoid using a framework if I can. Has anyone got a link or some code that I can use?
JQuery is more focused on a lot of nice utility functions, and makes DOM manipulation a whole lot easier. Basically, I consider it to be Javascript as it should have been. It's a supremely helpful addition to the Javascript language itself. ExtJS is a suite of GUI components with specific APIs... Use it if you want to easily create components that look like that, otherwise, go with a more flexible framework.
How do I create a draggable and resizable JavaScript popup window? I want to create a draggable and resizable window in JavaScript for cross browser use, but I want to try and avoid using a framework if I can. Has anyone got a link or some code that I can use?
TITLE: How do I create a draggable and resizable JavaScript popup window? QUESTION: I want to create a draggable and resizable window in JavaScript for cross browser use, but I want to try and avoid using a framework if I can. Has anyone got a link or some code that I can use? ANSWER: JQuery is more focused on a lot of nice utility functions, and makes DOM manipulation a whole lot easier. Basically, I consider it to be Javascript as it should have been. It's a supremely helpful addition to the Javascript language itself. ExtJS is a suite of GUI components with specific APIs... Use it if you want to easily create components that look like that, otherwise, go with a more flexible framework.
[ "javascript", "dialog" ]
3
2
4,206
5
0
2008-08-27T17:45:06.743000
2008-08-27T18:21:49.667000
30,710
30,818
How to unit test an object with database queries
I've heard that unit testing is "totally awesome", "really cool" and "all manner of good things" but 70% or more of my files involve database access (some read and some write) and I'm not sure how to write a unit test for these files. I'm using PHP and Python but I think it's a question that applies to most/all languages that use database access.
I would suggest mocking out your calls to the database. Mocks are basically objects that look like the object you are trying to call a method on, in the sense that they have the same properties, methods, etc. available to caller. But instead of performing whatever action they are programmed to do when a particular method is called, it skips that altogether, and just returns a result. That result is typically defined by you ahead of time. In order to set up your objects for mocking, you probably need to use some sort of inversion of control/ dependency injection pattern, as in the following pseudo-code: class Bar { private FooDataProvider _dataProvider; public instantiate(FooDataProvider dataProvider) { _dataProvider = dataProvider; } public getAllFoos() { // instead of calling Foo.GetAll() here, we are introducing an extra layer of abstraction return _dataProvider.GetAllFoos(); } } class FooDataProvider { public Foo[] GetAllFoos() { return Foo.GetAll(); } } Now in your unit test, you create a mock of FooDataProvider, which allows you to call the method GetAllFoos without having to actually hit the database. class BarTests { public TestGetAllFoos() { // here we set up our mock FooDataProvider mockRepository = MockingFramework.new() mockFooDataProvider = mockRepository.CreateMockOfType(FooDataProvider); // create a new array of Foo objects testFooArray = new Foo[] {Foo.new(), Foo.new(), Foo.new()} // the next statement will cause testFooArray to be returned every time we call FooDAtaProvider.GetAllFoos, // instead of calling to the database and returning whatever is in there // ExpectCallTo and Returns are methods provided by our imaginary mocking framework ExpectCallTo(mockFooDataProvider.GetAllFoos).Returns(testFooArray) // now begins our actual unit test testBar = new Bar(mockFooDataProvider) baz = testBar.GetAllFoos() // baz should now equal the testFooArray object we created earlier Assert.AreEqual(3, baz.length) } } A common mocking scenario, in a nutshell. Of course you will still probably want to unit test your actual database calls too, for which you will need to hit the database.
How to unit test an object with database queries I've heard that unit testing is "totally awesome", "really cool" and "all manner of good things" but 70% or more of my files involve database access (some read and some write) and I'm not sure how to write a unit test for these files. I'm using PHP and Python but I think it's a question that applies to most/all languages that use database access.
TITLE: How to unit test an object with database queries QUESTION: I've heard that unit testing is "totally awesome", "really cool" and "all manner of good things" but 70% or more of my files involve database access (some read and some write) and I'm not sure how to write a unit test for these files. I'm using PHP and Python but I think it's a question that applies to most/all languages that use database access. ANSWER: I would suggest mocking out your calls to the database. Mocks are basically objects that look like the object you are trying to call a method on, in the sense that they have the same properties, methods, etc. available to caller. But instead of performing whatever action they are programmed to do when a particular method is called, it skips that altogether, and just returns a result. That result is typically defined by you ahead of time. In order to set up your objects for mocking, you probably need to use some sort of inversion of control/ dependency injection pattern, as in the following pseudo-code: class Bar { private FooDataProvider _dataProvider; public instantiate(FooDataProvider dataProvider) { _dataProvider = dataProvider; } public getAllFoos() { // instead of calling Foo.GetAll() here, we are introducing an extra layer of abstraction return _dataProvider.GetAllFoos(); } } class FooDataProvider { public Foo[] GetAllFoos() { return Foo.GetAll(); } } Now in your unit test, you create a mock of FooDataProvider, which allows you to call the method GetAllFoos without having to actually hit the database. class BarTests { public TestGetAllFoos() { // here we set up our mock FooDataProvider mockRepository = MockingFramework.new() mockFooDataProvider = mockRepository.CreateMockOfType(FooDataProvider); // create a new array of Foo objects testFooArray = new Foo[] {Foo.new(), Foo.new(), Foo.new()} // the next statement will cause testFooArray to be returned every time we call FooDAtaProvider.GetAllFoos, // instead of calling to the database and returning whatever is in there // ExpectCallTo and Returns are methods provided by our imaginary mocking framework ExpectCallTo(mockFooDataProvider.GetAllFoos).Returns(testFooArray) // now begins our actual unit test testBar = new Bar(mockFooDataProvider) baz = testBar.GetAllFoos() // baz should now equal the testFooArray object we created earlier Assert.AreEqual(3, baz.length) } } A common mocking scenario, in a nutshell. Of course you will still probably want to unit test your actual database calls too, for which you will need to hit the database.
[ "database", "unit-testing" ]
174
90
104,229
13
0
2008-08-27T17:46:02.763000
2008-08-27T18:30:47.227000
30,712
30,874
What is the proper virtual directory access permission level required for a SOAP web service?
When setting up a new virtual directory for hosting a SOAP web service in IIS 6.0 on a Server 2003 box I am required to set the access permissions for the virtual directory. The various permissions are to allow/disallow the following: Read Run scripts (such as ASP) Execute (such as ISAPI or CGI) Write Browse The SOAP web service is being published through the SOAP3.0 ISAPI server with the extensions set to "Allowed" in the Web Service Extensions pane of the IIS Manager. Since I don't want to expose the contents of this directory to the web I know Browse is not desirable. But, I don't know if I need to have the Run scripts, Execute, and Write permissions enabled to properly publish this web service. The web service is being used to send and receive XML data sets between the server and remote clients. What is the correct level of access permission for my SOAP web service's virtual directory?
Upon further examination, I've come to the conclusion that one assumption I had about needing Read permissions was incorrect. SOAP web services only need the "Run scripts" permission enabled because the.wsdl apparently comes from the web service in the form of a script execution response. So the minimum required for a SOAP3.0 web service's directory is Run scripts.
What is the proper virtual directory access permission level required for a SOAP web service? When setting up a new virtual directory for hosting a SOAP web service in IIS 6.0 on a Server 2003 box I am required to set the access permissions for the virtual directory. The various permissions are to allow/disallow the following: Read Run scripts (such as ASP) Execute (such as ISAPI or CGI) Write Browse The SOAP web service is being published through the SOAP3.0 ISAPI server with the extensions set to "Allowed" in the Web Service Extensions pane of the IIS Manager. Since I don't want to expose the contents of this directory to the web I know Browse is not desirable. But, I don't know if I need to have the Run scripts, Execute, and Write permissions enabled to properly publish this web service. The web service is being used to send and receive XML data sets between the server and remote clients. What is the correct level of access permission for my SOAP web service's virtual directory?
TITLE: What is the proper virtual directory access permission level required for a SOAP web service? QUESTION: When setting up a new virtual directory for hosting a SOAP web service in IIS 6.0 on a Server 2003 box I am required to set the access permissions for the virtual directory. The various permissions are to allow/disallow the following: Read Run scripts (such as ASP) Execute (such as ISAPI or CGI) Write Browse The SOAP web service is being published through the SOAP3.0 ISAPI server with the extensions set to "Allowed" in the Web Service Extensions pane of the IIS Manager. Since I don't want to expose the contents of this directory to the web I know Browse is not desirable. But, I don't know if I need to have the Run scripts, Execute, and Write permissions enabled to properly publish this web service. The web service is being used to send and receive XML data sets between the server and remote clients. What is the correct level of access permission for my SOAP web service's virtual directory? ANSWER: Upon further examination, I've come to the conclusion that one assumption I had about needing Read permissions was incorrect. SOAP web services only need the "Run scripts" permission enabled because the.wsdl apparently comes from the web service in the form of a script execution response. So the minimum required for a SOAP3.0 web service's directory is Run scripts.
[ "web-services", "soap", "file-permissions" ]
5
4
1,443
1
0
2008-08-27T17:48:21.867000
2008-08-27T18:53:43.737000
30,729
30,766
C# Performance For Proxy Server (vs C++)
I want to create a simple http proxy server that does some very basic processing on the http headers (i.e. if header x == y, do z). The server may need to support hundreds of users. I can write the server in C# (pretty easy) or c++ (much harder). However, would a C# version have as good of performance as a C++ version? If not, would the difference in performance be big enough that it would not make sense to write it in C#?
You can use unsafe C# code and pointers in critical bottleneck points to make it run faster. Those behave much like C++ code and I believe it executes as fast. But most of the time, C# is JIT-ted to uber-fast already, I don't believe there will be much differences as with what everyone has said. But one thing you might want to consider is: Managed code (C#) string operations are rather slow compared to using pointers effectively in C++. There are more optimization tricks with C++ pointers than with CLR strings. I think I have done some benchmarks before, but can't remember where I've put them.
C# Performance For Proxy Server (vs C++) I want to create a simple http proxy server that does some very basic processing on the http headers (i.e. if header x == y, do z). The server may need to support hundreds of users. I can write the server in C# (pretty easy) or c++ (much harder). However, would a C# version have as good of performance as a C++ version? If not, would the difference in performance be big enough that it would not make sense to write it in C#?
TITLE: C# Performance For Proxy Server (vs C++) QUESTION: I want to create a simple http proxy server that does some very basic processing on the http headers (i.e. if header x == y, do z). The server may need to support hundreds of users. I can write the server in C# (pretty easy) or c++ (much harder). However, would a C# version have as good of performance as a C++ version? If not, would the difference in performance be big enough that it would not make sense to write it in C#? ANSWER: You can use unsafe C# code and pointers in critical bottleneck points to make it run faster. Those behave much like C++ code and I believe it executes as fast. But most of the time, C# is JIT-ted to uber-fast already, I don't believe there will be much differences as with what everyone has said. But one thing you might want to consider is: Managed code (C#) string operations are rather slow compared to using pointers effectively in C++. There are more optimization tricks with C++ pointers than with CLR strings. I think I have done some benchmarks before, but can't remember where I've put them.
[ "c#", "c++", "performance", "sockets", "system.net" ]
4
4
2,736
7
0
2008-08-27T17:55:16.577000
2008-08-27T18:12:53.773000
30,754
30,796
Performance vs Readability
Reading this question I found this as (note the quotation marks) "code" to solve the problem (that's perl by the way). 100,{)..3%!'Fizz'*\5%!'Buzz'*+\or}%n* Obviously this is an intellectual example without real (I hope to never see that in real code in my life) implications but, when you have to make the choice, when do you sacrifice code readability for performance? Do you apply just common sense, do you do it always as a last resort? What are your strategies? Edit: I'm sorry, seeing the answers I might have expressed the question badly (English is not my native language). I don't mean performance vs readability only after you've written the code, I ask about before you write it as well. Sometimes you can foresee a performance improvement in the future by making some darker design or providing with some properties that will make your class darker. You may decide you will use multiple threads or just a single one because you expect the scalability that such threads may give you, even when that will make the code much more difficult to understand.
My process for situations where I think performance may be an issue: Make it work. Make it clear. Test the performance. If there are meaningful performance issues: refactor for speed. Note that this does not apply to higher-level design decisions that are more difficult to change at a later stage.
Performance vs Readability Reading this question I found this as (note the quotation marks) "code" to solve the problem (that's perl by the way). 100,{)..3%!'Fizz'*\5%!'Buzz'*+\or}%n* Obviously this is an intellectual example without real (I hope to never see that in real code in my life) implications but, when you have to make the choice, when do you sacrifice code readability for performance? Do you apply just common sense, do you do it always as a last resort? What are your strategies? Edit: I'm sorry, seeing the answers I might have expressed the question badly (English is not my native language). I don't mean performance vs readability only after you've written the code, I ask about before you write it as well. Sometimes you can foresee a performance improvement in the future by making some darker design or providing with some properties that will make your class darker. You may decide you will use multiple threads or just a single one because you expect the scalability that such threads may give you, even when that will make the code much more difficult to understand.
TITLE: Performance vs Readability QUESTION: Reading this question I found this as (note the quotation marks) "code" to solve the problem (that's perl by the way). 100,{)..3%!'Fizz'*\5%!'Buzz'*+\or}%n* Obviously this is an intellectual example without real (I hope to never see that in real code in my life) implications but, when you have to make the choice, when do you sacrifice code readability for performance? Do you apply just common sense, do you do it always as a last resort? What are your strategies? Edit: I'm sorry, seeing the answers I might have expressed the question badly (English is not my native language). I don't mean performance vs readability only after you've written the code, I ask about before you write it as well. Sometimes you can foresee a performance improvement in the future by making some darker design or providing with some properties that will make your class darker. You may decide you will use multiple threads or just a single one because you expect the scalability that such threads may give you, even when that will make the code much more difficult to understand. ANSWER: My process for situations where I think performance may be an issue: Make it work. Make it clear. Test the performance. If there are meaningful performance issues: refactor for speed. Note that this does not apply to higher-level design decisions that are more difficult to change at a later stage.
[ "performance" ]
21
29
4,154
14
0
2008-08-27T18:09:42.877000
2008-08-27T18:21:26.327000
30,763
30,771
Understanding Interfaces
I have class method that returns a list of employees that I can iterate through. What's the best way to return the list? Typically I just return an ArrayList. However, as I understand, interfaces are better suited for this type of action. Which would be the best interface to use? Also, why is it better to return an interface, rather than the implementation (say ArrayList object)? It just seems like a lot more work to me.
Personally, I would use a List for creating the list on the backend, and then use IList when you return. When you use interfaces, it gives you the flexability to change the implementation without having to alter who's using your code. If you wanted to stick with an ArrayList, that'd be a non-generic IList.
Understanding Interfaces I have class method that returns a list of employees that I can iterate through. What's the best way to return the list? Typically I just return an ArrayList. However, as I understand, interfaces are better suited for this type of action. Which would be the best interface to use? Also, why is it better to return an interface, rather than the implementation (say ArrayList object)? It just seems like a lot more work to me.
TITLE: Understanding Interfaces QUESTION: I have class method that returns a list of employees that I can iterate through. What's the best way to return the list? Typically I just return an ArrayList. However, as I understand, interfaces are better suited for this type of action. Which would be the best interface to use? Also, why is it better to return an interface, rather than the implementation (say ArrayList object)? It just seems like a lot more work to me. ANSWER: Personally, I would use a List for creating the list on the backend, and then use IList when you return. When you use interfaces, it gives you the flexability to change the implementation without having to alter who's using your code. If you wanted to stick with an ArrayList, that'd be a non-generic IList.
[ "interface" ]
5
4
667
11
0
2008-08-27T18:12:20.203000
2008-08-27T18:14:52.660000
30,775
31,368
NHibernate and Oracle connect through Windows Authenication
How do I use Windows Authentication to connect to an Oracle database? Currently, I just use an Oracle Username and password, however, a requirement is to give the user on install the option of selecting Windows Authentication since we offer the same as SQL.
You need to modify the AUTHENTICATION_SERVICES entry in SQLNET.ORA to this: SQLNET.AUTHENTICATION_SERVICES= (NTS) As well, you will need to setup the accounts in Oracle to match the Windows accounts. Have a look at http://www.dba-oracle.com/bk_sqlnet_authentication_services.htm for more details.
NHibernate and Oracle connect through Windows Authenication How do I use Windows Authentication to connect to an Oracle database? Currently, I just use an Oracle Username and password, however, a requirement is to give the user on install the option of selecting Windows Authentication since we offer the same as SQL.
TITLE: NHibernate and Oracle connect through Windows Authenication QUESTION: How do I use Windows Authentication to connect to an Oracle database? Currently, I just use an Oracle Username and password, however, a requirement is to give the user on install the option of selecting Windows Authentication since we offer the same as SQL. ANSWER: You need to modify the AUTHENTICATION_SERVICES entry in SQLNET.ORA to this: SQLNET.AUTHENTICATION_SERVICES= (NTS) As well, you will need to setup the accounts in Oracle to match the Windows accounts. Have a look at http://www.dba-oracle.com/bk_sqlnet_authentication_services.htm for more details.
[ "windows", "oracle", "nhibernate" ]
4
4
596
1
0
2008-08-27T18:15:39.837000
2008-08-27T23:56:20.093000
30,781
30,792
How do I retrieve data sent to the web server in ASP.NET?
What are the ways to retrieve data submitted to the web server from a form in the client HTML in ASP.NET?
You can also search through both the Form and QueryString collections at the same time so that the data will be found regardless of the the request method. value = Request("formElementID")
How do I retrieve data sent to the web server in ASP.NET? What are the ways to retrieve data submitted to the web server from a form in the client HTML in ASP.NET?
TITLE: How do I retrieve data sent to the web server in ASP.NET? QUESTION: What are the ways to retrieve data submitted to the web server from a form in the client HTML in ASP.NET? ANSWER: You can also search through both the Form and QueryString collections at the same time so that the data will be found regardless of the the request method. value = Request("formElementID")
[ "html", "asp.net" ]
0
4
224
2
0
2008-08-27T18:16:37.510000
2008-08-27T18:19:20.607000
30,790
30,809
Is there a Way to use Linq to Oracle
I can connect with the DataContext to the Oracle database however I get errors in running the query against the oracle database. I looked at the SQL generated and it is for MSSQL and not Oracle PSQL. Does anybody know of a decent easy to use wrapper to use LINQ against an Oracle Database?
No, LINQ to SQL is very much MS SQL only - think of it as a client driver. Microsoft is/was helping Oracle and DataDirect develop providers for Oracle and other non-MS database servers.
Is there a Way to use Linq to Oracle I can connect with the DataContext to the Oracle database however I get errors in running the query against the oracle database. I looked at the SQL generated and it is for MSSQL and not Oracle PSQL. Does anybody know of a decent easy to use wrapper to use LINQ against an Oracle Database?
TITLE: Is there a Way to use Linq to Oracle QUESTION: I can connect with the DataContext to the Oracle database however I get errors in running the query against the oracle database. I looked at the SQL generated and it is for MSSQL and not Oracle PSQL. Does anybody know of a decent easy to use wrapper to use LINQ against an Oracle Database? ANSWER: No, LINQ to SQL is very much MS SQL only - think of it as a client driver. Microsoft is/was helping Oracle and DataDirect develop providers for Oracle and other non-MS database servers.
[ "linq", "oracle" ]
17
12
24,633
11
0
2008-08-27T18:18:29.033000
2008-08-27T18:26:12.213000
30,800
36,384
How can I authenticate using client credentials in WCF just once?
What is the best approach to make sure you only need to authenticate once when using an API built on WCF? My current bindings and behaviors are listed below Next is what I am using in my client app to authenticate (currently I must do this everytime I want to make a call into WCF) Dim client As ProductServiceClient = New ProductServiceClient("wsHttpProductService") client.ClientCredentials.UserName.UserName = "foo" client.ClientCredentials.UserName.Password = "bar" Dim ProductList As List(Of Product) = client.GetProducts() What I would like to do is auth w/ the API once using these credentials, then get some type of token for the period of time my client application is using the web service project. I thought establishsecuritycontext=true did this for me?
If you're on an intranet, Windows authentication can be handled for "free" by configuration alone. If this isn't appropriate, token services work just fine, but for some situations they may be just too much. The application I'm working on needed bare-bones authentication. Our server and client run inside a (very secure) intranet, so we didn't care too much for the requirement to use an X.509 certificate to encrypt the communication, which is required if you're using username authentication. So we added a custom behavior to the client that adds the username and (encrypted) password to the message headers, and another custom behavior on the server that verifies them. All very simple, required no changes to the client side service access layer or the service contract implementation. And as it's all done by configuration, if and when we need to move to something a little stronger it'll be easy to migrate.
How can I authenticate using client credentials in WCF just once? What is the best approach to make sure you only need to authenticate once when using an API built on WCF? My current bindings and behaviors are listed below Next is what I am using in my client app to authenticate (currently I must do this everytime I want to make a call into WCF) Dim client As ProductServiceClient = New ProductServiceClient("wsHttpProductService") client.ClientCredentials.UserName.UserName = "foo" client.ClientCredentials.UserName.Password = "bar" Dim ProductList As List(Of Product) = client.GetProducts() What I would like to do is auth w/ the API once using these credentials, then get some type of token for the period of time my client application is using the web service project. I thought establishsecuritycontext=true did this for me?
TITLE: How can I authenticate using client credentials in WCF just once? QUESTION: What is the best approach to make sure you only need to authenticate once when using an API built on WCF? My current bindings and behaviors are listed below Next is what I am using in my client app to authenticate (currently I must do this everytime I want to make a call into WCF) Dim client As ProductServiceClient = New ProductServiceClient("wsHttpProductService") client.ClientCredentials.UserName.UserName = "foo" client.ClientCredentials.UserName.Password = "bar" Dim ProductList As List(Of Product) = client.GetProducts() What I would like to do is auth w/ the API once using these credentials, then get some type of token for the period of time my client application is using the web service project. I thought establishsecuritycontext=true did this for me? ANSWER: If you're on an intranet, Windows authentication can be handled for "free" by configuration alone. If this isn't appropriate, token services work just fine, but for some situations they may be just too much. The application I'm working on needed bare-bones authentication. Our server and client run inside a (very secure) intranet, so we didn't care too much for the requirement to use an X.509 certificate to encrypt the communication, which is required if you're using username authentication. So we added a custom behavior to the client that adds the username and (encrypted) password to the message headers, and another custom behavior on the server that verifies them. All very simple, required no changes to the client side service access layer or the service contract implementation. And as it's all done by configuration, if and when we need to move to something a little stronger it'll be easy to migrate.
[ "wcf", "security", "authentication", "ws-security" ]
1
3
18,516
2
0
2008-08-27T18:23:20.770000
2008-08-30T21:56:23.107000
30,811
31,139
Should I use Google Web Toolkit for my new webapp?
I would like to create a database backed interactive AJAX webapp which has a custom (specific kind of events, editing) calendaring system. This would involve quite a lot of JavaScript and AJAX, and I thought about Google Web Toolkit for the interface and Ruby on Rails for server side. Is Google Web Toolkit reliable and good? What hidden risks might be if I choose Google Web Toolkit? Can one easily combine it with Ruby on Rails on server side? Or should I try to use directly a JavaScript library like jQuery? I have no experience in web development except some HTML, but I am an experienced programmer (c++, java, c#), and I would like to use only free tools for this project.
RoR is actually one of the things the GWT is made to work well with, as long as you're using REST properly. It's in the Google Web Toolkit Applications book, and you can see a demo from the book using this kind of idea here. That's not to say that you won't have any problems, but I think the support is definitely out there for it. There's a neat project for making RoR/GWT easy that you can find here (MIT license). I haven't had a chance to try it out yet, but it looks like a good amount of thought has been put into it. One catch is that it looks like it hasn't been fully tested with 2.1 Rails yet, just 2.0, so you may run into a few (probably minor and fixable) errors.
Should I use Google Web Toolkit for my new webapp? I would like to create a database backed interactive AJAX webapp which has a custom (specific kind of events, editing) calendaring system. This would involve quite a lot of JavaScript and AJAX, and I thought about Google Web Toolkit for the interface and Ruby on Rails for server side. Is Google Web Toolkit reliable and good? What hidden risks might be if I choose Google Web Toolkit? Can one easily combine it with Ruby on Rails on server side? Or should I try to use directly a JavaScript library like jQuery? I have no experience in web development except some HTML, but I am an experienced programmer (c++, java, c#), and I would like to use only free tools for this project.
TITLE: Should I use Google Web Toolkit for my new webapp? QUESTION: I would like to create a database backed interactive AJAX webapp which has a custom (specific kind of events, editing) calendaring system. This would involve quite a lot of JavaScript and AJAX, and I thought about Google Web Toolkit for the interface and Ruby on Rails for server side. Is Google Web Toolkit reliable and good? What hidden risks might be if I choose Google Web Toolkit? Can one easily combine it with Ruby on Rails on server side? Or should I try to use directly a JavaScript library like jQuery? I have no experience in web development except some HTML, but I am an experienced programmer (c++, java, c#), and I would like to use only free tools for this project. ANSWER: RoR is actually one of the things the GWT is made to work well with, as long as you're using REST properly. It's in the Google Web Toolkit Applications book, and you can see a demo from the book using this kind of idea here. That's not to say that you won't have any problems, but I think the support is definitely out there for it. There's a neat project for making RoR/GWT easy that you can find here (MIT license). I haven't had a chance to try it out yet, but it looks like a good amount of thought has been put into it. One catch is that it looks like it hasn't been fully tested with 2.1 Rails yet, just 2.0, so you may run into a few (probably minor and fixable) errors.
[ "javascript", "ruby", "gwt" ]
17
12
7,864
12
0
2008-08-27T18:26:42.023000
2008-08-27T20:16:37.017000
30,833
32,011
Compile a referenced dll
Using VS2005 and VB.NET. I have a project that is an API for a data-store that I created. When compiled creates api.dll. I have a second project in the same solution that has a project reference to the API project which when compiled will create wrapper.dll. This is basically a wrapper for the API that is specific to an application. When I use wrapper.dll in that other application, I have to copy wrapper.dll and api.dll to my new application. How can I get the wrapper project to compile the api.dll into itself so that I only have one dll to move around?
@Jas, it's a special feature in Visual Studio. The procedure is outlined in this blog entry, called "Sharing a Strong Name Key File Across Projects". The example is for sharing strong name key files, but will work for any kind of file. Briefly, you right-click on your project and select "Add Existing Item". Browse to the directory of the file(s) you want to link and highlight the file or files. Insted of just hitting "Add" or "Open" (depending on your version of Visual Studio), click on the little down arrow on the right-hand side of that button. You'll see options to "Open" or "Link File" if you're using Visual Studio 2003, or "Add" or "Add as Link" with 2005 (I'm not sure about 2008). In any case, choose the one that involves the word "Link". Then your project will essentially reference the file - it will be accessible both from the original project its was in and the project you "linked" it to. This is a convenient way to create an assembly that contains all the functionality of wrapper.dll and api.dll, but you'll have to remember to repeat this procedure every time you add a new file to api.dll (but not wrapper.dll).
Compile a referenced dll Using VS2005 and VB.NET. I have a project that is an API for a data-store that I created. When compiled creates api.dll. I have a second project in the same solution that has a project reference to the API project which when compiled will create wrapper.dll. This is basically a wrapper for the API that is specific to an application. When I use wrapper.dll in that other application, I have to copy wrapper.dll and api.dll to my new application. How can I get the wrapper project to compile the api.dll into itself so that I only have one dll to move around?
TITLE: Compile a referenced dll QUESTION: Using VS2005 and VB.NET. I have a project that is an API for a data-store that I created. When compiled creates api.dll. I have a second project in the same solution that has a project reference to the API project which when compiled will create wrapper.dll. This is basically a wrapper for the API that is specific to an application. When I use wrapper.dll in that other application, I have to copy wrapper.dll and api.dll to my new application. How can I get the wrapper project to compile the api.dll into itself so that I only have one dll to move around? ANSWER: @Jas, it's a special feature in Visual Studio. The procedure is outlined in this blog entry, called "Sharing a Strong Name Key File Across Projects". The example is for sharing strong name key files, but will work for any kind of file. Briefly, you right-click on your project and select "Add Existing Item". Browse to the directory of the file(s) you want to link and highlight the file or files. Insted of just hitting "Add" or "Open" (depending on your version of Visual Studio), click on the little down arrow on the right-hand side of that button. You'll see options to "Open" or "Link File" if you're using Visual Studio 2003, or "Add" or "Add as Link" with 2005 (I'm not sure about 2008). In any case, choose the one that involves the word "Link". Then your project will essentially reference the file - it will be accessible both from the original project its was in and the project you "linked" it to. This is a convenient way to create an assembly that contains all the functionality of wrapper.dll and api.dll, but you'll have to remember to repeat this procedure every time you add a new file to api.dll (but not wrapper.dll).
[ ".net", "vb.net", "visual-studio-2005" ]
3
1
2,201
4
0
2008-08-27T18:38:31.077000
2008-08-28T10:56:44.860000
30,835
30,862
Source Versioning for Visual Studio Express
Is there any Visual Studio Express plug ins for source versioning? I am starting a project on my own and only have the Express version of Visual Studio 2008.
Short answer: No. The Express editions support neither the Add-Ins nor Source Control providers (SCC plug-ins). While there are ways to make this work, they are undocumented, violate the license and have caused legal trouble before…
Source Versioning for Visual Studio Express Is there any Visual Studio Express plug ins for source versioning? I am starting a project on my own and only have the Express version of Visual Studio 2008.
TITLE: Source Versioning for Visual Studio Express QUESTION: Is there any Visual Studio Express plug ins for source versioning? I am starting a project on my own and only have the Express version of Visual Studio 2008. ANSWER: Short answer: No. The Express editions support neither the Add-Ins nor Source Control providers (SCC plug-ins). While there are ways to make this work, they are undocumented, violate the license and have caused legal trouble before…
[ "visual-studio", "visual-studio-2008", "version-control", "plugins", "visual-studio-express" ]
15
15
22,808
10
0
2008-08-27T18:38:54.600000
2008-08-27T18:49:46.133000
30,847
30,910
How to write a regular expression pattern that is capable of validating URIs?
How does one go about authoring a Regular Expression that matches against all strings that are valid URIs, while failing to match against all strings that are invalid URIs? To be specific about what I am referencing when I say URI, I have added a link below for the most current URI RFC standard. It defines the entity that I want to validate using a regular expression. I don't need it to be able to parse the URI. I just need a regular expression for validating. The.Net Regular Expression Format is preferred. (.Net V1.1) My Current Solution: ^([a-zA-Z0-9+.-]+):(//([a-zA-Z0-9-._~!$&'()*+,;=:]*)@)?([a-zA-Z0-9-._~!$&'()*+,;=]+)(:(\\d*))?(/?[a-zA-Z0-9-._~!$&'()*+,;=:/]+)?(\\?[a-zA-Z0-9-._~!$&'()*+,;=:/?@]+)?(#[a-zA-Z0-9-._~!$&'()*+,;=:/?@]+)?$(:(\\d*))?(/?[a-zA-Z0-9-._~!$&'()*+,;=:/]+)?(\?[a-zA-Z0-9-._~!$&'()*+,;=:/?@]+)?(\#[a-zA-Z0-9-._~!$&'()*+,;=:/?@]+)?$
This site looks promising: http://snipplr.com/view/6889/regular-expressions-for-uri-validationparsing/ They propose following regex: /^([a-z0-9+.-]+):(?://(?:((?:[a-z0-9-._~!$&'()*+,;=:]|%[0-9A-F]{2})*)@)?((?:[a-z0-9-._~!$&'()*+,;=]|%[0-9A-F]{2})*)(?::(\d*))?(/(?:[a-z0-9-._~!$&'()*+,;=:@/]|%[0-9A-F]{2})*)?|(/?(?:[a-z0-9-._~!$&'()*+,;=:@]|%[0-9A-F]{2})+(?:[a-z0-9-._~!$&'()*+,;=:@/]|%[0-9A-F]{2})*)?)(?:\?((?:[a-z0-9-._~!$&'()*+,;=:/?@]|%[0-9A-F]{2})*))?(?:#((?:[a-z0-9-._~!$&'()*+,;=:/?@]|%[0-9A-F]{2})*))?$/i
How to write a regular expression pattern that is capable of validating URIs? How does one go about authoring a Regular Expression that matches against all strings that are valid URIs, while failing to match against all strings that are invalid URIs? To be specific about what I am referencing when I say URI, I have added a link below for the most current URI RFC standard. It defines the entity that I want to validate using a regular expression. I don't need it to be able to parse the URI. I just need a regular expression for validating. The.Net Regular Expression Format is preferred. (.Net V1.1) My Current Solution: ^([a-zA-Z0-9+.-]+):(//([a-zA-Z0-9-._~!$&'()*+,;=:]*)@)?([a-zA-Z0-9-._~!$&'()*+,;=]+)(:(\\d*))?(/?[a-zA-Z0-9-._~!$&'()*+,;=:/]+)?(\\?[a-zA-Z0-9-._~!$&'()*+,;=:/?@]+)?(#[a-zA-Z0-9-._~!$&'()*+,;=:/?@]+)?$(:(\\d*))?(/?[a-zA-Z0-9-._~!$&'()*+,;=:/]+)?(\?[a-zA-Z0-9-._~!$&'()*+,;=:/?@]+)?(\#[a-zA-Z0-9-._~!$&'()*+,;=:/?@]+)?$
TITLE: How to write a regular expression pattern that is capable of validating URIs? QUESTION: How does one go about authoring a Regular Expression that matches against all strings that are valid URIs, while failing to match against all strings that are invalid URIs? To be specific about what I am referencing when I say URI, I have added a link below for the most current URI RFC standard. It defines the entity that I want to validate using a regular expression. I don't need it to be able to parse the URI. I just need a regular expression for validating. The.Net Regular Expression Format is preferred. (.Net V1.1) My Current Solution: ^([a-zA-Z0-9+.-]+):(//([a-zA-Z0-9-._~!$&'()*+,;=:]*)@)?([a-zA-Z0-9-._~!$&'()*+,;=]+)(:(\\d*))?(/?[a-zA-Z0-9-._~!$&'()*+,;=:/]+)?(\\?[a-zA-Z0-9-._~!$&'()*+,;=:/?@]+)?(#[a-zA-Z0-9-._~!$&'()*+,;=:/?@]+)?$(:(\\d*))?(/?[a-zA-Z0-9-._~!$&'()*+,;=:/]+)?(\?[a-zA-Z0-9-._~!$&'()*+,;=:/?@]+)?(\#[a-zA-Z0-9-._~!$&'()*+,;=:/?@]+)?$ ANSWER: This site looks promising: http://snipplr.com/view/6889/regular-expressions-for-uri-validationparsing/ They propose following regex: /^([a-z0-9+.-]+):(?://(?:((?:[a-z0-9-._~!$&'()*+,;=:]|%[0-9A-F]{2})*)@)?((?:[a-z0-9-._~!$&'()*+,;=]|%[0-9A-F]{2})*)(?::(\d*))?(/(?:[a-z0-9-._~!$&'()*+,;=:@/]|%[0-9A-F]{2})*)?|(/?(?:[a-z0-9-._~!$&'()*+,;=:@]|%[0-9A-F]{2})+(?:[a-z0-9-._~!$&'()*+,;=:@/]|%[0-9A-F]{2})*)?)(?:\?((?:[a-z0-9-._~!$&'()*+,;=:/?@]|%[0-9A-F]{2})*))?(?:#((?:[a-z0-9-._~!$&'()*+,;=:/?@]|%[0-9A-F]{2})*))?$/i
[ ".net", "regex" ]
23
12
48,670
7
0
2008-08-27T18:43:21.237000
2008-08-27T19:03:31.327000
30,856
30,868
MySQL Results to a File
How do I write the results from a mysql query to file? I just need something quick. Output can be CSV, XML, HTML, etc.
SELECT a,b,a+b FROM test_table INTO OUTFILE '/tmp/result.txt' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n' (the docs show INTO OUTFILE up in the SELECT.. portion which may work as well, but I've never tried it that way) http://dev.mysql.com/doc/refman/5.0/en/select.html INTO OUTFILE creates a file on the server; if you are on a client and want it there, do: mysql -u you -p -e "SELECT..." > file_name
MySQL Results to a File How do I write the results from a mysql query to file? I just need something quick. Output can be CSV, XML, HTML, etc.
TITLE: MySQL Results to a File QUESTION: How do I write the results from a mysql query to file? I just need something quick. Output can be CSV, XML, HTML, etc. ANSWER: SELECT a,b,a+b FROM test_table INTO OUTFILE '/tmp/result.txt' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n' (the docs show INTO OUTFILE up in the SELECT.. portion which may work as well, but I've never tried it that way) http://dev.mysql.com/doc/refman/5.0/en/select.html INTO OUTFILE creates a file on the server; if you are on a client and want it there, do: mysql -u you -p -e "SELECT..." > file_name
[ "mysql", "database" ]
12
20
8,196
3
0
2008-08-27T18:48:04.970000
2008-08-27T18:50:42.373000
30,877
34,217
Fastest way to calculate primes in C#?
I actually have an answer to my question but it is not parallelized so I am interested in ways to improve the algorithm. Anyway it might be useful as-is for some people. int Until = 20000000; BitArray PrimeBits = new BitArray(Until, true); /* * Sieve of Eratosthenes * PrimeBits is a simple BitArray where all bit is an integer * and we mark composite numbers as false */ PrimeBits.Set(0, false); // You don't actually need this, just PrimeBits.Set(1, false); // remindig you that 2 is the smallest prime for (int P = 2; P < (int)Math.Sqrt(Until) + 1; P++) if (PrimeBits.Get(P)) // These are going to be the multiples of P if it is a prime for (int PMultiply = P * 2; PMultiply < Until; PMultiply += P) PrimeBits.Set(PMultiply, false); // We use this to store the actual prime numbers List Primes = new List (); for (int i = 2; i < Until; i++) if (PrimeBits.Get(i)) Primes.Add(i); Maybe I could use multiple BitArray s and BitArray.And() them together?
You might save some time by cross-referencing your bit array with a doubly-linked list, so you can more quickly advance to the next prime. Also, in eliminating later composites once you hit a new prime p for the first time - the first composite multiple of p remaining will be p*p, since everything before that has already been eliminated. In fact, you only need to multiply p by all the remaining potential primes that are left after it in the list, stopping as soon as your product is out of range (larger than Until). There are also some good probabilistic algorithms out there, such as the Miller-Rabin test. The wikipedia page is a good introduction.
Fastest way to calculate primes in C#? I actually have an answer to my question but it is not parallelized so I am interested in ways to improve the algorithm. Anyway it might be useful as-is for some people. int Until = 20000000; BitArray PrimeBits = new BitArray(Until, true); /* * Sieve of Eratosthenes * PrimeBits is a simple BitArray where all bit is an integer * and we mark composite numbers as false */ PrimeBits.Set(0, false); // You don't actually need this, just PrimeBits.Set(1, false); // remindig you that 2 is the smallest prime for (int P = 2; P < (int)Math.Sqrt(Until) + 1; P++) if (PrimeBits.Get(P)) // These are going to be the multiples of P if it is a prime for (int PMultiply = P * 2; PMultiply < Until; PMultiply += P) PrimeBits.Set(PMultiply, false); // We use this to store the actual prime numbers List Primes = new List (); for (int i = 2; i < Until; i++) if (PrimeBits.Get(i)) Primes.Add(i); Maybe I could use multiple BitArray s and BitArray.And() them together?
TITLE: Fastest way to calculate primes in C#? QUESTION: I actually have an answer to my question but it is not parallelized so I am interested in ways to improve the algorithm. Anyway it might be useful as-is for some people. int Until = 20000000; BitArray PrimeBits = new BitArray(Until, true); /* * Sieve of Eratosthenes * PrimeBits is a simple BitArray where all bit is an integer * and we mark composite numbers as false */ PrimeBits.Set(0, false); // You don't actually need this, just PrimeBits.Set(1, false); // remindig you that 2 is the smallest prime for (int P = 2; P < (int)Math.Sqrt(Until) + 1; P++) if (PrimeBits.Get(P)) // These are going to be the multiples of P if it is a prime for (int PMultiply = P * 2; PMultiply < Until; PMultiply += P) PrimeBits.Set(PMultiply, false); // We use this to store the actual prime numbers List Primes = new List (); for (int i = 2; i < Until; i++) if (PrimeBits.Get(i)) Primes.Add(i); Maybe I could use multiple BitArray s and BitArray.And() them together? ANSWER: You might save some time by cross-referencing your bit array with a doubly-linked list, so you can more quickly advance to the next prime. Also, in eliminating later composites once you hit a new prime p for the first time - the first composite multiple of p remaining will be p*p, since everything before that has already been eliminated. In fact, you only need to multiply p by all the remaining potential primes that are left after it in the list, stopping as soon as your product is out of range (larger than Until). There are also some good probabilistic algorithms out there, such as the Miller-Rabin test. The wikipedia page is a good introduction.
[ "c#", ".net", "performance", "algorithm", "bitarray" ]
14
8
10,857
8
0
2008-08-27T18:54:44.423000
2008-08-29T09:08:27.030000
30,879
30,887
Is there a pattern using Linq to dynamically create a filter?
Is there a pattern using Linq to dynamically create a filter? I have the need to create custom filtering on a list, in the past I would just dynamically create the SQL...it doesn't seem like this is possible with Linq.
Check out the Dynamic Linq Library from ScottGu's blog: For example, below is a standard type-safe LINQ to SQL VB query that retrieves data from a Northwind database and displays it in a ASP.NET GridView control: Dim Northwind As New NorthwindDataContext Dim query = From q In Northwind.Products Where p.CategoryID = 2 And p.UnitPrice > 3 Order By p.SupplierID Select p Gridview1.DataSource = query GridView1.DataBind() Using the LINQ DynamicQuery library I could re-write the above query expression instead like so Dim Northwind As New NorthwindDataContext Dim query = Northwind.Products.where("CategoryID=2 And UnitPrice>3"). OrderBy("SupplierId") Gridview1.DataSource = query GridView1.DataBind() Notice how the conditional-where clause and sort-orderby clause now take string expressions instead of code expressions. Because they are late-bound strings I can dynamically construct them. For example: I could provide UI to an end-user business analyst using my application that enables them to construct queries on their own (including arbitrary conditional clauses).
Is there a pattern using Linq to dynamically create a filter? Is there a pattern using Linq to dynamically create a filter? I have the need to create custom filtering on a list, in the past I would just dynamically create the SQL...it doesn't seem like this is possible with Linq.
TITLE: Is there a pattern using Linq to dynamically create a filter? QUESTION: Is there a pattern using Linq to dynamically create a filter? I have the need to create custom filtering on a list, in the past I would just dynamically create the SQL...it doesn't seem like this is possible with Linq. ANSWER: Check out the Dynamic Linq Library from ScottGu's blog: For example, below is a standard type-safe LINQ to SQL VB query that retrieves data from a Northwind database and displays it in a ASP.NET GridView control: Dim Northwind As New NorthwindDataContext Dim query = From q In Northwind.Products Where p.CategoryID = 2 And p.UnitPrice > 3 Order By p.SupplierID Select p Gridview1.DataSource = query GridView1.DataBind() Using the LINQ DynamicQuery library I could re-write the above query expression instead like so Dim Northwind As New NorthwindDataContext Dim query = Northwind.Products.where("CategoryID=2 And UnitPrice>3"). OrderBy("SupplierId") Gridview1.DataSource = query GridView1.DataBind() Notice how the conditional-where clause and sort-orderby clause now take string expressions instead of code expressions. Because they are late-bound strings I can dynamically construct them. For example: I could provide UI to an end-user business analyst using my application that enables them to construct queries on their own (including arbitrary conditional clauses).
[ "linq", "linq-to-sql", ".net-3.5" ]
21
19
16,485
4
0
2008-08-27T18:55:30.503000
2008-08-27T18:57:46.367000
30,884
375,755
What is the best way to share MasterPages across projects
Suppose you have two seperate ASP.NET Web Application projects that both need to use a common MasterPage. What's the best way to share the MasterPage across projects without having to duplicate code? Preferably without having to resort to source control or file system hacks.
I have trying to accomplish the same thing. I look into a couple of solutions but I think using a virtual directory is probably the best way to share master pages. Here are a couple sources that you can look at. Sharing Master Pages amongst Applications by Embedding it in a Dll Sharing Master Pages in Visual Studio ASP.Net 2.0 - Master Pages: Tips, Tricks, and Traps The third bullets near the end the article tells you of possible ways you can share Masterpages also.
What is the best way to share MasterPages across projects Suppose you have two seperate ASP.NET Web Application projects that both need to use a common MasterPage. What's the best way to share the MasterPage across projects without having to duplicate code? Preferably without having to resort to source control or file system hacks.
TITLE: What is the best way to share MasterPages across projects QUESTION: Suppose you have two seperate ASP.NET Web Application projects that both need to use a common MasterPage. What's the best way to share the MasterPage across projects without having to duplicate code? Preferably without having to resort to source control or file system hacks. ANSWER: I have trying to accomplish the same thing. I look into a couple of solutions but I think using a virtual directory is probably the best way to share master pages. Here are a couple sources that you can look at. Sharing Master Pages amongst Applications by Embedding it in a Dll Sharing Master Pages in Visual Studio ASP.Net 2.0 - Master Pages: Tips, Tricks, and Traps The third bullets near the end the article tells you of possible ways you can share Masterpages also.
[ ".net", "asp.net", "master-pages" ]
24
11
17,057
7
0
2008-08-27T18:57:17.833000
2008-12-17T19:36:53.040000
30,903
909,952
Good Mercurial repository viewer for Mac
Is there a good, native Mac tool to view Mercurial repositories, similar to gitnub for Git?
I know it's pretty old question, however just for sake of completeness, I think it is still worth to mention here the newest kid on the block called Murky.
Good Mercurial repository viewer for Mac Is there a good, native Mac tool to view Mercurial repositories, similar to gitnub for Git?
TITLE: Good Mercurial repository viewer for Mac QUESTION: Is there a good, native Mac tool to view Mercurial repositories, similar to gitnub for Git? ANSWER: I know it's pretty old question, however just for sake of completeness, I think it is still worth to mention here the newest kid on the block called Murky.
[ "macos", "version-control", "mercurial", "dvcs" ]
34
16
11,406
6
0
2008-08-27T19:00:34.610000
2009-05-26T10:15:53.910000
30,931
31,836
Register file extensions / mime types in Linux
I'm developing a Linux application that has its own file format. I want my app to open when you double-click on those files. How can I register a file extension and associate it with my application on Linux? I'm looking for a way that is standard (works with GNOME and KDE based systems) and can be done automatic when my program is installed or run for the first time.
Use xdg-utils from freedesktop.org Portland. Register the icon for the MIME type: xdg-icon-resource install --context mimetypes --size 48 myicon-file-type.png x-application-mytype Create a configuration file ( freedesktop Shared MIME documentation ): A witty comment Uno Commento Install the configuration file: xdg-mime install mytype-mime.xml This gets your files recognized and associated with an icon. xdg-mime default can be used for associating an application with the MIME type after you get a.desktop file installed.
Register file extensions / mime types in Linux I'm developing a Linux application that has its own file format. I want my app to open when you double-click on those files. How can I register a file extension and associate it with my application on Linux? I'm looking for a way that is standard (works with GNOME and KDE based systems) and can be done automatic when my program is installed or run for the first time.
TITLE: Register file extensions / mime types in Linux QUESTION: I'm developing a Linux application that has its own file format. I want my app to open when you double-click on those files. How can I register a file extension and associate it with my application on Linux? I'm looking for a way that is standard (works with GNOME and KDE based systems) and can be done automatic when my program is installed or run for the first time. ANSWER: Use xdg-utils from freedesktop.org Portland. Register the icon for the MIME type: xdg-icon-resource install --context mimetypes --size 48 myicon-file-type.png x-application-mytype Create a configuration file ( freedesktop Shared MIME documentation ): A witty comment Uno Commento Install the configuration file: xdg-mime install mytype-mime.xml This gets your files recognized and associated with an icon. xdg-mime default can be used for associating an application with the MIME type after you get a.desktop file installed.
[ "linux", "installation", "mime", "file-type" ]
61
56
36,660
5
0
2008-08-27T19:12:36.830000
2008-08-28T08:18:00.263000
30,946
30,979
Simple password encryption
What is a good, simple encryption scheme for protecting passwords in a database? I don't necessarily need anything that's hyper-secure nor do I need anything that's lightning fast, but those things would be nice. Primarily, I just want something that's easy to implement without being terribly slow or insecure.
As mk says, SHA1 or MD5 are the standard ones, along with SHA2. Update: As processors have gotten faster over the years, hashes have gotten more brute-forceable. It's now recommended you use bcrypt. Another update: bcrypt is still probably good, but if I was writing a new system today I would use scrypt. What you want is more generally called a cryptographic hash function. Cryptographic hashes are designed to be one-way (given the resulting hash, you shouldn't be able to derive the original input). Also, the likelihood of two arbitrary strings having the same hash (known as a hash collision) should be low (ideally 1/number of hash values). Unfortunately, just because your passwords are hashed doesn't free you from having to try really hard to keep the hashed versions safe. Far too many people will use weak passwords that would be vulnerable to an off-line brute-force attack. Edit - several people have also already pointed out the importance of using a salt. A salt is a constant value that you mix in with the input before using the hash function. Having a unique salt prevents off-line attackers from using pre-computed tables of common passwords (rainbow tables) to brute-force your passwords even faster.
Simple password encryption What is a good, simple encryption scheme for protecting passwords in a database? I don't necessarily need anything that's hyper-secure nor do I need anything that's lightning fast, but those things would be nice. Primarily, I just want something that's easy to implement without being terribly slow or insecure.
TITLE: Simple password encryption QUESTION: What is a good, simple encryption scheme for protecting passwords in a database? I don't necessarily need anything that's hyper-secure nor do I need anything that's lightning fast, but those things would be nice. Primarily, I just want something that's easy to implement without being terribly slow or insecure. ANSWER: As mk says, SHA1 or MD5 are the standard ones, along with SHA2. Update: As processors have gotten faster over the years, hashes have gotten more brute-forceable. It's now recommended you use bcrypt. Another update: bcrypt is still probably good, but if I was writing a new system today I would use scrypt. What you want is more generally called a cryptographic hash function. Cryptographic hashes are designed to be one-way (given the resulting hash, you shouldn't be able to derive the original input). Also, the likelihood of two arbitrary strings having the same hash (known as a hash collision) should be low (ideally 1/number of hash values). Unfortunately, just because your passwords are hashed doesn't free you from having to try really hard to keep the hashed versions safe. Far too many people will use weak passwords that would be vulnerable to an off-line brute-force attack. Edit - several people have also already pointed out the importance of using a salt. A salt is a constant value that you mix in with the input before using the hash function. Having a unique salt prevents off-line attackers from using pre-computed tables of common passwords (rainbow tables) to brute-force your passwords even faster.
[ "database", "language-agnostic", "passwords" ]
18
15
11,461
11
0
2008-08-27T19:17:47.127000
2008-08-27T19:29:03.060000
30,947
102,168
Visual Studio 08 Spell Check Addin?
If possible one that supports at least spell checking: C# string literals HTML content Comments
Well, 3 weeks later, I've stumbled across CodeSpell. [ Note: this link no longer works and the product does not appear to be listed by that company). Its $30 but has a trial period. Does everything I asked for. Check link to see features. This blog entry, though dated, helped me out. Edit: The original link is now invalid but this appears to be the new home of CodeSpell at SubMain. Here is acquisition announcement from them.
Visual Studio 08 Spell Check Addin? If possible one that supports at least spell checking: C# string literals HTML content Comments
TITLE: Visual Studio 08 Spell Check Addin? QUESTION: If possible one that supports at least spell checking: C# string literals HTML content Comments ANSWER: Well, 3 weeks later, I've stumbled across CodeSpell. [ Note: this link no longer works and the product does not appear to be listed by that company). Its $30 but has a trial period. Does everything I asked for. Check link to see features. This blog entry, though dated, helped me out. Edit: The original link is now invalid but this appears to be the new home of CodeSpell at SubMain. Here is acquisition announcement from them.
[ "visual-studio", "visual-studio-2008", "add-in" ]
33
5
6,968
10
0
2008-08-27T19:17:55.757000
2008-09-19T14:16:50.503000
30,962
30,965
Finding City and Zip Code for a Location
Given a latitude and longitude, what is the easiest way to find the name of the city and the US zip code of that location. (This is similar to https://stackoverflow.com/questions/23572/latitude-longitude-database, except I want to convert in the opposite direction.) Related question: Get street address at lat/long pair
This is the web service to call. http://developer.yahoo.com/search/local/V2/localSearch.html This site has ok web services, but not exactly what you're asking for here. http://www.usps.com/webtools/
Finding City and Zip Code for a Location Given a latitude and longitude, what is the easiest way to find the name of the city and the US zip code of that location. (This is similar to https://stackoverflow.com/questions/23572/latitude-longitude-database, except I want to convert in the opposite direction.) Related question: Get street address at lat/long pair
TITLE: Finding City and Zip Code for a Location QUESTION: Given a latitude and longitude, what is the easiest way to find the name of the city and the US zip code of that location. (This is similar to https://stackoverflow.com/questions/23572/latitude-longitude-database, except I want to convert in the opposite direction.) Related question: Get street address at lat/long pair ANSWER: This is the web service to call. http://developer.yahoo.com/search/local/V2/localSearch.html This site has ok web services, but not exactly what you're asking for here. http://www.usps.com/webtools/
[ "mapping", "maps", "gis", "location", "geocoding" ]
5
2
8,117
8
0
2008-08-27T19:24:18.203000
2008-08-27T19:25:10.713000
30,964
30,992
Limiting traffic to SSL version of page only
We have an external service that is currently accessible via the http (port 80, non-SSL) and https (port 443, SSL) addresses. What is the best way to limit connections to only the https address? Is it something we can do via IIS or does it have to be done via code. Additional info: Regular ASP.NET web service (.asmx) running on IIS on Windows 2003 server. Service is built with C# on.NET 3.5.
Just to clarify Greg's point 1. IIS Manager > Site properties > Directory Security > Secure Communications > Require Secure Channel (SSL)
Limiting traffic to SSL version of page only We have an external service that is currently accessible via the http (port 80, non-SSL) and https (port 443, SSL) addresses. What is the best way to limit connections to only the https address? Is it something we can do via IIS or does it have to be done via code. Additional info: Regular ASP.NET web service (.asmx) running on IIS on Windows 2003 server. Service is built with C# on.NET 3.5.
TITLE: Limiting traffic to SSL version of page only QUESTION: We have an external service that is currently accessible via the http (port 80, non-SSL) and https (port 443, SSL) addresses. What is the best way to limit connections to only the https address? Is it something we can do via IIS or does it have to be done via code. Additional info: Regular ASP.NET web service (.asmx) running on IIS on Windows 2003 server. Service is built with C# on.NET 3.5. ANSWER: Just to clarify Greg's point 1. IIS Manager > Site properties > Directory Security > Secure Communications > Require Secure Channel (SSL)
[ "web-services", "iis", "ssl" ]
4
3
852
3
0
2008-08-27T19:25:10.510000
2008-08-27T19:34:52.220000
30,966
30,988
InputManager on OS X
I was wondering if InputManagers are still part of Leopard and if there is a good example that would show me what are the use of it?
InputManagers are still available on Leopard, except: they need to be in the Local domain ( /Library/InputManagers ); you cannot install them per-user any more, they need to have appropriate privileges, in 64-bit, they won't get loaded at all. The Leopard AppKit Release Notes have more specific details.
InputManager on OS X I was wondering if InputManagers are still part of Leopard and if there is a good example that would show me what are the use of it?
TITLE: InputManager on OS X QUESTION: I was wondering if InputManagers are still part of Leopard and if there is a good example that would show me what are the use of it? ANSWER: InputManagers are still available on Leopard, except: they need to be in the Local domain ( /Library/InputManagers ); you cannot install them per-user any more, they need to have appropriate privileges, in 64-bit, they won't get loaded at all. The Leopard AppKit Release Notes have more specific details.
[ "macos", "cocoa" ]
3
4
841
1
0
2008-08-27T19:25:21.323000
2008-08-27T19:32:41.397000
30,972
36,501
Is there anything similar to the OS X InputManager on Windows?
Is there anything similar on Windows what would achieve the same as the InputManager on OS X?
If you are looking to inject code into processes (which is what Input Managers are most commonly used for), the Windows equivalents are: AppInit_DLLs to automatically load your DLL into new processes, CreateRemoteThread to start a new thread in a particular existing process, and SetWindowsHookEx to allow the capture of window events (keyboard, mouse, window creating, drawing, etc). All of these methods require a DLL which will be injected into the remote process. C would be the best language to write such a DLL in as such a DLL needs to be quite light weight as to not bog the system down. RPC methods such as named pipes can be used to communicate to a master process should this be required. Googling for these three APIs will turn up general sample code for these methods.
Is there anything similar to the OS X InputManager on Windows? Is there anything similar on Windows what would achieve the same as the InputManager on OS X?
TITLE: Is there anything similar to the OS X InputManager on Windows? QUESTION: Is there anything similar on Windows what would achieve the same as the InputManager on OS X? ANSWER: If you are looking to inject code into processes (which is what Input Managers are most commonly used for), the Windows equivalents are: AppInit_DLLs to automatically load your DLL into new processes, CreateRemoteThread to start a new thread in a particular existing process, and SetWindowsHookEx to allow the capture of window events (keyboard, mouse, window creating, drawing, etc). All of these methods require a DLL which will be injected into the remote process. C would be the best language to write such a DLL in as such a DLL needs to be quite light weight as to not bog the system down. RPC methods such as named pipes can be used to communicate to a master process should this be required. Googling for these three APIs will turn up general sample code for these methods.
[ "windows", "macos", "winapi" ]
1
1
401
2
0
2008-08-27T19:26:47.887000
2008-08-31T00:15:43.770000
30,995
34,245
"File Save Failed" error when working with Crystal Reports in VS2008
Occasionally while attempting to save a Crystal Report that I'm working on in VS2008, a dialog titled "File Save Failed" pops up saying "The document could not be saved in C:\Users\Phillip\AppData\Local\Temp{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}.rpt. It has been saved in C:\Users\Phillip\AppData\Local\Temp\~zzz{YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY}.tmp." If I OK the dialog, I get a "Save File As" dialog. If I specify the correct location of the report file, I'm asked if I want to replace the existing file. If I say "Yes", I get an error message saying "The operation could not be completed. The system cannot find the file specified." Even if I specify a completely different filename, in a different folder (e.g. C:/test.rpt) I get the same "operation could not be completed" error. Sometimes if I wait a moment, then try to save again, it works fine. More frequently, however, I keep getting the "Save File As" dialog. My only option then is to close the report and discard my changes. This is an intermittent problem - much of the time, saving the report works just fine. Any ideas?
Copernic Desktop Search sometimes locks files so that they can't be written. Closing the program resolves the problem. Perhaps the same problem occurs with other search engines too.
"File Save Failed" error when working with Crystal Reports in VS2008 Occasionally while attempting to save a Crystal Report that I'm working on in VS2008, a dialog titled "File Save Failed" pops up saying "The document could not be saved in C:\Users\Phillip\AppData\Local\Temp{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}.rpt. It has been saved in C:\Users\Phillip\AppData\Local\Temp\~zzz{YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY}.tmp." If I OK the dialog, I get a "Save File As" dialog. If I specify the correct location of the report file, I'm asked if I want to replace the existing file. If I say "Yes", I get an error message saying "The operation could not be completed. The system cannot find the file specified." Even if I specify a completely different filename, in a different folder (e.g. C:/test.rpt) I get the same "operation could not be completed" error. Sometimes if I wait a moment, then try to save again, it works fine. More frequently, however, I keep getting the "Save File As" dialog. My only option then is to close the report and discard my changes. This is an intermittent problem - much of the time, saving the report works just fine. Any ideas?
TITLE: "File Save Failed" error when working with Crystal Reports in VS2008 QUESTION: Occasionally while attempting to save a Crystal Report that I'm working on in VS2008, a dialog titled "File Save Failed" pops up saying "The document could not be saved in C:\Users\Phillip\AppData\Local\Temp{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}.rpt. It has been saved in C:\Users\Phillip\AppData\Local\Temp\~zzz{YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY}.tmp." If I OK the dialog, I get a "Save File As" dialog. If I specify the correct location of the report file, I'm asked if I want to replace the existing file. If I say "Yes", I get an error message saying "The operation could not be completed. The system cannot find the file specified." Even if I specify a completely different filename, in a different folder (e.g. C:/test.rpt) I get the same "operation could not be completed" error. Sometimes if I wait a moment, then try to save again, it works fine. More frequently, however, I keep getting the "Save File As" dialog. My only option then is to close the report and discard my changes. This is an intermittent problem - much of the time, saving the report works just fine. Any ideas? ANSWER: Copernic Desktop Search sometimes locks files so that they can't be written. Closing the program resolves the problem. Perhaps the same problem occurs with other search engines too.
[ "vb.net", "visual-studio-2008", "crystal-reports" ]
1
1
4,780
3
0
2008-08-27T19:35:40.940000
2008-08-29T09:24:24.480000
30,998
31,111
Is using too much static bad or good?
I like to use static functions in C++ as a way to categorize them, like C# does. Console::WriteLine("hello") Is this good or bad? If the functions are used often I guess it doesn't matter, but if not do they put pressure on memory? What about static const?
but is it good or bad The first adjective that comes to mind is "unnecessary". C++ has free functions and namespaces, so why would you need to make them static functions in a class? The use of static methods in uninstantiable classes in C# and Java is a workaround because those languages don't have free functions (that is, functions that reside directly in the namespace, rather than as part of a class). C++ doesn't have that flaw. Just use a namespace.
Is using too much static bad or good? I like to use static functions in C++ as a way to categorize them, like C# does. Console::WriteLine("hello") Is this good or bad? If the functions are used often I guess it doesn't matter, but if not do they put pressure on memory? What about static const?
TITLE: Is using too much static bad or good? QUESTION: I like to use static functions in C++ as a way to categorize them, like C# does. Console::WriteLine("hello") Is this good or bad? If the functions are used often I guess it doesn't matter, but if not do they put pressure on memory? What about static const? ANSWER: but is it good or bad The first adjective that comes to mind is "unnecessary". C++ has free functions and namespaces, so why would you need to make them static functions in a class? The use of static methods in uninstantiable classes in C# and Java is a workaround because those languages don't have free functions (that is, functions that reside directly in the namespace, rather than as part of a class). C++ doesn't have that flaw. Just use a namespace.
[ "c++", "static" ]
12
28
7,355
10
0
2008-08-27T19:36:18.847000
2008-08-27T20:10:38.233000
31,007
31,027
Pass reference to element in C# Array
I build up an array of strings with string[] parts = string.spilt(" "); And get an array with X parts in it, I would like to get a copy of the array of strings starting at element parts[x-2] Other than the obvious brute force approach (make a new array and insert strings), is there a more elegant way to do this in C#?
How about Array.Copy? http://msdn.microsoft.com/en-us/library/aa310864(VS.71).aspx Array.Copy Method (Array, Int32, Array, Int32, Int32) Copies a range of elements from an Array starting at the specified source index and pastes them to another Array starting at the specified destination index. The length and the indexes are specified as 32-bit integers.
Pass reference to element in C# Array I build up an array of strings with string[] parts = string.spilt(" "); And get an array with X parts in it, I would like to get a copy of the array of strings starting at element parts[x-2] Other than the obvious brute force approach (make a new array and insert strings), is there a more elegant way to do this in C#?
TITLE: Pass reference to element in C# Array QUESTION: I build up an array of strings with string[] parts = string.spilt(" "); And get an array with X parts in it, I would like to get a copy of the array of strings starting at element parts[x-2] Other than the obvious brute force approach (make a new array and insert strings), is there a more elegant way to do this in C#? ANSWER: How about Array.Copy? http://msdn.microsoft.com/en-us/library/aa310864(VS.71).aspx Array.Copy Method (Array, Int32, Array, Int32, Int32) Copies a range of elements from an Array starting at the specified source index and pastes them to another Array starting at the specified destination index. The length and the indexes are specified as 32-bit integers.
[ "c#", "arrays" ]
6
2
4,348
5
0
2008-08-27T19:39:07.887000
2008-08-27T19:43:36.740000
31,031
31,036
What's the best way to allow a user to browse for a file in C#?
What's the best way to allow a user to browse for a file in C#?
using (OpenFileDialog dlg = new OpenFileDialog()) { dlg.Title = "Select a file"; if (dlg.ShowDialog()== DialogResult.OK) { //do something with dlg.FileName } }
What's the best way to allow a user to browse for a file in C#? What's the best way to allow a user to browse for a file in C#?
TITLE: What's the best way to allow a user to browse for a file in C#? QUESTION: What's the best way to allow a user to browse for a file in C#? ANSWER: using (OpenFileDialog dlg = new OpenFileDialog()) { dlg.Title = "Select a file"; if (dlg.ShowDialog()== DialogResult.OK) { //do something with dlg.FileName } }
[ "c#" ]
6
16
322
3
0
2008-08-27T19:45:34.673000
2008-08-27T19:46:54.483000
31,044
587,408
Is there an "exists" function for jQuery?
How can I check the existence of an element in jQuery? The current code that I have is this: if ($(selector).length > 0) { // Do something } Is there a more elegant way to approach this? Perhaps a plugin or a function?
In JavaScript, everything is 'truthy' or 'falsy', and for numbers 0 means false, everything else true. So you could write: if ($(selector).length) You don't need that >0 part.
Is there an "exists" function for jQuery? How can I check the existence of an element in jQuery? The current code that I have is this: if ($(selector).length > 0) { // Do something } Is there a more elegant way to approach this? Perhaps a plugin or a function?
TITLE: Is there an "exists" function for jQuery? QUESTION: How can I check the existence of an element in jQuery? The current code that I have is this: if ($(selector).length > 0) { // Do something } Is there a more elegant way to approach this? Perhaps a plugin or a function? ANSWER: In JavaScript, everything is 'truthy' or 'falsy', and for numbers 0 means false, everything else true. So you could write: if ($(selector).length) You don't need that >0 part.
[ "javascript", "jquery" ]
3,142
2,763
865,330
17
0
2008-08-27T19:49:41.107000
2009-02-25T19:16:21.610000
31,051
31,300
Setting up replicated repositories in Plastic SCM
So we're trying to set up replicated repositories using PlasticSCM, one in the US, and one in Australia and running into a bit of a snag. The US configuration is Active Directory, the AU configuration is User/Password. This in itself is not a big deal, I've already set up the SID translation table. The problem is with plasticscm's replicate command itself. This is the command which should replicate from the US to AU, run ON the AU server. cm replicate br:/main@rep:default@repserver:US:8084 rep:myrep@repserver:AU:9090 --trmode=name --trtable=trans.txt --authdata=ActiveDirectory:192.168.1.3:389:john.doe@factory.com:fPBea2rPsQaagEW3pKNveA==:dc=factory,dc=com The part I'm stuck at is the authdata part (the above is an EXAMPLE only). How can I generate the obscured password? I think it's the only thing preventing these two repositories from talking to each other.
Ok, I've solved my own problem. To get that "authdata" string, you need to configure your client to how you need to authenticate. Then navigate to c:[users directory][username]\Local Settings\Application Data\plastic. Pick up the client.conf and extract the string from the SecurityConfig element in the XML.
Setting up replicated repositories in Plastic SCM So we're trying to set up replicated repositories using PlasticSCM, one in the US, and one in Australia and running into a bit of a snag. The US configuration is Active Directory, the AU configuration is User/Password. This in itself is not a big deal, I've already set up the SID translation table. The problem is with plasticscm's replicate command itself. This is the command which should replicate from the US to AU, run ON the AU server. cm replicate br:/main@rep:default@repserver:US:8084 rep:myrep@repserver:AU:9090 --trmode=name --trtable=trans.txt --authdata=ActiveDirectory:192.168.1.3:389:john.doe@factory.com:fPBea2rPsQaagEW3pKNveA==:dc=factory,dc=com The part I'm stuck at is the authdata part (the above is an EXAMPLE only). How can I generate the obscured password? I think it's the only thing preventing these two repositories from talking to each other.
TITLE: Setting up replicated repositories in Plastic SCM QUESTION: So we're trying to set up replicated repositories using PlasticSCM, one in the US, and one in Australia and running into a bit of a snag. The US configuration is Active Directory, the AU configuration is User/Password. This in itself is not a big deal, I've already set up the SID translation table. The problem is with plasticscm's replicate command itself. This is the command which should replicate from the US to AU, run ON the AU server. cm replicate br:/main@rep:default@repserver:US:8084 rep:myrep@repserver:AU:9090 --trmode=name --trtable=trans.txt --authdata=ActiveDirectory:192.168.1.3:389:john.doe@factory.com:fPBea2rPsQaagEW3pKNveA==:dc=factory,dc=com The part I'm stuck at is the authdata part (the above is an EXAMPLE only). How can I generate the obscured password? I think it's the only thing preventing these two repositories from talking to each other. ANSWER: Ok, I've solved my own problem. To get that "authdata" string, you need to configure your client to how you need to authenticate. Then navigate to c:[users directory][username]\Local Settings\Application Data\plastic. Pick up the client.conf and extract the string from the SecurityConfig element in the XML.
[ "version-control", "repository", "plasticscm" ]
3
1
565
2
0
2008-08-27T19:51:09.420000
2008-08-27T21:09:27.173000
31,053
31,056
Regex (C#): Replace \n with \r\n
How can I replace lone instances of \n with \r\n (LF alone with CRLF) using a regular expression in C#? I know to do it using plan String.Replace, like: myStr.Replace("\n", "\r\n"); myStr.Replace("\r\r\n", "\r\n"); However, this is inelegant, and would destroy any "\r+\r\n" already in the text (although they are not likely to exist).
Will this do? [^\r]\n Basically it matches a '\n' that is preceded with a character that is not '\r'. If you want it to detect lines that start with just a single '\n' as well, then try ([^\r]|$)\n Which says that it should match a '\n' but only those that is the first character of a line or those that are not preceded with '\r' There might be special cases to check since you're messing with the definition of lines itself the '$' might not work too well. But I think you should get the idea. EDIT: credit @Kibbee Using look-ahead s is clearly better since it won't capture the matched preceding character and should help with any edge cases as well. So here's a better regex + the code becomes: myStr = Regex.Replace(myStr, "(?
Regex (C#): Replace \n with \r\n How can I replace lone instances of \n with \r\n (LF alone with CRLF) using a regular expression in C#? I know to do it using plan String.Replace, like: myStr.Replace("\n", "\r\n"); myStr.Replace("\r\r\n", "\r\n"); However, this is inelegant, and would destroy any "\r+\r\n" already in the text (although they are not likely to exist).
TITLE: Regex (C#): Replace \n with \r\n QUESTION: How can I replace lone instances of \n with \r\n (LF alone with CRLF) using a regular expression in C#? I know to do it using plan String.Replace, like: myStr.Replace("\n", "\r\n"); myStr.Replace("\r\r\n", "\r\n"); However, this is inelegant, and would destroy any "\r+\r\n" already in the text (although they are not likely to exist). ANSWER: Will this do? [^\r]\n Basically it matches a '\n' that is preceded with a character that is not '\r'. If you want it to detect lines that start with just a single '\n' as well, then try ([^\r]|$)\n Which says that it should match a '\n' but only those that is the first character of a line or those that are not preceded with '\r' There might be special cases to check since you're messing with the definition of lines itself the '$' might not work too well. But I think you should get the idea. EDIT: credit @Kibbee Using look-ahead s is clearly better since it won't capture the matched preceding character and should help with any edge cases as well. So here's a better regex + the code becomes: myStr = Regex.Replace(myStr, "(?
[ "c#", "regex" ]
44
46
81,818
7
0
2008-08-27T19:51:30.730000
2008-08-27T19:52:19.043000
31,057
31,063
How to insert a line break in a SQL Server VARCHAR/NVARCHAR string
I didn't see any similar questions asked on this topic, and I had to research this for something I'm working on right now. Thought I would post the answer for it in case anyone else had the same question.
I found the answer here: http://blog.sqlauthority.com/2007/08/22/sql-server-t-sql-script-to-insert-carriage-return-and-new-line-feed-in-code/ You just concatenate the string and insert a CHAR(13) where you want your line break. Example: DECLARE @text NVARCHAR(100) SET @text = 'This is line 1.' + CHAR(13) + 'This is line 2.' SELECT @text This prints out the following: This is line 1. This is line 2.
How to insert a line break in a SQL Server VARCHAR/NVARCHAR string I didn't see any similar questions asked on this topic, and I had to research this for something I'm working on right now. Thought I would post the answer for it in case anyone else had the same question.
TITLE: How to insert a line break in a SQL Server VARCHAR/NVARCHAR string QUESTION: I didn't see any similar questions asked on this topic, and I had to research this for something I'm working on right now. Thought I would post the answer for it in case anyone else had the same question. ANSWER: I found the answer here: http://blog.sqlauthority.com/2007/08/22/sql-server-t-sql-script-to-insert-carriage-return-and-new-line-feed-in-code/ You just concatenate the string and insert a CHAR(13) where you want your line break. Example: DECLARE @text NVARCHAR(100) SET @text = 'This is line 1.' + CHAR(13) + 'This is line 2.' SELECT @text This prints out the following: This is line 1. This is line 2.
[ "sql", "sql-server", "line-breaks" ]
697
344
1,458,332
11
0
2008-08-27T19:53:01.303000
2008-08-27T19:55:42.467000
31,059
514,368
How do you configure an OpenFileDialog to select folders?
In VS.NET, when you are selecting a folder for a project, a dialog that looks like an OpenFileDialog or SaveFileDialog is displayed, but is set up to accept only folders. Ever since I've seen this I've wanted to know how it's done. I am aware of the FolderBrowserDialog, but I've never really liked that dialog. It starts too small and doesn't let me take advantage of being able to type a path. I'm almost certain by now there's not a way to do this from.NET, but I'm just as curious how you do it from unmanaged code as well. Short of completely reimplementing the dialog from scratch, how do you modify the dialog to have this behavior? I'd also like to restate that I am aware of the FolderBrowserDialog but sometimes I don't like to use it, in addition to being genuinely curious how to configure a dialog in this manner. Telling me to just use the FolderBrowserDialog helps me maintain a consistent UI experience but doesn't satisfy my curiosity so it won't count as an answer. It's not a Vista-specific thing either; I've been seeing this dialog since VS.NET 2003, so it is doable in Win2k and WinXP. This is less of a "I want to know the proper way to do this" question and more of a "I have been curious about this since I first wanted to do it in VS 2003" question. I understand that Vista's file dialog has an option to do this, but it's been working in XP so I know they did something to get it to work. Vista-specific answers are not answers, because Vista doesn't exist in the question context. Update: I'm accepting Scott Wisniewski's answer because it comes with a working sample, but I think Serge deserves credit for pointing to the dialog customization (which is admittedly nasty from.NET but it does work) and Mark Ransom for figuring out that MS probably rolled a custom dialog for this task.
I have a dialog that I wrote called an OpenFileOrFolder dialog that allows you to open either a folder or a file. If you set its AcceptFiles value to false, then it operates in only accept folder mode. You can download the source from GitHub here
How do you configure an OpenFileDialog to select folders? In VS.NET, when you are selecting a folder for a project, a dialog that looks like an OpenFileDialog or SaveFileDialog is displayed, but is set up to accept only folders. Ever since I've seen this I've wanted to know how it's done. I am aware of the FolderBrowserDialog, but I've never really liked that dialog. It starts too small and doesn't let me take advantage of being able to type a path. I'm almost certain by now there's not a way to do this from.NET, but I'm just as curious how you do it from unmanaged code as well. Short of completely reimplementing the dialog from scratch, how do you modify the dialog to have this behavior? I'd also like to restate that I am aware of the FolderBrowserDialog but sometimes I don't like to use it, in addition to being genuinely curious how to configure a dialog in this manner. Telling me to just use the FolderBrowserDialog helps me maintain a consistent UI experience but doesn't satisfy my curiosity so it won't count as an answer. It's not a Vista-specific thing either; I've been seeing this dialog since VS.NET 2003, so it is doable in Win2k and WinXP. This is less of a "I want to know the proper way to do this" question and more of a "I have been curious about this since I first wanted to do it in VS 2003" question. I understand that Vista's file dialog has an option to do this, but it's been working in XP so I know they did something to get it to work. Vista-specific answers are not answers, because Vista doesn't exist in the question context. Update: I'm accepting Scott Wisniewski's answer because it comes with a working sample, but I think Serge deserves credit for pointing to the dialog customization (which is admittedly nasty from.NET but it does work) and Mark Ransom for figuring out that MS probably rolled a custom dialog for this task.
TITLE: How do you configure an OpenFileDialog to select folders? QUESTION: In VS.NET, when you are selecting a folder for a project, a dialog that looks like an OpenFileDialog or SaveFileDialog is displayed, but is set up to accept only folders. Ever since I've seen this I've wanted to know how it's done. I am aware of the FolderBrowserDialog, but I've never really liked that dialog. It starts too small and doesn't let me take advantage of being able to type a path. I'm almost certain by now there's not a way to do this from.NET, but I'm just as curious how you do it from unmanaged code as well. Short of completely reimplementing the dialog from scratch, how do you modify the dialog to have this behavior? I'd also like to restate that I am aware of the FolderBrowserDialog but sometimes I don't like to use it, in addition to being genuinely curious how to configure a dialog in this manner. Telling me to just use the FolderBrowserDialog helps me maintain a consistent UI experience but doesn't satisfy my curiosity so it won't count as an answer. It's not a Vista-specific thing either; I've been seeing this dialog since VS.NET 2003, so it is doable in Win2k and WinXP. This is less of a "I want to know the proper way to do this" question and more of a "I have been curious about this since I first wanted to do it in VS 2003" question. I understand that Vista's file dialog has an option to do this, but it's been working in XP so I know they did something to get it to work. Vista-specific answers are not answers, because Vista doesn't exist in the question context. Update: I'm accepting Scott Wisniewski's answer because it comes with a working sample, but I think Serge deserves credit for pointing to the dialog customization (which is admittedly nasty from.NET but it does work) and Mark Ransom for figuring out that MS probably rolled a custom dialog for this task. ANSWER: I have a dialog that I wrote called an OpenFileOrFolder dialog that allows you to open either a folder or a file. If you set its AcceptFiles value to false, then it operates in only accept folder mode. You can download the source from GitHub here
[ ".net", "windows", "winapi", "openfiledialog" ]
264
62
251,486
17
0
2008-08-27T19:54:16.713000
2009-02-05T02:58:25.693000
31,077
1,781,042
How do I display a PDF in Adobe Flex?
Looking for a way to display a PDF in Flex. I'm sure there are several ways. Looking for the easiest to maintain / integrate / most user friendly. I'm guessing it's possible to display a browser window in the app and render it, but if it goes off of IE / FireFox it's not acceptable for this project. Thanks...
This looks like a nice PDF viewer for flex http://www.devaldi.com/?p=212
How do I display a PDF in Adobe Flex? Looking for a way to display a PDF in Flex. I'm sure there are several ways. Looking for the easiest to maintain / integrate / most user friendly. I'm guessing it's possible to display a browser window in the app and render it, but if it goes off of IE / FireFox it's not acceptable for this project. Thanks...
TITLE: How do I display a PDF in Adobe Flex? QUESTION: Looking for a way to display a PDF in Flex. I'm sure there are several ways. Looking for the easiest to maintain / integrate / most user friendly. I'm guessing it's possible to display a browser window in the app and render it, but if it goes off of IE / FireFox it's not acceptable for this project. Thanks... ANSWER: This looks like a nice PDF viewer for flex http://www.devaldi.com/?p=212
[ "apache-flex", "pdf", "adobe" ]
8
5
31,594
8
0
2008-08-27T19:58:50.337000
2009-11-23T04:03:11.870000
31,088
31,110
What is the best way to inherit an array that needs to store subclass specific data?
I'm trying to set up an inheritance hierarchy similar to the following: abstract class Vehicle { public string Name; public List Axles; } class Motorcycle: Vehicle { } class Car: Vehicle { } abstract class Axle { public int Length; public void Turn(int numTurns) {... } } class MotorcycleAxle: Axle { public bool WheelAttached; } class CarAxle: Axle { public bool LeftWheelAttached; public bool RightWheelAttached; } I would like to only store MotorcycleAxle objects in a Motorcycle object's Axles array, and CarAxle objects in a Car object's Axles array. The problem is there is no way to override the array in the subclass to force one or the other. Ideally something like the following would be valid for the Motorcycle class: class Motorcycle: Vehicle { public override List Axles; } but the types have to match when overriding. How can I support this architecture? Will I just have to do a lot of run-time type checking and casting wherever the Axles member is accessed? I don't like adding run-time type checks because you start to lose the benefits of strong typing and polymorphism. There have to be at least some run-time checks in this scenario since the WheelAttached and Left/RightWheelAttached properties depend on the type, but I would like to minimize them.
Use more generics abstract class Vehicle where T: Axle { public string Name; public List Axles; } class Motorcycle: Vehicle { } class Car: Vehicle { } abstract class Axle { public int Length; public void Turn(int numTurns) {... } } class MotorcycleAxle: Axle { public bool WheelAttached; } class CarAxle: Axle { public bool LeftWheelAttached; public bool RightWheelAttached; }
What is the best way to inherit an array that needs to store subclass specific data? I'm trying to set up an inheritance hierarchy similar to the following: abstract class Vehicle { public string Name; public List Axles; } class Motorcycle: Vehicle { } class Car: Vehicle { } abstract class Axle { public int Length; public void Turn(int numTurns) {... } } class MotorcycleAxle: Axle { public bool WheelAttached; } class CarAxle: Axle { public bool LeftWheelAttached; public bool RightWheelAttached; } I would like to only store MotorcycleAxle objects in a Motorcycle object's Axles array, and CarAxle objects in a Car object's Axles array. The problem is there is no way to override the array in the subclass to force one or the other. Ideally something like the following would be valid for the Motorcycle class: class Motorcycle: Vehicle { public override List Axles; } but the types have to match when overriding. How can I support this architecture? Will I just have to do a lot of run-time type checking and casting wherever the Axles member is accessed? I don't like adding run-time type checks because you start to lose the benefits of strong typing and polymorphism. There have to be at least some run-time checks in this scenario since the WheelAttached and Left/RightWheelAttached properties depend on the type, but I would like to minimize them.
TITLE: What is the best way to inherit an array that needs to store subclass specific data? QUESTION: I'm trying to set up an inheritance hierarchy similar to the following: abstract class Vehicle { public string Name; public List Axles; } class Motorcycle: Vehicle { } class Car: Vehicle { } abstract class Axle { public int Length; public void Turn(int numTurns) {... } } class MotorcycleAxle: Axle { public bool WheelAttached; } class CarAxle: Axle { public bool LeftWheelAttached; public bool RightWheelAttached; } I would like to only store MotorcycleAxle objects in a Motorcycle object's Axles array, and CarAxle objects in a Car object's Axles array. The problem is there is no way to override the array in the subclass to force one or the other. Ideally something like the following would be valid for the Motorcycle class: class Motorcycle: Vehicle { public override List Axles; } but the types have to match when overriding. How can I support this architecture? Will I just have to do a lot of run-time type checking and casting wherever the Axles member is accessed? I don't like adding run-time type checks because you start to lose the benefits of strong typing and polymorphism. There have to be at least some run-time checks in this scenario since the WheelAttached and Left/RightWheelAttached properties depend on the type, but I would like to minimize them. ANSWER: Use more generics abstract class Vehicle where T: Axle { public string Name; public List Axles; } class Motorcycle: Vehicle { } class Car: Vehicle { } abstract class Axle { public int Length; public void Turn(int numTurns) {... } } class MotorcycleAxle: Axle { public bool WheelAttached; } class CarAxle: Axle { public bool LeftWheelAttached; public bool RightWheelAttached; }
[ "c#", "oop", "inheritance", "covariance", "contravariance" ]
2
5
4,826
3
0
2008-08-27T20:02:00.813000
2008-08-27T20:10:28.373000
31,090
31,262
What control is this? ("Open" Button with Drop Down)
The Open button on the open file dialog used in certain windows applications includes a dropdown arrow with a list of additional options — namely Open With... I haven't seen this in every Windows application, so you may have to try a few to get it, but SQL Server Management Studio and Visual Studio 2017 will both show the button that way if you go to the menu and choose File -> Open -> File... I want to use a button like this with a built-in list in one of my applications, but I can't find the control they're using anywhere in Visual Studio. I should clarify that I'm looking for that specific button, not the entire dialog. Any thoughts?
I used the draggable search in Spy++ (installed with VS) to look at the split open button on the file-open dialog of VS. This revealed that it's an ordinary windows button with a style which includes BS_DEFSPLITBUTTON. That's a magic keyword which gets you to some interesting places, including http://www.codeplex.com/windowsformsaero/SourceControl/FileView.aspx?itemId=212902&changeSetId=9930 and here http://msdn.microsoft.com/en-us/library/bb775949.aspx#using_splits Hope this helps you. EDIT: I've actually just tried that code from CodePlex and it does create a split button - but you do have to make sure you've set the button's FlatStyle to 'System' rather than 'Standard' which is the default. I've not bothered to hook-up the event handling stuff for the drop-down, but that's covered in the MSDN link, I think. Of course, this is Vista-only (but doesn't need Aero enabled, despite the name on codeplex) - if you need earlier OS support, you'll be back to drawing it yourself.
What control is this? ("Open" Button with Drop Down) The Open button on the open file dialog used in certain windows applications includes a dropdown arrow with a list of additional options — namely Open With... I haven't seen this in every Windows application, so you may have to try a few to get it, but SQL Server Management Studio and Visual Studio 2017 will both show the button that way if you go to the menu and choose File -> Open -> File... I want to use a button like this with a built-in list in one of my applications, but I can't find the control they're using anywhere in Visual Studio. I should clarify that I'm looking for that specific button, not the entire dialog. Any thoughts?
TITLE: What control is this? ("Open" Button with Drop Down) QUESTION: The Open button on the open file dialog used in certain windows applications includes a dropdown arrow with a list of additional options — namely Open With... I haven't seen this in every Windows application, so you may have to try a few to get it, but SQL Server Management Studio and Visual Studio 2017 will both show the button that way if you go to the menu and choose File -> Open -> File... I want to use a button like this with a built-in list in one of my applications, but I can't find the control they're using anywhere in Visual Studio. I should clarify that I'm looking for that specific button, not the entire dialog. Any thoughts? ANSWER: I used the draggable search in Spy++ (installed with VS) to look at the split open button on the file-open dialog of VS. This revealed that it's an ordinary windows button with a style which includes BS_DEFSPLITBUTTON. That's a magic keyword which gets you to some interesting places, including http://www.codeplex.com/windowsformsaero/SourceControl/FileView.aspx?itemId=212902&changeSetId=9930 and here http://msdn.microsoft.com/en-us/library/bb775949.aspx#using_splits Hope this helps you. EDIT: I've actually just tried that code from CodePlex and it does create a split button - but you do have to make sure you've set the button's FlatStyle to 'System' rather than 'Standard' which is the default. I've not bothered to hook-up the event handling stuff for the drop-down, but that's covered in the MSDN link, I think. Of course, this is Vista-only (but doesn't need Aero enabled, despite the name on codeplex) - if you need earlier OS support, you'll be back to drawing it yourself.
[ ".net", "winforms", ".net-2.0" ]
9
7
4,578
7
0
2008-08-27T20:03:03.820000
2008-08-27T20:51:31.803000
31,096
31,164
Process Memory Size - Different Counters
I'm trying to find out how much memory my own.Net server process is using (for monitoring and logging purposes). I'm using: Process.GetCurrentProcess().PrivateMemorySize64 However, the Process object has several different properties that let me read the memory space used: Paged, NonPaged, PagedSystem, NonPagedSystem, Private, Virtual, WorkingSet and then the "peaks": which i'm guessing just store the maximum values these last ones ever took. Reading through the MSDN definition of each property hasn't proved too helpful for me. I have to admit my knowledge regarding how memory is managed (as far as paging and virtual goes) is very limited. So my question is obviously "which one should I use?", and I know the answer is "it depends". This process will basically hold a bunch of lists in memory of things that are going on, while other processes communicate with it and query it for stuff. I'm expecting the server where this will run on to require lots of RAM, and so i'm querying this data over time to be able to estimate RAM requirements when compared to the sizes of the lists it keeps inside. So... Which one should I use and why?
If you want to know how much the GC uses try: GC.GetTotalMemory(true) If you want to know what your process uses from Windows (VM Size column in TaskManager) try: Process.GetCurrentProcess().PrivateMemorySize64 If you want to know what your process has in RAM (as opposed to in the pagefile) (Mem Usage column in TaskManager) try: Process.GetCurrentProcess().WorkingSet64 See here for more explanation on the different sorts of memory.
Process Memory Size - Different Counters I'm trying to find out how much memory my own.Net server process is using (for monitoring and logging purposes). I'm using: Process.GetCurrentProcess().PrivateMemorySize64 However, the Process object has several different properties that let me read the memory space used: Paged, NonPaged, PagedSystem, NonPagedSystem, Private, Virtual, WorkingSet and then the "peaks": which i'm guessing just store the maximum values these last ones ever took. Reading through the MSDN definition of each property hasn't proved too helpful for me. I have to admit my knowledge regarding how memory is managed (as far as paging and virtual goes) is very limited. So my question is obviously "which one should I use?", and I know the answer is "it depends". This process will basically hold a bunch of lists in memory of things that are going on, while other processes communicate with it and query it for stuff. I'm expecting the server where this will run on to require lots of RAM, and so i'm querying this data over time to be able to estimate RAM requirements when compared to the sizes of the lists it keeps inside. So... Which one should I use and why?
TITLE: Process Memory Size - Different Counters QUESTION: I'm trying to find out how much memory my own.Net server process is using (for monitoring and logging purposes). I'm using: Process.GetCurrentProcess().PrivateMemorySize64 However, the Process object has several different properties that let me read the memory space used: Paged, NonPaged, PagedSystem, NonPagedSystem, Private, Virtual, WorkingSet and then the "peaks": which i'm guessing just store the maximum values these last ones ever took. Reading through the MSDN definition of each property hasn't proved too helpful for me. I have to admit my knowledge regarding how memory is managed (as far as paging and virtual goes) is very limited. So my question is obviously "which one should I use?", and I know the answer is "it depends". This process will basically hold a bunch of lists in memory of things that are going on, while other processes communicate with it and query it for stuff. I'm expecting the server where this will run on to require lots of RAM, and so i'm querying this data over time to be able to estimate RAM requirements when compared to the sizes of the lists it keeps inside. So... Which one should I use and why? ANSWER: If you want to know how much the GC uses try: GC.GetTotalMemory(true) If you want to know what your process uses from Windows (VM Size column in TaskManager) try: Process.GetCurrentProcess().PrivateMemorySize64 If you want to know what your process has in RAM (as opposed to in the pagefile) (Mem Usage column in TaskManager) try: Process.GetCurrentProcess().WorkingSet64 See here for more explanation on the different sorts of memory.
[ "c#", ".net", "memory", "process", "diagnostics" ]
19
18
18,961
7
0
2008-08-27T20:05:23.300000
2008-08-27T20:23:11.090000
31,097
31,860
Is there a lang-vb or lang-basic option for prettify.js from Google?
Visual Basic code does not render correctly with prettify.js from Google. on Stack Overflow: Partial Public Class WebForm1 Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 'set page title Page.Title = "Something" End Sub End Class in Visual Studio... I found this in the README document: How do I specify which language my code is in? You don't need to specify the language since prettyprint() will guess. You can specify a language by specifying the language extension along with the prettyprint class like so: The lang-* class specifies the language file extensions. Supported file extensions include "c", "cc", "cpp", "cs", "cyc", "java", "bsh", "csh", "sh", "cv", "py", "perl", "pl", "pm", "rb", "js", "html", "html", "xhtml", "xml", "xsl". I see no lang-vb or lang-basic option. Does anyone know if one exists as an add-in? Note: This is related to the VB.NET code blocks suggestion for Stack Overflow.
/EDIT: I've rewritten the whole posting. Below is a pretty complete solution to the VB highlighting problem. If SO has got nothing better, please use it. VB syntax highlighting is definitely wanted. I've also added a code example with some complex code literals that gets highlighted correctly. However, I haven't even tried to get XLinq right. Might still work, though. The keywords list is taken from the MSDN. Contextual keywords are not included. Did you know the GetXmlNamespace operator? The algorithm knows literal type characters. It should also be able to handle identifier type characters but I haven't tested these. Note that the code works on HTML. As a consequence, &, < and > are required to be read as named (!) entities, not single characters. Sorry for the long regex. var highlightVB = function(code) { var regex = /("(?:""|[^"])+"c?)|('.*$)|#.+?#|(&[HO])?\d+(\.\d*)?(e[+-]?\d+)?U?([SILDFR%@!#]|&)?|\.\d+[FR!#]?|\s+|\w+|&|<|>|([-+*/\\^$@!#%&<>()\[\]{}.,:=]+)/gi; var lines = code.split("\n"); for (var i = 0; i < lines.length; i++) { var line = lines[i]; var tokens; var result = ""; while (tokens = regex.exec(line)) { var tok = getToken(tokens); switch (tok.charAt(0)) { case '"': if (tok.charAt(tok.length - 1) == "c") result += span("char", tok); else result += span("string", tok); break; case "'": result += span("comment", tok); break; case '#': result += span("date", tok); break; default: var c1 = tok.charAt(0); if (isDigit(c1) || tok.length > 1 && c1 == '.' && isDigit(tok.charAt(1)) || tok.length > 5 && (tok.indexOf("&") == 0 && tok.charAt(5) == 'H' || tok.charAt(5) == 'O') ) result += span("number", tok); else if (isKeyword(tok)) result += span("keyword", tok); else result += tok; break; } } lines[i] = result; } return lines.join("\n"); } var keywords = [ "addhandler", "addressof", "alias", "and", "andalso", "as", "boolean", "byref", "byte", "byval", "call", "case", "catch", "cbool", "cbyte", "cchar", "cdate", "cdec", "cdbl", "char", "cint", "class", "clng", "cobj", "const", "continue", "csbyte", "cshort", "csng", "cstr", "ctype", "cuint", "culng", "cushort", "date", "decimal", "declare", "default", "delegate", "dim", "directcast", "do", "double", "each", "else", "elseif", "end", "endif", "enum", "erase", "error", "event", "exit", "false", "finally", "for", "friend", "function", "get", "gettype", "getxmlnamespace", "global", "gosub", "goto", "handles", "if", "if", "implements", "imports", "in", "inherits", "integer", "interface", "is", "isnot", "let", "lib", "like", "long", "loop", "me", "mod", "module", "mustinherit", "mustoverride", "mybase", "myclass", "namespace", "narrowing", "new", "next", "not", "nothing", "notinheritable", "notoverridable", "object", "of", "on", "operator", "option", "optional", "or", "orelse", "overloads", "overridable", "overrides", "paramarray", "partial", "private", "property", "protected", "public", "raiseevent", "readonly", "redim", "rem", "removehandler", "resume", "return", "sbyte", "select", "set", "shadows", "shared", "short", "single", "static", "step", "stop", "string", "structure", "sub", "synclock", "then", "throw", "to", "true", "try", "trycast", "typeof", "variant", "wend", "uinteger", "ulong", "ushort", "using", "when", "while", "widening", "with", "withevents", "writeonly", "xor", "#const", "#else", "#elseif", "#end", "#if" ] var isKeyword = function(token) { return keywords.indexOf(token.toLowerCase())!= -1; } var isDigit = function(c) { return c >= '0' && c <= '9'; } var getToken = function(tokens) { for (var i = 0; i < tokens.length; i++) if (tokens[i]!= undefined) return tokens[i]; return null; } var span = function(class, text) { return " " + text + " "; } Code for testing: Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load 'set page title Page.Title = "Something" Dim r As String = "Say ""Hello""" Dim i As Integer = 1234 Dim d As Double = 1.23 Dim s As Single =.123F Dim l As Long = 123L Dim ul As ULong = 123UL Dim c As Char = "x"c Dim h As Integer = &H0 Dim t As Date = #5/31/1993 1:15:30 PM# Dim f As Single = 1.32e-5F End Sub
Is there a lang-vb or lang-basic option for prettify.js from Google? Visual Basic code does not render correctly with prettify.js from Google. on Stack Overflow: Partial Public Class WebForm1 Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 'set page title Page.Title = "Something" End Sub End Class in Visual Studio... I found this in the README document: How do I specify which language my code is in? You don't need to specify the language since prettyprint() will guess. You can specify a language by specifying the language extension along with the prettyprint class like so: The lang-* class specifies the language file extensions. Supported file extensions include "c", "cc", "cpp", "cs", "cyc", "java", "bsh", "csh", "sh", "cv", "py", "perl", "pl", "pm", "rb", "js", "html", "html", "xhtml", "xml", "xsl". I see no lang-vb or lang-basic option. Does anyone know if one exists as an add-in? Note: This is related to the VB.NET code blocks suggestion for Stack Overflow.
TITLE: Is there a lang-vb or lang-basic option for prettify.js from Google? QUESTION: Visual Basic code does not render correctly with prettify.js from Google. on Stack Overflow: Partial Public Class WebForm1 Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 'set page title Page.Title = "Something" End Sub End Class in Visual Studio... I found this in the README document: How do I specify which language my code is in? You don't need to specify the language since prettyprint() will guess. You can specify a language by specifying the language extension along with the prettyprint class like so: The lang-* class specifies the language file extensions. Supported file extensions include "c", "cc", "cpp", "cs", "cyc", "java", "bsh", "csh", "sh", "cv", "py", "perl", "pl", "pm", "rb", "js", "html", "html", "xhtml", "xml", "xsl". I see no lang-vb or lang-basic option. Does anyone know if one exists as an add-in? Note: This is related to the VB.NET code blocks suggestion for Stack Overflow. ANSWER: /EDIT: I've rewritten the whole posting. Below is a pretty complete solution to the VB highlighting problem. If SO has got nothing better, please use it. VB syntax highlighting is definitely wanted. I've also added a code example with some complex code literals that gets highlighted correctly. However, I haven't even tried to get XLinq right. Might still work, though. The keywords list is taken from the MSDN. Contextual keywords are not included. Did you know the GetXmlNamespace operator? The algorithm knows literal type characters. It should also be able to handle identifier type characters but I haven't tested these. Note that the code works on HTML. As a consequence, &, < and > are required to be read as named (!) entities, not single characters. Sorry for the long regex. var highlightVB = function(code) { var regex = /("(?:""|[^"])+"c?)|('.*$)|#.+?#|(&[HO])?\d+(\.\d*)?(e[+-]?\d+)?U?([SILDFR%@!#]|&)?|\.\d+[FR!#]?|\s+|\w+|&|<|>|([-+*/\\^$@!#%&<>()\[\]{}.,:=]+)/gi; var lines = code.split("\n"); for (var i = 0; i < lines.length; i++) { var line = lines[i]; var tokens; var result = ""; while (tokens = regex.exec(line)) { var tok = getToken(tokens); switch (tok.charAt(0)) { case '"': if (tok.charAt(tok.length - 1) == "c") result += span("char", tok); else result += span("string", tok); break; case "'": result += span("comment", tok); break; case '#': result += span("date", tok); break; default: var c1 = tok.charAt(0); if (isDigit(c1) || tok.length > 1 && c1 == '.' && isDigit(tok.charAt(1)) || tok.length > 5 && (tok.indexOf("&") == 0 && tok.charAt(5) == 'H' || tok.charAt(5) == 'O') ) result += span("number", tok); else if (isKeyword(tok)) result += span("keyword", tok); else result += tok; break; } } lines[i] = result; } return lines.join("\n"); } var keywords = [ "addhandler", "addressof", "alias", "and", "andalso", "as", "boolean", "byref", "byte", "byval", "call", "case", "catch", "cbool", "cbyte", "cchar", "cdate", "cdec", "cdbl", "char", "cint", "class", "clng", "cobj", "const", "continue", "csbyte", "cshort", "csng", "cstr", "ctype", "cuint", "culng", "cushort", "date", "decimal", "declare", "default", "delegate", "dim", "directcast", "do", "double", "each", "else", "elseif", "end", "endif", "enum", "erase", "error", "event", "exit", "false", "finally", "for", "friend", "function", "get", "gettype", "getxmlnamespace", "global", "gosub", "goto", "handles", "if", "if", "implements", "imports", "in", "inherits", "integer", "interface", "is", "isnot", "let", "lib", "like", "long", "loop", "me", "mod", "module", "mustinherit", "mustoverride", "mybase", "myclass", "namespace", "narrowing", "new", "next", "not", "nothing", "notinheritable", "notoverridable", "object", "of", "on", "operator", "option", "optional", "or", "orelse", "overloads", "overridable", "overrides", "paramarray", "partial", "private", "property", "protected", "public", "raiseevent", "readonly", "redim", "rem", "removehandler", "resume", "return", "sbyte", "select", "set", "shadows", "shared", "short", "single", "static", "step", "stop", "string", "structure", "sub", "synclock", "then", "throw", "to", "true", "try", "trycast", "typeof", "variant", "wend", "uinteger", "ulong", "ushort", "using", "when", "while", "widening", "with", "withevents", "writeonly", "xor", "#const", "#else", "#elseif", "#end", "#if" ] var isKeyword = function(token) { return keywords.indexOf(token.toLowerCase())!= -1; } var isDigit = function(c) { return c >= '0' && c <= '9'; } var getToken = function(tokens) { for (var i = 0; i < tokens.length; i++) if (tokens[i]!= undefined) return tokens[i]; return null; } var span = function(class, text) { return " " + text + " "; } Code for testing: Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load 'set page title Page.Title = "Something" Dim r As String = "Say ""Hello""" Dim i As Integer = 1234 Dim d As Double = 1.23 Dim s As Single =.123F Dim l As Long = 123L Dim ul As ULong = 123UL Dim c As Char = "x"c Dim h As Integer = &H0 Dim t As Date = #5/31/1993 1:15:30 PM# Dim f As Single = 1.32e-5F End Sub
[ "javascript", "vb.net", "prettify" ]
11
8
1,140
3
0
2008-08-27T20:05:30.883000
2008-08-28T08:43:06.850000
31,127
45,580
Java Swing: Displaying images from within a Jar
When running a Java app from eclipse my ImageIcon shows up just fine. But after creating a jar the path to the image obviously gets screwed up. Is there a way to extract an image from the jar at runtime so I can then open it up? Or, is there a better way to do this? I'd like to distribute a single jar file if possible.
To create an ImageIcon from an image file within the same jars your code is loaded: new javax.swing.ImageIcon(getClass().getResource("myimage.jpeg")) Class.getResource returns a URL of a resource (or null!). ImageIcon has a constructors that load from a URL. To construct a URL for a resource in a jar not on your "classpath", see the documentation for java.net.JarURLConnection.
Java Swing: Displaying images from within a Jar When running a Java app from eclipse my ImageIcon shows up just fine. But after creating a jar the path to the image obviously gets screwed up. Is there a way to extract an image from the jar at runtime so I can then open it up? Or, is there a better way to do this? I'd like to distribute a single jar file if possible.
TITLE: Java Swing: Displaying images from within a Jar QUESTION: When running a Java app from eclipse my ImageIcon shows up just fine. But after creating a jar the path to the image obviously gets screwed up. Is there a way to extract an image from the jar at runtime so I can then open it up? Or, is there a better way to do this? I'd like to distribute a single jar file if possible. ANSWER: To create an ImageIcon from an image file within the same jars your code is loaded: new javax.swing.ImageIcon(getClass().getResource("myimage.jpeg")) Class.getResource returns a URL of a resource (or null!). ImageIcon has a constructors that load from a URL. To construct a URL for a resource in a jar not on your "classpath", see the documentation for java.net.JarURLConnection.
[ "java", "swing", "embedded-resource", "imageicon" ]
48
37
41,918
5
0
2008-08-27T20:14:07.150000
2008-09-05T11:30:37.147000
31,128
32,478
Enforcing web coding standards
The HTML standard defines a clear separation of concerns between CSS (presentation) and HTML (semantics or structure). Does anyone use a coding standards document for CSS and XHTML that has clauses which help to maintain this separation? What would be good clauses to include in such a coding standards document?
We don't have a physical document we all adhere to where I work. There are a number of guidelines we try and keep in mind but there isn't really enough information to require a physcial document. This article sums them up these guidelines pretty well. You may also consider formatting your CSS to make it easier to read. Smashing Magazine has a great article on this subject.
Enforcing web coding standards The HTML standard defines a clear separation of concerns between CSS (presentation) and HTML (semantics or structure). Does anyone use a coding standards document for CSS and XHTML that has clauses which help to maintain this separation? What would be good clauses to include in such a coding standards document?
TITLE: Enforcing web coding standards QUESTION: The HTML standard defines a clear separation of concerns between CSS (presentation) and HTML (semantics or structure). Does anyone use a coding standards document for CSS and XHTML that has clauses which help to maintain this separation? What would be good clauses to include in such a coding standards document? ANSWER: We don't have a physical document we all adhere to where I work. There are a number of guidelines we try and keep in mind but there isn't really enough information to require a physcial document. This article sums them up these guidelines pretty well. You may also consider formatting your CSS to make it easier to read. Smashing Magazine has a great article on this subject.
[ "html", "css", "xhtml", "coding-style" ]
5
2
374
2
0
2008-08-27T20:14:15.543000
2008-08-28T14:49:54.267000
31,129
31,153
How can I return a variable from a $.getJSON function
I want to return StudentId to use elsewhere outside of the scope of the $.getJSON() j.getJSON(url, data, function(result) { var studentId = result.Something; }); //use studentId here I would imagine this has to do with scoping, but it doesn't seem to work the same way c# does
Yeah, my previous answer does not work because I didn't pay any attention to your code.:) The problem is that the anonymous function is a callback function - i.e. getJSON is an async operation that will return at some indeterminate point in time, so even if the scope of the variable were outside of that anonymous function (i.e. a closure), it would not have the value you would think it should: var studentId = null; j.getJSON(url, data, function(result) { studentId = result.Something; }); // studentId is still null right here, because this line // executes before the line that sets its value to result.Something Any code that you want to execute with the value of studentId set by the getJSON call needs to happen either within that callback function or after the callback executes.
How can I return a variable from a $.getJSON function I want to return StudentId to use elsewhere outside of the scope of the $.getJSON() j.getJSON(url, data, function(result) { var studentId = result.Something; }); //use studentId here I would imagine this has to do with scoping, but it doesn't seem to work the same way c# does
TITLE: How can I return a variable from a $.getJSON function QUESTION: I want to return StudentId to use elsewhere outside of the scope of the $.getJSON() j.getJSON(url, data, function(result) { var studentId = result.Something; }); //use studentId here I would imagine this has to do with scoping, but it doesn't seem to work the same way c# does ANSWER: Yeah, my previous answer does not work because I didn't pay any attention to your code.:) The problem is that the anonymous function is a callback function - i.e. getJSON is an async operation that will return at some indeterminate point in time, so even if the scope of the variable were outside of that anonymous function (i.e. a closure), it would not have the value you would think it should: var studentId = null; j.getJSON(url, data, function(result) { studentId = result.Something; }); // studentId is still null right here, because this line // executes before the line that sets its value to result.Something Any code that you want to execute with the value of studentId set by the getJSON call needs to happen either within that callback function or after the callback executes.
[ "javascript", "jquery", "ajax", "scope", "return-value" ]
55
41
98,958
6
0
2008-08-27T20:14:19.880000
2008-08-27T20:19:51.580000
31,151
31,206
ASP.NET - How do you Unit Test WebControls?
Alright. So I figure it's about time I get into unit testing, since everyone's been banging on about it for long enough. I've installed NUnit and gone through a few "intro to unit testing" type tutorials. I'm currently putting together a small framework to help with the rebuild of one of our web apps, so I've created a VS2008 project for my framework and I want to unit test it as I go. How on earth do I go about unit testing the WebControls? The methods are all protected or private, and since it's a framework, there isn't much else but WebControls. Any pointers? Burns
You can do model-view-controller or model-view-presenter type architectures without using a full blown framework. You already found out that unit-testing ui-components is difficult. There are ways around that but you probably don't want to go that route. Usually this will make your tests very hard to maintain, more maintenance nightmare's is something programmers can do without:-) Try to separate out the functionality you want to test in a "controller" or "presenter" class. Then test that class. To make it more testable you can hide the usercontrol class (the view) behind an interface and make the controller or presenter talk to the view through the interface. That way you can mock up the view in your tests. I know this sounds like a lot of work and it seems like a workaround but if you get used to this it's a realy nice architecture that makes it far easier to change ui behaviour. You can always start using a "real" mvc framework when you realy need it:-)
ASP.NET - How do you Unit Test WebControls? Alright. So I figure it's about time I get into unit testing, since everyone's been banging on about it for long enough. I've installed NUnit and gone through a few "intro to unit testing" type tutorials. I'm currently putting together a small framework to help with the rebuild of one of our web apps, so I've created a VS2008 project for my framework and I want to unit test it as I go. How on earth do I go about unit testing the WebControls? The methods are all protected or private, and since it's a framework, there isn't much else but WebControls. Any pointers? Burns
TITLE: ASP.NET - How do you Unit Test WebControls? QUESTION: Alright. So I figure it's about time I get into unit testing, since everyone's been banging on about it for long enough. I've installed NUnit and gone through a few "intro to unit testing" type tutorials. I'm currently putting together a small framework to help with the rebuild of one of our web apps, so I've created a VS2008 project for my framework and I want to unit test it as I go. How on earth do I go about unit testing the WebControls? The methods are all protected or private, and since it's a framework, there isn't much else but WebControls. Any pointers? Burns ANSWER: You can do model-view-controller or model-view-presenter type architectures without using a full blown framework. You already found out that unit-testing ui-components is difficult. There are ways around that but you probably don't want to go that route. Usually this will make your tests very hard to maintain, more maintenance nightmare's is something programmers can do without:-) Try to separate out the functionality you want to test in a "controller" or "presenter" class. Then test that class. To make it more testable you can hide the usercontrol class (the view) behind an interface and make the controller or presenter talk to the view through the interface. That way you can mock up the view in your tests. I know this sounds like a lot of work and it seems like a workaround but if you get used to this it's a realy nice architecture that makes it far easier to change ui behaviour. You can always start using a "real" mvc framework when you realy need it:-)
[ "asp.net", "unit-testing" ]
13
8
5,077
9
0
2008-08-27T20:19:45.077000
2008-08-27T20:37:06.767000