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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
11,088 | 11,101 | What is the best way to work around the fact that ALL Java bytes are signed? | In Java, there is no such thing as an unsigned byte. Working with some low level code, occasionally you need to work with bytes that have unsigned values greater than 128, which causes Java to interpret them as a negative number due to the MSB being used for sign. What's a good way to work around this? (Saying don't use Java is not an option) | When reading any single value from the array copy it into something like a short or an int and manually convert the negative number into the positive value it should be. byte[] foobar =..; int value = foobar[10]; if (value < 0) value += 256 // Patch up the 'falsely' negative value You can do a similar conversion when writing into the array. | What is the best way to work around the fact that ALL Java bytes are signed? In Java, there is no such thing as an unsigned byte. Working with some low level code, occasionally you need to work with bytes that have unsigned values greater than 128, which causes Java to interpret them as a negative number due to the MSB being used for sign. What's a good way to work around this? (Saying don't use Java is not an option) | TITLE:
What is the best way to work around the fact that ALL Java bytes are signed?
QUESTION:
In Java, there is no such thing as an unsigned byte. Working with some low level code, occasionally you need to work with bytes that have unsigned values greater than 128, which causes Java to interpret them as a negative number due to the MSB being used for sign. What's a good way to work around this? (Saying don't use Java is not an option)
ANSWER:
When reading any single value from the array copy it into something like a short or an int and manually convert the negative number into the positive value it should be. byte[] foobar =..; int value = foobar[10]; if (value < 0) value += 256 // Patch up the 'falsely' negative value You can do a similar conversion when writing into the array. | [
"java",
"byte",
"unsigned",
"signed"
] | 60 | 20 | 27,050 | 7 | 0 | 2008-08-14T14:14:03.940000 | 2008-08-14T14:24:50.453000 |
11,099 | 11,107 | What is the prefered style for single decision and action statements? | In the case of languages that support single decision and action without brackets, such as the following example: if (var == true) doSomething(); What is the preferred way of writing this? Should brackets always be used, or should their usage be left as a preference of the individual developer? Additionally, does this practice depend on the size of the code block, such as in the following example: if (var == 1) doSomething(1); else if (var > 1 && var < 10) doSomething(2); else { validate(var); doSomething(var); } | There isn't really a right answer. This is what coding standards within the company are for. If you can keep it consistent across the whole company then it will be easy to read. I personally like if ( a == b) { doSomething(); } else { doSomething(); } but this is a holy war. | What is the prefered style for single decision and action statements? In the case of languages that support single decision and action without brackets, such as the following example: if (var == true) doSomething(); What is the preferred way of writing this? Should brackets always be used, or should their usage be left as a preference of the individual developer? Additionally, does this practice depend on the size of the code block, such as in the following example: if (var == 1) doSomething(1); else if (var > 1 && var < 10) doSomething(2); else { validate(var); doSomething(var); } | TITLE:
What is the prefered style for single decision and action statements?
QUESTION:
In the case of languages that support single decision and action without brackets, such as the following example: if (var == true) doSomething(); What is the preferred way of writing this? Should brackets always be used, or should their usage be left as a preference of the individual developer? Additionally, does this practice depend on the size of the code block, such as in the following example: if (var == 1) doSomething(1); else if (var > 1 && var < 10) doSomething(2); else { validate(var); doSomething(var); }
ANSWER:
There isn't really a right answer. This is what coding standards within the company are for. If you can keep it consistent across the whole company then it will be easy to read. I personally like if ( a == b) { doSomething(); } else { doSomething(); } but this is a holy war. | [
"language-agnostic",
"language-features",
"readability"
] | 3 | 10 | 966 | 20 | 0 | 2008-08-14T14:23:11.237000 | 2008-08-14T14:27:26.750000 |
11,112 | 2,028,892 | Best Wiki for Mobile Users | Most wiki software I've presents lots of "features" on their pages. This is fine for desktop users, but is annoying when using an iPhone or other mobile device. I'd prefer pages that just had the content, along with maybe an Edit button and a Search button. The editors are also often too fancy for mobile users; a simple multi-line edit field would be better for mobile users than a bunch of formatting controls. What is a good wiki package for mobile users? | W2 by Steven Frank (of Panic, makers of Transmit) is awesome. It's totally stripped down for iPhone--just the essentials. It supports markdown and basic Wiki-style formatting. https://github.com/panicsteve/w2wiki That page has a link to a demo site. | Best Wiki for Mobile Users Most wiki software I've presents lots of "features" on their pages. This is fine for desktop users, but is annoying when using an iPhone or other mobile device. I'd prefer pages that just had the content, along with maybe an Edit button and a Search button. The editors are also often too fancy for mobile users; a simple multi-line edit field would be better for mobile users than a bunch of formatting controls. What is a good wiki package for mobile users? | TITLE:
Best Wiki for Mobile Users
QUESTION:
Most wiki software I've presents lots of "features" on their pages. This is fine for desktop users, but is annoying when using an iPhone or other mobile device. I'd prefer pages that just had the content, along with maybe an Edit button and a Search button. The editors are also often too fancy for mobile users; a simple multi-line edit field would be better for mobile users than a bunch of formatting controls. What is a good wiki package for mobile users?
ANSWER:
W2 by Steven Frank (of Panic, makers of Transmit) is awesome. It's totally stripped down for iPhone--just the essentials. It supports markdown and basic Wiki-style formatting. https://github.com/panicsteve/w2wiki That page has a link to a demo site. | [
"iphone",
"wiki",
"mobile-website"
] | 7 | 2 | 1,189 | 3 | 0 | 2008-08-14T14:30:17.277000 | 2010-01-08T16:11:47.593000 |
11,127 | 11,132 | In C++/Windows how do I get the network name of the computer I'm on? | In a C++ Windows (XP and NT, if it makes a difference) application I'm working on, I need to get the network name associated with the computer the code is executing on, so that I can convert local filenames from C:\filename.ext to \\network_name\C$\filename.ext. How would I do this? Alternatively, if there's a function that will just do the conversion I described, that would be even better. I looked into WNetGetUniversalName, but that doesn't seem to work with local (C drive) files. | You'll want Win32's GetComputerName: http://msdn.microsoft.com/en-us/library/ms724295(VS.85).aspx | In C++/Windows how do I get the network name of the computer I'm on? In a C++ Windows (XP and NT, if it makes a difference) application I'm working on, I need to get the network name associated with the computer the code is executing on, so that I can convert local filenames from C:\filename.ext to \\network_name\C$\filename.ext. How would I do this? Alternatively, if there's a function that will just do the conversion I described, that would be even better. I looked into WNetGetUniversalName, but that doesn't seem to work with local (C drive) files. | TITLE:
In C++/Windows how do I get the network name of the computer I'm on?
QUESTION:
In a C++ Windows (XP and NT, if it makes a difference) application I'm working on, I need to get the network name associated with the computer the code is executing on, so that I can convert local filenames from C:\filename.ext to \\network_name\C$\filename.ext. How would I do this? Alternatively, if there's a function that will just do the conversion I described, that would be even better. I looked into WNetGetUniversalName, but that doesn't seem to work with local (C drive) files.
ANSWER:
You'll want Win32's GetComputerName: http://msdn.microsoft.com/en-us/library/ms724295(VS.85).aspx | [
"c++",
"windows-xp",
"networking",
"windows-nt"
] | 8 | 7 | 10,508 | 4 | 0 | 2008-08-14T14:37:27.120000 | 2008-08-14T14:40:31.217000 |
11,135 | 11,188 | How to run remote shell scripts from ASP pages? | I need to create an ASP page (classic, not ASP.NET) which runs remote shell scripts on a UNIX server, then captures the output into variables in VBScript within the page itself. I have never done ASP or VBScipt before. I have tried to google this stuff, but all I find are references to remote server side scripting, nothing concrete. I could really use: An elementary example of how this could be done. Any other better alternatives to achieve this in a secure manner. Are there any freeware/open source alternatives to these libraries? Any examples? | If the shell scripts are normally run on a telnet session then you could screen scrape and parse the responses. There are commercial COM components out there such as the Dart telnet library: http://www.dart.com/pttel.aspx that would let you do this. Either that or you could roll your own using AspSock http://www.15seconds.com/component/pg000300.htm | How to run remote shell scripts from ASP pages? I need to create an ASP page (classic, not ASP.NET) which runs remote shell scripts on a UNIX server, then captures the output into variables in VBScript within the page itself. I have never done ASP or VBScipt before. I have tried to google this stuff, but all I find are references to remote server side scripting, nothing concrete. I could really use: An elementary example of how this could be done. Any other better alternatives to achieve this in a secure manner. Are there any freeware/open source alternatives to these libraries? Any examples? | TITLE:
How to run remote shell scripts from ASP pages?
QUESTION:
I need to create an ASP page (classic, not ASP.NET) which runs remote shell scripts on a UNIX server, then captures the output into variables in VBScript within the page itself. I have never done ASP or VBScipt before. I have tried to google this stuff, but all I find are references to remote server side scripting, nothing concrete. I could really use: An elementary example of how this could be done. Any other better alternatives to achieve this in a secure manner. Are there any freeware/open source alternatives to these libraries? Any examples?
ANSWER:
If the shell scripts are normally run on a telnet session then you could screen scrape and parse the responses. There are commercial COM components out there such as the Dart telnet library: http://www.dart.com/pttel.aspx that would let you do this. Either that or you could roll your own using AspSock http://www.15seconds.com/component/pg000300.htm | [
"asp-classic",
"vbscript"
] | 1 | 0 | 2,085 | 2 | 0 | 2008-08-14T14:42:50.887000 | 2008-08-14T15:17:54.217000 |
11,141 | 11,146 | ASP.NET Caching | Recently I have been investigating the possibilities of caching in ASP.NET. I rolled my own "Cache", because I didn't know any better, it looked a bit like this: public class DataManager {
private static DataManager s_instance;
public static DataManager GetInstance() { }
private Data[] m_myData; private DataTime m_cacheTime;
public Data[] GetData() { TimeSpan span = DateTime.Now.Substract(m_cacheTime);
if(span.TotalSeconds > 10) { // Do SQL to get data m_myData = data; m_cacheTime = DateTime.Now; return m_myData; } else { return m_myData; } }
} So the values are stored for a while in a singleton, and when the time expires, the values are renewed. If time has not expired, and a request for the data is done, the stored values in the field are returned. What are the benefits over using the real method ( http://msdn.microsoft.com/en-us/library/aa478965.aspx ) instead of this? | I think the maxim "let the computer do it; it's smarter than you" applies here. Just like memory management and other complicated things, the computer is a lot more informed about what it's doing than your are; consequently, able to get more performance than you are. Microsoft has had a team of engineers working on it and they've probably managed to squeeze much more performance out of the system than would be possible for you to. It's also likely that ASP.NET's built-in caching operates at a different level (which is inaccessible to your application), making it much faster. | ASP.NET Caching Recently I have been investigating the possibilities of caching in ASP.NET. I rolled my own "Cache", because I didn't know any better, it looked a bit like this: public class DataManager {
private static DataManager s_instance;
public static DataManager GetInstance() { }
private Data[] m_myData; private DataTime m_cacheTime;
public Data[] GetData() { TimeSpan span = DateTime.Now.Substract(m_cacheTime);
if(span.TotalSeconds > 10) { // Do SQL to get data m_myData = data; m_cacheTime = DateTime.Now; return m_myData; } else { return m_myData; } }
} So the values are stored for a while in a singleton, and when the time expires, the values are renewed. If time has not expired, and a request for the data is done, the stored values in the field are returned. What are the benefits over using the real method ( http://msdn.microsoft.com/en-us/library/aa478965.aspx ) instead of this? | TITLE:
ASP.NET Caching
QUESTION:
Recently I have been investigating the possibilities of caching in ASP.NET. I rolled my own "Cache", because I didn't know any better, it looked a bit like this: public class DataManager {
private static DataManager s_instance;
public static DataManager GetInstance() { }
private Data[] m_myData; private DataTime m_cacheTime;
public Data[] GetData() { TimeSpan span = DateTime.Now.Substract(m_cacheTime);
if(span.TotalSeconds > 10) { // Do SQL to get data m_myData = data; m_cacheTime = DateTime.Now; return m_myData; } else { return m_myData; } }
} So the values are stored for a while in a singleton, and when the time expires, the values are renewed. If time has not expired, and a request for the data is done, the stored values in the field are returned. What are the benefits over using the real method ( http://msdn.microsoft.com/en-us/library/aa478965.aspx ) instead of this?
ANSWER:
I think the maxim "let the computer do it; it's smarter than you" applies here. Just like memory management and other complicated things, the computer is a lot more informed about what it's doing than your are; consequently, able to get more performance than you are. Microsoft has had a team of engineers working on it and they've probably managed to squeeze much more performance out of the system than would be possible for you to. It's also likely that ASP.NET's built-in caching operates at a different level (which is inaccessible to your application), making it much faster. | [
"asp.net",
"sql",
"caching"
] | 2 | 4 | 600 | 3 | 0 | 2008-08-14T14:46:30.317000 | 2008-08-14T14:52:54.267000 |
11,145 | 12,120 | Drawing Library for Ruby | I am trying to code a flowchart generator for a language using Ruby. I wanted to know if there were any libraries that I could use to draw various shapes for the various flowchart elements and write out text to those shapes. I would really prefer not having to write code for drawing basic shapes, if I can help it. Can someone could point me to some reference documentation with examples of using that library? | The simple answer is that (at time of writing) what you want almost certainly didn't exist. Sorry! If you're Windows-based then I'd look for a product in the.NET space, where I expect you'd find something. You're probably going to have to pay real money though. I suppose, if you're brave, you may be able to talk to it using IronRuby. From a non-MS environment I would be hoping for a Java-based solution. As already mentioned, within the Web world, you're going to be hoping some something JavaScript-based, or probably more likely, something from the Flash (or maybe even Silverlight?) world. Actually, if you want to stay in Ruby and don't mind some risk, Silverlight might be a way to go - assuming the DLR stuff actually works (no experience here). Ruby - much as I love it - hardly has the most mature GUI structure around it. Update: Since writing this (approaching 5 years ago) the situation has improved - a little. While I'm still not aware of any specific Ruby graph-drawing libraries, there is improved support for Graphviz here (Github ) or by gem install ruby-graphviz. I've found that for simple graphs, it's quite possible to write the script directly from Ruby. | Drawing Library for Ruby I am trying to code a flowchart generator for a language using Ruby. I wanted to know if there were any libraries that I could use to draw various shapes for the various flowchart elements and write out text to those shapes. I would really prefer not having to write code for drawing basic shapes, if I can help it. Can someone could point me to some reference documentation with examples of using that library? | TITLE:
Drawing Library for Ruby
QUESTION:
I am trying to code a flowchart generator for a language using Ruby. I wanted to know if there were any libraries that I could use to draw various shapes for the various flowchart elements and write out text to those shapes. I would really prefer not having to write code for drawing basic shapes, if I can help it. Can someone could point me to some reference documentation with examples of using that library?
ANSWER:
The simple answer is that (at time of writing) what you want almost certainly didn't exist. Sorry! If you're Windows-based then I'd look for a product in the.NET space, where I expect you'd find something. You're probably going to have to pay real money though. I suppose, if you're brave, you may be able to talk to it using IronRuby. From a non-MS environment I would be hoping for a Java-based solution. As already mentioned, within the Web world, you're going to be hoping some something JavaScript-based, or probably more likely, something from the Flash (or maybe even Silverlight?) world. Actually, if you want to stay in Ruby and don't mind some risk, Silverlight might be a way to go - assuming the DLR stuff actually works (no experience here). Ruby - much as I love it - hardly has the most mature GUI structure around it. Update: Since writing this (approaching 5 years ago) the situation has improved - a little. While I'm still not aware of any specific Ruby graph-drawing libraries, there is improved support for Graphviz here (Github ) or by gem install ruby-graphviz. I've found that for simple graphs, it's quite possible to write the script directly from Ruby. | [
"ruby",
"graphics",
"drawing"
] | 15 | 2 | 11,693 | 4 | 0 | 2008-08-14T14:51:28.217000 | 2008-08-15T10:07:39.113000 |
11,194 | 11,203 | How can I conditionally apply a Linq operator? | We're working on a Log Viewer. The use will have the option to filter by user, severity, etc. In the Sql days I'd add to the query string, but I want to do it with Linq. How can I conditionally add where-clauses? | if you want to only filter if certain criteria is passed, do something like this var logs = from log in context.Logs select log;
if (filterBySeverity) logs = logs.Where(p => p.Severity == severity);
if (filterByUser) logs = logs.Where(p => p.User == user); Doing so this way will allow your Expression tree to be exactly what you want. That way the SQL created will be exactly what you need and nothing less. | How can I conditionally apply a Linq operator? We're working on a Log Viewer. The use will have the option to filter by user, severity, etc. In the Sql days I'd add to the query string, but I want to do it with Linq. How can I conditionally add where-clauses? | TITLE:
How can I conditionally apply a Linq operator?
QUESTION:
We're working on a Log Viewer. The use will have the option to filter by user, severity, etc. In the Sql days I'd add to the query string, but I want to do it with Linq. How can I conditionally add where-clauses?
ANSWER:
if you want to only filter if certain criteria is passed, do something like this var logs = from log in context.Logs select log;
if (filterBySeverity) logs = logs.Where(p => p.Severity == severity);
if (filterByUser) logs = logs.Where(p => p.User == user); Doing so this way will allow your Expression tree to be exactly what you want. That way the SQL created will be exactly what you need and nothing less. | [
"c#",
"linq",
"linq-to-sql"
] | 105 | 171 | 116,967 | 13 | 0 | 2008-08-14T15:20:26.973000 | 2008-08-14T15:27:09.297000 |
11,199 | 11,215 | .NET Framework dependency | When developing a desktop application in.NET, is it possible to not require the.NET Framework? Is developing software in.NET a preferred way to develop desktop applications? What is the most used programming language that software companies use to develop desktop applications? Is the requirement of the.NET Framework just assumed based on the Windows OS you have installed hence why they list Windows OS version requirements? | You can still develop applications for the windows desktop using C/C++, eliminating the requirement to the.NET framework, but you'll need to make sure the necessary libraries are already on the system or installed. The nice thing about the.NET framework is that Windows XP SP2 and Vista has the 3.0 framework runtime installed by default. In a lot of ways, this is Microsoft's "development standard" and has been that way for a while. This allows you to not worry about having a bunch of libraries tacked onto your application. If you're sticking to all of the.NET provided libraries, you wind up only have to worry about deploying your executable, which is a big headache reliever. When you have a bunch of libraries you have to deploy as well, then you start to run into hassles when you write updates, because you have to make sure those updates are pushed out in your existing installer and to all the existing installed apps out there. As for "preferred", that always tends to ruffle feathers at times, but there are more and more.NET developers wanted for the web and the desktop at the job hunt sites I tend to visit. 8^D EDIT: Many thanks to Orion for pointing out my confusion on the frameworks. You get 3.0 "out the gate if you're on XP SP2 or Vista. Everything else is going to require a simple download or run of Windows Update. | .NET Framework dependency When developing a desktop application in.NET, is it possible to not require the.NET Framework? Is developing software in.NET a preferred way to develop desktop applications? What is the most used programming language that software companies use to develop desktop applications? Is the requirement of the.NET Framework just assumed based on the Windows OS you have installed hence why they list Windows OS version requirements? | TITLE:
.NET Framework dependency
QUESTION:
When developing a desktop application in.NET, is it possible to not require the.NET Framework? Is developing software in.NET a preferred way to develop desktop applications? What is the most used programming language that software companies use to develop desktop applications? Is the requirement of the.NET Framework just assumed based on the Windows OS you have installed hence why they list Windows OS version requirements?
ANSWER:
You can still develop applications for the windows desktop using C/C++, eliminating the requirement to the.NET framework, but you'll need to make sure the necessary libraries are already on the system or installed. The nice thing about the.NET framework is that Windows XP SP2 and Vista has the 3.0 framework runtime installed by default. In a lot of ways, this is Microsoft's "development standard" and has been that way for a while. This allows you to not worry about having a bunch of libraries tacked onto your application. If you're sticking to all of the.NET provided libraries, you wind up only have to worry about deploying your executable, which is a big headache reliever. When you have a bunch of libraries you have to deploy as well, then you start to run into hassles when you write updates, because you have to make sure those updates are pushed out in your existing installer and to all the existing installed apps out there. As for "preferred", that always tends to ruffle feathers at times, but there are more and more.NET developers wanted for the web and the desktop at the job hunt sites I tend to visit. 8^D EDIT: Many thanks to Orion for pointing out my confusion on the frameworks. You get 3.0 "out the gate if you're on XP SP2 or Vista. Everything else is going to require a simple download or run of Windows Update. | [
".net",
"frameworks",
"dependencies"
] | 5 | 10 | 4,211 | 15 | 0 | 2008-08-14T15:25:44.637000 | 2008-08-14T15:32:49.410000 |
11,200 | 11,240 | T-Sql date format for seconds since last epoch / formatting for sqlite input | I'm guessing it needs to be something like: CONVERT(CHAR(24), lastModified, 101) However I'm not sure of the right value for the third parameter. Thanks! Well I'm trying to write a script to copy my sql server db to a sqlite file, which gets downloaded to an air app, which then syncs the data to another sqlite file. I'm having a ton of trouble with dates. If I select a date in air and try to insert it, it fails because it's not in the right format... even if it was a valid date to begin with. I figured I'd try to experiment with the unix time since that's the only thing thats worked so far. I am considering just leaving them as varchar because I don't sort by them anyway. | I wound up using format 120 in MS SQL: convert(char(24), lastModified, 120) Each time I needed to a select a date in SQLite for non-display purposes I used: strftime(\"%Y-%m-%d %H:%M:%S\", dateModified) as dateModified Now I just need a readable/friendly way to display the date to the user! edit: accept answer goes to whoever shows me how to display the date nicely from sqlite;p | T-Sql date format for seconds since last epoch / formatting for sqlite input I'm guessing it needs to be something like: CONVERT(CHAR(24), lastModified, 101) However I'm not sure of the right value for the third parameter. Thanks! Well I'm trying to write a script to copy my sql server db to a sqlite file, which gets downloaded to an air app, which then syncs the data to another sqlite file. I'm having a ton of trouble with dates. If I select a date in air and try to insert it, it fails because it's not in the right format... even if it was a valid date to begin with. I figured I'd try to experiment with the unix time since that's the only thing thats worked so far. I am considering just leaving them as varchar because I don't sort by them anyway. | TITLE:
T-Sql date format for seconds since last epoch / formatting for sqlite input
QUESTION:
I'm guessing it needs to be something like: CONVERT(CHAR(24), lastModified, 101) However I'm not sure of the right value for the third parameter. Thanks! Well I'm trying to write a script to copy my sql server db to a sqlite file, which gets downloaded to an air app, which then syncs the data to another sqlite file. I'm having a ton of trouble with dates. If I select a date in air and try to insert it, it fails because it's not in the right format... even if it was a valid date to begin with. I figured I'd try to experiment with the unix time since that's the only thing thats worked so far. I am considering just leaving them as varchar because I don't sort by them anyway.
ANSWER:
I wound up using format 120 in MS SQL: convert(char(24), lastModified, 120) Each time I needed to a select a date in SQLite for non-display purposes I used: strftime(\"%Y-%m-%d %H:%M:%S\", dateModified) as dateModified Now I just need a readable/friendly way to display the date to the user! edit: accept answer goes to whoever shows me how to display the date nicely from sqlite;p | [
"t-sql",
"sqlite",
"date"
] | 1 | 1 | 8,713 | 6 | 0 | 2008-08-14T15:26:11.327000 | 2008-08-14T15:52:17.237000 |
11,219 | 11,238 | Calling REST web services from a classic asp page | I'd like to start moving our application business layers into a collection of REST web services. However, most of our Intranet has been built using Classic ASP and most of the developers where I work keep programming in Classic ASP. Ideally, then, for them to benefit from the advantages of a unique set of web APIs, it would have to be called from Classic ASP pages. I haven't the slightest idea how to do that. | You could use a combination of JQuery with JSON calls to consume REST services from the client or if you need to interact with the REST services from the ASP layer you can use MSXML2.ServerXMLHTTP like: Set HttpReq = Server.CreateObject("MSXML2.ServerXMLHTTP") HttpReq.open "GET", "Rest_URI", False HttpReq.send | Calling REST web services from a classic asp page I'd like to start moving our application business layers into a collection of REST web services. However, most of our Intranet has been built using Classic ASP and most of the developers where I work keep programming in Classic ASP. Ideally, then, for them to benefit from the advantages of a unique set of web APIs, it would have to be called from Classic ASP pages. I haven't the slightest idea how to do that. | TITLE:
Calling REST web services from a classic asp page
QUESTION:
I'd like to start moving our application business layers into a collection of REST web services. However, most of our Intranet has been built using Classic ASP and most of the developers where I work keep programming in Classic ASP. Ideally, then, for them to benefit from the advantages of a unique set of web APIs, it would have to be called from Classic ASP pages. I haven't the slightest idea how to do that.
ANSWER:
You could use a combination of JQuery with JSON calls to consume REST services from the client or if you need to interact with the REST services from the ASP layer you can use MSXML2.ServerXMLHTTP like: Set HttpReq = Server.CreateObject("MSXML2.ServerXMLHTTP") HttpReq.open "GET", "Rest_URI", False HttpReq.send | [
"web-services",
"rest",
"asp-classic"
] | 29 | 34 | 63,687 | 7 | 0 | 2008-08-14T15:34:26.757000 | 2008-08-14T15:49:27.413000 |
11,263 | 11,271 | Do you know any patterns for GUI programming? (Not patterns on designing GUIs) | I'm looking for patterns that concern coding parts of a GUI. Not as global as MVC, that I'm quite familiar with, but patterns and good ideas and best practices concerning single controls and inputs. Let say I want to make a control that display some objects that may overlap. Now if I click on an object, I need to find out what to do (Just finding the object I can do in several ways, such as an quad-tree and Z-order, thats not the problem). And also I might hold down a modifier key, or some object is active from the beginning, making the selection or whatever a bit more complicated. Should I have an object instance representing a screen object, handle the user-action when clicked, or a master class. etc.. What kind of patterns or solutions are there for problems like this? | I think to be honest you a better just boning up on your standard design patterns and applying them to the individual problems that you face in developing your UI. While there are common UI "themes" (such as dealing with modifier keys) the actual implementation may vary widely. I have O'Reilly's Head First Design Patterns and The Poster, which I have found invaluable! Shameless Plug: These links are using my associates ID. | Do you know any patterns for GUI programming? (Not patterns on designing GUIs) I'm looking for patterns that concern coding parts of a GUI. Not as global as MVC, that I'm quite familiar with, but patterns and good ideas and best practices concerning single controls and inputs. Let say I want to make a control that display some objects that may overlap. Now if I click on an object, I need to find out what to do (Just finding the object I can do in several ways, such as an quad-tree and Z-order, thats not the problem). And also I might hold down a modifier key, or some object is active from the beginning, making the selection or whatever a bit more complicated. Should I have an object instance representing a screen object, handle the user-action when clicked, or a master class. etc.. What kind of patterns or solutions are there for problems like this? | TITLE:
Do you know any patterns for GUI programming? (Not patterns on designing GUIs)
QUESTION:
I'm looking for patterns that concern coding parts of a GUI. Not as global as MVC, that I'm quite familiar with, but patterns and good ideas and best practices concerning single controls and inputs. Let say I want to make a control that display some objects that may overlap. Now if I click on an object, I need to find out what to do (Just finding the object I can do in several ways, such as an quad-tree and Z-order, thats not the problem). And also I might hold down a modifier key, or some object is active from the beginning, making the selection or whatever a bit more complicated. Should I have an object instance representing a screen object, handle the user-action when clicked, or a master class. etc.. What kind of patterns or solutions are there for problems like this?
ANSWER:
I think to be honest you a better just boning up on your standard design patterns and applying them to the individual problems that you face in developing your UI. While there are common UI "themes" (such as dealing with modifier keys) the actual implementation may vary widely. I have O'Reilly's Head First Design Patterns and The Poster, which I have found invaluable! Shameless Plug: These links are using my associates ID. | [
"user-interface",
"design-patterns"
] | 8 | 6 | 9,709 | 6 | 0 | 2008-08-14T16:09:55.030000 | 2008-08-14T16:18:10.553000 |
11,267 | 11,307 | ASP.NET UserControl's and DefaultEvent | Outline OK, I have Google'd this and already expecting a big fat NO!! But I thought I should ask since I know sometimes there can be the odd little gem of knowledge lurking around in peoples heads ^_^ I am working my way through some excercises in a book for study, and this particular exercise is User Controls. I have cobbled together a control and would like to set the DefaultEvent for it (having done this for previous controls) so when I double-click it, the default event created is whatever I specify it to be. NOTE: This is a standard User Control (.ascx), NOT a custom rendered control. Current Code Here is the class & event definition: [System.ComponentModel.DefaultEvent("OKClicked")] public partial class AddressBox: System.Web.UI.UserControl { public event EventHandler OKClicked; Current Result Now, when I double click the the control when it is on a ASPX page, the following is created: protected void AddressBox1_Load(object sender, EventArgs e) {
} Not quite what I was expecting! So, my question: Is it possible to define a DefaultEvent for a UserControl? Is it a hack? If it's [not] supported, is there a reason? Side Note: How do we put underscores in code? I cant seem to put and escape char in? | Here is a possible answer, without testing (like martin did). In reflector, you will see that the DefaultEventAttribute allows itself to be inherited. In reflector, you see that the UserControl class has it's default event set to the Load event. So the possible reason is that even though you are decorating your user control with the default event of OKClick, VS might still be thinking that the default event is load, as it's being inherited from UserControl whose default event is Load. Just a high level guess at what might be happening. | ASP.NET UserControl's and DefaultEvent Outline OK, I have Google'd this and already expecting a big fat NO!! But I thought I should ask since I know sometimes there can be the odd little gem of knowledge lurking around in peoples heads ^_^ I am working my way through some excercises in a book for study, and this particular exercise is User Controls. I have cobbled together a control and would like to set the DefaultEvent for it (having done this for previous controls) so when I double-click it, the default event created is whatever I specify it to be. NOTE: This is a standard User Control (.ascx), NOT a custom rendered control. Current Code Here is the class & event definition: [System.ComponentModel.DefaultEvent("OKClicked")] public partial class AddressBox: System.Web.UI.UserControl { public event EventHandler OKClicked; Current Result Now, when I double click the the control when it is on a ASPX page, the following is created: protected void AddressBox1_Load(object sender, EventArgs e) {
} Not quite what I was expecting! So, my question: Is it possible to define a DefaultEvent for a UserControl? Is it a hack? If it's [not] supported, is there a reason? Side Note: How do we put underscores in code? I cant seem to put and escape char in? | TITLE:
ASP.NET UserControl's and DefaultEvent
QUESTION:
Outline OK, I have Google'd this and already expecting a big fat NO!! But I thought I should ask since I know sometimes there can be the odd little gem of knowledge lurking around in peoples heads ^_^ I am working my way through some excercises in a book for study, and this particular exercise is User Controls. I have cobbled together a control and would like to set the DefaultEvent for it (having done this for previous controls) so when I double-click it, the default event created is whatever I specify it to be. NOTE: This is a standard User Control (.ascx), NOT a custom rendered control. Current Code Here is the class & event definition: [System.ComponentModel.DefaultEvent("OKClicked")] public partial class AddressBox: System.Web.UI.UserControl { public event EventHandler OKClicked; Current Result Now, when I double click the the control when it is on a ASPX page, the following is created: protected void AddressBox1_Load(object sender, EventArgs e) {
} Not quite what I was expecting! So, my question: Is it possible to define a DefaultEvent for a UserControl? Is it a hack? If it's [not] supported, is there a reason? Side Note: How do we put underscores in code? I cant seem to put and escape char in?
ANSWER:
Here is a possible answer, without testing (like martin did). In reflector, you will see that the DefaultEventAttribute allows itself to be inherited. In reflector, you see that the UserControl class has it's default event set to the Load event. So the possible reason is that even though you are decorating your user control with the default event of OKClick, VS might still be thinking that the default event is load, as it's being inherited from UserControl whose default event is Load. Just a high level guess at what might be happening. | [
"c#",
"asp.net",
"user-controls",
"attributes"
] | 5 | 0 | 1,488 | 2 | 0 | 2008-08-14T16:14:36.427000 | 2008-08-14T16:42:13.093000 |
11,275 | 11,421 | Standard Signature a Text in a Message using Exchange Server | Anyone know how to do this without using a third party program? If there no way to do it with a add-on someone can recommend one? EDIT: I need to add this in the server so all users have the same signature. Thanks | You need to create your own exchange message sink to do this. Here's a classic VB example from MS KB: http://support.microsoft.com/kb/317327 and a VB Script one: http://support.microsoft.com/kb/317680 And lots of goodness from MSDN about Exchange 2003 Transport Event Sinks: http://msdn.microsoft.com/en-us/library/ms526223(EXCHG.10).aspx If you're running Exchange 2007 then you can use Transport Rules: http://msexchangeteam.com/archive/2006/12/12/431879.aspx http://www.msexchange.org/tutorials/Using-Transport-Rules-Creating-Disclaimers-Exchange-Server-2007.html | Standard Signature a Text in a Message using Exchange Server Anyone know how to do this without using a third party program? If there no way to do it with a add-on someone can recommend one? EDIT: I need to add this in the server so all users have the same signature. Thanks | TITLE:
Standard Signature a Text in a Message using Exchange Server
QUESTION:
Anyone know how to do this without using a third party program? If there no way to do it with a add-on someone can recommend one? EDIT: I need to add this in the server so all users have the same signature. Thanks
ANSWER:
You need to create your own exchange message sink to do this. Here's a classic VB example from MS KB: http://support.microsoft.com/kb/317327 and a VB Script one: http://support.microsoft.com/kb/317680 And lots of goodness from MSDN about Exchange 2003 Transport Event Sinks: http://msdn.microsoft.com/en-us/library/ms526223(EXCHG.10).aspx If you're running Exchange 2007 then you can use Transport Rules: http://msexchangeteam.com/archive/2006/12/12/431879.aspx http://www.msexchange.org/tutorials/Using-Transport-Rules-Creating-Disclaimers-Exchange-Server-2007.html | [
"outlook",
"exchange-server"
] | 2 | 2 | 3,267 | 2 | 0 | 2008-08-14T16:19:49.613000 | 2008-08-14T17:59:49.753000 |
11,279 | 11,297 | Automatically incremented revision number doesn't show up in the About Box | I have a small VB.NET application that I'm working on using the full version of Visual Studio 2005. In the Publish properties of the project, I have it set to Automatically increment revision with each publish. The issue is that it's only incrementing the revision in the Setup files. It doesn't seem to be updating the version number in the About Box (which is the generic, built-in, About Box template). That version number seems to be coming from My.Application.Info.Version. What should I be using instead so that my automatically incrementing revision number shows up in the about box? | Change the code for the About box to Me.LabelVersion.Text = String.Format("Version {0}", My.Application.Deployment.CurrentVersion.ToString) Please note that all the other answers are correct for "how do I get my assembly version", not the stated question "how do I show my publish version". | Automatically incremented revision number doesn't show up in the About Box I have a small VB.NET application that I'm working on using the full version of Visual Studio 2005. In the Publish properties of the project, I have it set to Automatically increment revision with each publish. The issue is that it's only incrementing the revision in the Setup files. It doesn't seem to be updating the version number in the About Box (which is the generic, built-in, About Box template). That version number seems to be coming from My.Application.Info.Version. What should I be using instead so that my automatically incrementing revision number shows up in the about box? | TITLE:
Automatically incremented revision number doesn't show up in the About Box
QUESTION:
I have a small VB.NET application that I'm working on using the full version of Visual Studio 2005. In the Publish properties of the project, I have it set to Automatically increment revision with each publish. The issue is that it's only incrementing the revision in the Setup files. It doesn't seem to be updating the version number in the About Box (which is the generic, built-in, About Box template). That version number seems to be coming from My.Application.Info.Version. What should I be using instead so that my automatically incrementing revision number shows up in the about box?
ANSWER:
Change the code for the About box to Me.LabelVersion.Text = String.Format("Version {0}", My.Application.Deployment.CurrentVersion.ToString) Please note that all the other answers are correct for "how do I get my assembly version", not the stated question "how do I show my publish version". | [
"vb.net",
"visual-studio"
] | 2 | 1 | 8,594 | 5 | 0 | 2008-08-14T16:25:12.457000 | 2008-08-14T16:35:52.903000 |
11,288 | 23,933 | Sorting a composite collection | So WPF doesn't support standard sorting or filtering behavior for views of CompositeCollections, so what would be a best practice for solving this problem. There are two or more object collections of different types. You want to combine them into a single sortable and filterable collection (withing having to manually implement sort or filter). One of the approaches I've considered is to create a new object collection with only a few core properties, including the ones that I would want the collection sorted on, and an object instance of each type. class MyCompositeObject { enum ObjectType; DateTime CreatedDate; string SomeAttribute; myObjectType1 Obj1; myObjectType2 Obj2; { class MyCompositeObjects: List { } And then loop through my two object collections to build the new composite collection. Obviously this is a bit of a brute force method, but it would work. I'd get all the default view sorting and filtering behavior on my new composite object collection, and I'd be able to put a data template on it to display my list items properly depending on which type is actually stored in that composite item. What suggestions are there for doing this in a more elegant way? | Update: I found a much more elegant solution: class MyCompositeObject { DateTime CreatedDate; string SomeAttribute; Object Obj1; { class MyCompositeObjects: List { } I found that due to reflection, the specific type stored in Obj1 is resolved at runtime and the type specific DataTemplate is applied as expected! | Sorting a composite collection So WPF doesn't support standard sorting or filtering behavior for views of CompositeCollections, so what would be a best practice for solving this problem. There are two or more object collections of different types. You want to combine them into a single sortable and filterable collection (withing having to manually implement sort or filter). One of the approaches I've considered is to create a new object collection with only a few core properties, including the ones that I would want the collection sorted on, and an object instance of each type. class MyCompositeObject { enum ObjectType; DateTime CreatedDate; string SomeAttribute; myObjectType1 Obj1; myObjectType2 Obj2; { class MyCompositeObjects: List { } And then loop through my two object collections to build the new composite collection. Obviously this is a bit of a brute force method, but it would work. I'd get all the default view sorting and filtering behavior on my new composite object collection, and I'd be able to put a data template on it to display my list items properly depending on which type is actually stored in that composite item. What suggestions are there for doing this in a more elegant way? | TITLE:
Sorting a composite collection
QUESTION:
So WPF doesn't support standard sorting or filtering behavior for views of CompositeCollections, so what would be a best practice for solving this problem. There are two or more object collections of different types. You want to combine them into a single sortable and filterable collection (withing having to manually implement sort or filter). One of the approaches I've considered is to create a new object collection with only a few core properties, including the ones that I would want the collection sorted on, and an object instance of each type. class MyCompositeObject { enum ObjectType; DateTime CreatedDate; string SomeAttribute; myObjectType1 Obj1; myObjectType2 Obj2; { class MyCompositeObjects: List { } And then loop through my two object collections to build the new composite collection. Obviously this is a bit of a brute force method, but it would work. I'd get all the default view sorting and filtering behavior on my new composite object collection, and I'd be able to put a data template on it to display my list items properly depending on which type is actually stored in that composite item. What suggestions are there for doing this in a more elegant way?
ANSWER:
Update: I found a much more elegant solution: class MyCompositeObject { DateTime CreatedDate; string SomeAttribute; Object Obj1; { class MyCompositeObjects: List { } I found that due to reflection, the specific type stored in Obj1 is resolved at runtime and the type specific DataTemplate is applied as expected! | [
"c#",
".net",
"wpf",
"data-binding",
"collections"
] | 7 | 1 | 8,441 | 3 | 0 | 2008-08-14T16:30:49.933000 | 2008-08-23T03:48:11.093000 |
11,291 | 11,312 | Best way to capture key events in NSTextView? | I'm slowly learning Objective-C and Cocoa, and the only way I see so far to capture key events in Text Views is to use delegation, but I'm having trouble finding useful documentation and examples on how to implement such a solution. Can anyone point me in the right direction or supply some first-hand help? | Generally, the way you implement it is simply to add the required function to your view's controller, and set its delegate. For example, if you want code to run when the view loads, you just delegate your view to the controller, and implement the awakeFromNib function. So, to detect a key press in a text view, make sure your controller is the text view's delegate, and then implement this: - (void)keyUp:(NSEvent *)theEvent Note that this is an inherited NSResponder method, not a NSTextView method. | Best way to capture key events in NSTextView? I'm slowly learning Objective-C and Cocoa, and the only way I see so far to capture key events in Text Views is to use delegation, but I'm having trouble finding useful documentation and examples on how to implement such a solution. Can anyone point me in the right direction or supply some first-hand help? | TITLE:
Best way to capture key events in NSTextView?
QUESTION:
I'm slowly learning Objective-C and Cocoa, and the only way I see so far to capture key events in Text Views is to use delegation, but I'm having trouble finding useful documentation and examples on how to implement such a solution. Can anyone point me in the right direction or supply some first-hand help?
ANSWER:
Generally, the way you implement it is simply to add the required function to your view's controller, and set its delegate. For example, if you want code to run when the view loads, you just delegate your view to the controller, and implement the awakeFromNib function. So, to detect a key press in a text view, make sure your controller is the text view's delegate, and then implement this: - (void)keyUp:(NSEvent *)theEvent Note that this is an inherited NSResponder method, not a NSTextView method. | [
"objective-c",
"cocoa",
"events"
] | 16 | 14 | 6,700 | 4 | 0 | 2008-08-14T16:32:22.957000 | 2008-08-14T16:43:05.883000 |
11,305 | 11,325 | How to parse XML using vba | I work in VBA, and want to parse a string eg 24.365 78.63 and get the X & Y values into two separate integer variables. I'm a newbie when it comes to XML, since I'm stuck in VB6 and VBA, because of the field I work in. How do I do this? | This is a bit of a complicated question, but it seems like the most direct route would be to load the XML document or XML string via MSXML2.DOMDocument which will then allow you to access the XML nodes. You can find more on MSXML2.DOMDocument at the following sites: Manipulating XML files with Excel VBA & Xpath MSXML - http://msdn.microsoft.com/en-us/library/ms763742(VS.85).aspx An Overview of MSXML 4.0 | How to parse XML using vba I work in VBA, and want to parse a string eg 24.365 78.63 and get the X & Y values into two separate integer variables. I'm a newbie when it comes to XML, since I'm stuck in VB6 and VBA, because of the field I work in. How do I do this? | TITLE:
How to parse XML using vba
QUESTION:
I work in VBA, and want to parse a string eg 24.365 78.63 and get the X & Y values into two separate integer variables. I'm a newbie when it comes to XML, since I'm stuck in VB6 and VBA, because of the field I work in. How do I do this?
ANSWER:
This is a bit of a complicated question, but it seems like the most direct route would be to load the XML document or XML string via MSXML2.DOMDocument which will then allow you to access the XML nodes. You can find more on MSXML2.DOMDocument at the following sites: Manipulating XML files with Excel VBA & Xpath MSXML - http://msdn.microsoft.com/en-us/library/ms763742(VS.85).aspx An Overview of MSXML 4.0 | [
"xml",
"vba",
"parsing",
"xml-parsing"
] | 87 | 57 | 416,323 | 8 | 0 | 2008-08-14T16:41:25.903000 | 2008-08-14T16:47:07.437000 |
11,311 | 11,323 | Formatting text in WinForm Label | Is it possible to format certain text in a WinForm Label instead of breaking the text into multiple labels? Please disregard the HTML tags within the label's text; it's only used to get my point out. For example: Dim myLabel As New Label myLabel.Text = "This is bold text. This is italicized text." Which would produce the text in the label as: This is bold text. This is italicized text. | That's not possible with a WinForms label as it is. The label has to have exactly one font, with exactly one size and one face. You have a couple of options: Use separate labels Create a new Control-derived class that does its own drawing via GDI+ and use that instead of Label; this is probably your best option, as it gives you complete control over how to instruct the control to format its text Use a third-party label control that will let you insert HTML snippets (there are a bunch - check CodeProject); this would be someone else's implementation of #2. | Formatting text in WinForm Label Is it possible to format certain text in a WinForm Label instead of breaking the text into multiple labels? Please disregard the HTML tags within the label's text; it's only used to get my point out. For example: Dim myLabel As New Label myLabel.Text = "This is bold text. This is italicized text." Which would produce the text in the label as: This is bold text. This is italicized text. | TITLE:
Formatting text in WinForm Label
QUESTION:
Is it possible to format certain text in a WinForm Label instead of breaking the text into multiple labels? Please disregard the HTML tags within the label's text; it's only used to get my point out. For example: Dim myLabel As New Label myLabel.Text = "This is bold text. This is italicized text." Which would produce the text in the label as: This is bold text. This is italicized text.
ANSWER:
That's not possible with a WinForms label as it is. The label has to have exactly one font, with exactly one size and one face. You have a couple of options: Use separate labels Create a new Control-derived class that does its own drawing via GDI+ and use that instead of Label; this is probably your best option, as it gives you complete control over how to instruct the control to format its text Use a third-party label control that will let you insert HTML snippets (there are a bunch - check CodeProject); this would be someone else's implementation of #2. | [
"winforms",
"text",
"formatting",
"label"
] | 23 | 19 | 55,967 | 12 | 0 | 2008-08-14T16:43:03.903000 | 2008-08-14T16:45:50.810000 |
11,318 | 11,404 | Simple animation in WinForms | Imagine you want to animate some object on a WinForm. You setup a timer to update the state or model, and override the paint event of the Form. But from there, what's the best way to continually repaint the Form for the animation? Invalidate the Form as soon as you are done drawing? Setup a second timer and invalidate the form on a regular interval? Perhaps there is a common pattern for this thing? Are there any useful.NET classes to help out? Each time I need to do this I discover a new method with a new drawback. What are the experiences and recommendations from the SO community? | In some situations, it's faster and more convenient to not draw using the paint event, but getting the Graphics object from the control/form and painting "on" that. This may give some troubles with opacity/anti aliasing/text etc, but could be worth the trouble in terms of not having to repaint the whole shabang. Something along the lines of: private void AnimationTimer_Tick(object sender, EventArgs args) { // First paint background, like Clear(Control.Background), or by // painting an image you have previously buffered that was the background. animationControl.CreateGraphics().DrawImage(0, 0, animationImages[animationTick++])); } I use this in some Controls myself, and have buffered images to "clear" the background with, when the object of interest moves or need to be removed. | Simple animation in WinForms Imagine you want to animate some object on a WinForm. You setup a timer to update the state or model, and override the paint event of the Form. But from there, what's the best way to continually repaint the Form for the animation? Invalidate the Form as soon as you are done drawing? Setup a second timer and invalidate the form on a regular interval? Perhaps there is a common pattern for this thing? Are there any useful.NET classes to help out? Each time I need to do this I discover a new method with a new drawback. What are the experiences and recommendations from the SO community? | TITLE:
Simple animation in WinForms
QUESTION:
Imagine you want to animate some object on a WinForm. You setup a timer to update the state or model, and override the paint event of the Form. But from there, what's the best way to continually repaint the Form for the animation? Invalidate the Form as soon as you are done drawing? Setup a second timer and invalidate the form on a regular interval? Perhaps there is a common pattern for this thing? Are there any useful.NET classes to help out? Each time I need to do this I discover a new method with a new drawback. What are the experiences and recommendations from the SO community?
ANSWER:
In some situations, it's faster and more convenient to not draw using the paint event, but getting the Graphics object from the control/form and painting "on" that. This may give some troubles with opacity/anti aliasing/text etc, but could be worth the trouble in terms of not having to repaint the whole shabang. Something along the lines of: private void AnimationTimer_Tick(object sender, EventArgs args) { // First paint background, like Clear(Control.Background), or by // painting an image you have previously buffered that was the background. animationControl.CreateGraphics().DrawImage(0, 0, animationImages[animationTick++])); } I use this in some Controls myself, and have buffered images to "clear" the background with, when the object of interest moves or need to be removed. | [
".net",
"winforms",
"animation"
] | 25 | 9 | 30,182 | 3 | 0 | 2008-08-14T16:44:42.060000 | 2008-08-14T17:39:43.307000 |
11,341 | 13,431 | Create PDFs from multipage forms in WebObjects | I would like to automatically generate PDF documents from WebObjects based on mulitpage forms. Assuming I have a class which can assemble the related forms (java/wod files) is there a good way to then parse the individual forms into a PDF instead of going to the screen? | The canonical response when asked about PDFs from WebObjects has generally been ReportMill. It's a PDF document generating framework that works a lot like WebObjects, and includes its own graphical PDF builder tool similar to WebObjects Builder and Interface Builder. You can bind elements in your generated PDFs to dynamic data in your application just as you would for a WOComponent. They have couple of tutorial videos on the ReportMill product page that should give you an idea of how the tool works. It'll probably be a lot easier than trying to work with FOP programmatically. | Create PDFs from multipage forms in WebObjects I would like to automatically generate PDF documents from WebObjects based on mulitpage forms. Assuming I have a class which can assemble the related forms (java/wod files) is there a good way to then parse the individual forms into a PDF instead of going to the screen? | TITLE:
Create PDFs from multipage forms in WebObjects
QUESTION:
I would like to automatically generate PDF documents from WebObjects based on mulitpage forms. Assuming I have a class which can assemble the related forms (java/wod files) is there a good way to then parse the individual forms into a PDF instead of going to the screen?
ANSWER:
The canonical response when asked about PDFs from WebObjects has generally been ReportMill. It's a PDF document generating framework that works a lot like WebObjects, and includes its own graphical PDF builder tool similar to WebObjects Builder and Interface Builder. You can bind elements in your generated PDFs to dynamic data in your application just as you would for a WOComponent. They have couple of tutorial videos on the ReportMill product page that should give you an idea of how the tool works. It'll probably be a lot easier than trying to work with FOP programmatically. | [
"java",
"pdf",
"webobjects"
] | 2 | 2 | 829 | 6 | 0 | 2008-08-14T17:06:46.493000 | 2008-08-17T00:40:16.287000 |
11,345 | 149,088 | XPATHS and Default Namespaces | What is the story behind XPath and support for namespaces? Did XPath as a specification precede namespaces? If I have a document where elements have been given a default namespace: It appears as though some of the XPath processor libraries won't recognize //foo because of the namespace whereas others will. The option my team has thought about is to add a namespace prefix using regular expressions to the XPath (you can add a namespace prefix via XmlNameTable) but this seems brittle since XPath is such a flexible language when it comes to node tests. Is there a standard that applies to this? My approach is a bit hackish but it seems to work fine; I remove the xmlns declaration with a search/replace and then apply XPath. string readyForXpath = Regex.Replace(xmldocument, "xmlns=\".+\"", String.Empty ); Is that a fair approach or has anyone solved this differently? | I tried something similar to what palehorse proposed and could not get it to work. Since I was getting data from a published service I couldn't change the xml. I ended up using XmlDocument and XmlNamespaceManager like so: XmlDocument doc = new XmlDocument(); doc.LoadXml(xmlWithBogusNamespace); XmlNamespaceManager nSpace = new XmlNamespaceManager(doc.NameTable); nSpace.AddNamespace("myNs", "http://theirUri");
XmlNodeList nodes = doc.SelectNodes("//myNs:NodesIWant",nSpace); //etc | XPATHS and Default Namespaces What is the story behind XPath and support for namespaces? Did XPath as a specification precede namespaces? If I have a document where elements have been given a default namespace: It appears as though some of the XPath processor libraries won't recognize //foo because of the namespace whereas others will. The option my team has thought about is to add a namespace prefix using regular expressions to the XPath (you can add a namespace prefix via XmlNameTable) but this seems brittle since XPath is such a flexible language when it comes to node tests. Is there a standard that applies to this? My approach is a bit hackish but it seems to work fine; I remove the xmlns declaration with a search/replace and then apply XPath. string readyForXpath = Regex.Replace(xmldocument, "xmlns=\".+\"", String.Empty ); Is that a fair approach or has anyone solved this differently? | TITLE:
XPATHS and Default Namespaces
QUESTION:
What is the story behind XPath and support for namespaces? Did XPath as a specification precede namespaces? If I have a document where elements have been given a default namespace: It appears as though some of the XPath processor libraries won't recognize //foo because of the namespace whereas others will. The option my team has thought about is to add a namespace prefix using regular expressions to the XPath (you can add a namespace prefix via XmlNameTable) but this seems brittle since XPath is such a flexible language when it comes to node tests. Is there a standard that applies to this? My approach is a bit hackish but it seems to work fine; I remove the xmlns declaration with a search/replace and then apply XPath. string readyForXpath = Regex.Replace(xmldocument, "xmlns=\".+\"", String.Empty ); Is that a fair approach or has anyone solved this differently?
ANSWER:
I tried something similar to what palehorse proposed and could not get it to work. Since I was getting data from a published service I couldn't change the xml. I ended up using XmlDocument and XmlNamespaceManager like so: XmlDocument doc = new XmlDocument(); doc.LoadXml(xmlWithBogusNamespace); XmlNamespaceManager nSpace = new XmlNamespaceManager(doc.NameTable); nSpace.AddNamespace("myNs", "http://theirUri");
XmlNodeList nodes = doc.SelectNodes("//myNs:NodesIWant",nSpace); //etc | [
"c#",
"xml",
"xpath",
"namespaces"
] | 17 | 10 | 10,924 | 5 | 0 | 2008-08-14T17:09:43.867000 | 2008-09-29T15:09:35.493000 |
11,359 | 92,557 | What is good server performance monitoring software for Windows? | I'm looking for some software to monitor a single server for performance alerts. Preferably free and with a reasonable default configuration. Edit: To clarify, I would like to run this software on a Windows machine and monitor a remote Windows server for CPU/memory/etc. usage alerts (not a single application). Edit: I suppose its not necessary that this software be run remotely, I would also settle for something that ran on the server and emailed me if there was an alert. It seems like Windows performance logs and alerts might be used for this purpose somehow but it was not immediately obvious to me. Edit: Found a neat tool on the coding horror blog, not as useful for remote monitoring but very useful for things you would worry about as a server admin: http://www.winsupersite.com/showcase/winvista_ff_rmon.asp | For performance monitor - start it on the server ( Win + R and enter "perfmon"). Select "Performance Logs and Alerts" and expand. Select "Alerts". Select "Action" & then "New Alert". Give the alert a name, click "Add" to add a counter (there are hundres of counters, for example CPU %), then give it some limits. Select the "Action" tab, and then decide what you want to do. You may need a third party program - for example Blat to send emails - but basiaclly any script can be run. | What is good server performance monitoring software for Windows? I'm looking for some software to monitor a single server for performance alerts. Preferably free and with a reasonable default configuration. Edit: To clarify, I would like to run this software on a Windows machine and monitor a remote Windows server for CPU/memory/etc. usage alerts (not a single application). Edit: I suppose its not necessary that this software be run remotely, I would also settle for something that ran on the server and emailed me if there was an alert. It seems like Windows performance logs and alerts might be used for this purpose somehow but it was not immediately obvious to me. Edit: Found a neat tool on the coding horror blog, not as useful for remote monitoring but very useful for things you would worry about as a server admin: http://www.winsupersite.com/showcase/winvista_ff_rmon.asp | TITLE:
What is good server performance monitoring software for Windows?
QUESTION:
I'm looking for some software to monitor a single server for performance alerts. Preferably free and with a reasonable default configuration. Edit: To clarify, I would like to run this software on a Windows machine and monitor a remote Windows server for CPU/memory/etc. usage alerts (not a single application). Edit: I suppose its not necessary that this software be run remotely, I would also settle for something that ran on the server and emailed me if there was an alert. It seems like Windows performance logs and alerts might be used for this purpose somehow but it was not immediately obvious to me. Edit: Found a neat tool on the coding horror blog, not as useful for remote monitoring but very useful for things you would worry about as a server admin: http://www.winsupersite.com/showcase/winvista_ff_rmon.asp
ANSWER:
For performance monitor - start it on the server ( Win + R and enter "perfmon"). Select "Performance Logs and Alerts" and expand. Select "Alerts". Select "Action" & then "New Alert". Give the alert a name, click "Add" to add a counter (there are hundres of counters, for example CPU %), then give it some limits. Select the "Action" tab, and then decide what you want to do. You may need a third party program - for example Blat to send emails - but basiaclly any script can be run. | [
"windows",
"performance",
"system-administration"
] | 8 | 2 | 18,233 | 7 | 0 | 2008-08-14T17:17:30.013000 | 2008-09-18T13:33:17.007000 |
11,381 | 11,413 | Making human readable representations of an Integer | Here's a coding problem for those that like this kind of thing. Let's see your implementations (in your language of choice, of course) of a function which returns a human readable String representation of a specified Integer. For example: humanReadable(1) returns "one". humanReadable(53) returns "fifty-three". humanReadable(723603) returns "seven hundred and twenty-three thousand, six hundred and three". humanReadable(1456376562) returns "one billion, four hundred and fifty-six million, three hundred and seventy-six thousand, five hundred and sixty-two". Bonus points for particularly clever/elegant solutions! It might seem like a pointless exercise, but there are number of real world applications for this kind of algorithm (although supporting numbers as high as a billion may be overkill:-) | There was already a question about this: Convert integers to written numbers The answer is for C#, but I think you can figure it out. | Making human readable representations of an Integer Here's a coding problem for those that like this kind of thing. Let's see your implementations (in your language of choice, of course) of a function which returns a human readable String representation of a specified Integer. For example: humanReadable(1) returns "one". humanReadable(53) returns "fifty-three". humanReadable(723603) returns "seven hundred and twenty-three thousand, six hundred and three". humanReadable(1456376562) returns "one billion, four hundred and fifty-six million, three hundred and seventy-six thousand, five hundred and sixty-two". Bonus points for particularly clever/elegant solutions! It might seem like a pointless exercise, but there are number of real world applications for this kind of algorithm (although supporting numbers as high as a billion may be overkill:-) | TITLE:
Making human readable representations of an Integer
QUESTION:
Here's a coding problem for those that like this kind of thing. Let's see your implementations (in your language of choice, of course) of a function which returns a human readable String representation of a specified Integer. For example: humanReadable(1) returns "one". humanReadable(53) returns "fifty-three". humanReadable(723603) returns "seven hundred and twenty-three thousand, six hundred and three". humanReadable(1456376562) returns "one billion, four hundred and fifty-six million, three hundred and seventy-six thousand, five hundred and sixty-two". Bonus points for particularly clever/elegant solutions! It might seem like a pointless exercise, but there are number of real world applications for this kind of algorithm (although supporting numbers as high as a billion may be overkill:-)
ANSWER:
There was already a question about this: Convert integers to written numbers The answer is for C#, but I think you can figure it out. | [
"algorithm",
"numbers"
] | 5 | 8 | 2,226 | 6 | 0 | 2008-08-14T17:25:29.747000 | 2008-08-14T17:49:35.190000 |
11,405 | 11,414 | GCC issue: using a member of a base class that depends on a template argument | The following code doesn't compile with gcc, but does with Visual Studio: template class A { public: T foo; };
template class B: public A { public: void bar() { cout << foo << endl; } }; I get the error: test.cpp: In member function ‘void B::bar()’: test.cpp:11: error: ‘foo’ was not declared in this scope But it should be! If I change bar to void bar() { cout << this->foo << endl; } then it does compile, but I don't think I have to do this. Is there something in the official specs of C++ that GCC is following here, or is it just a quirk? | This changed in gcc-3.4. The C++ parser got much more strict in that release -- per the spec but still kinda annoying for people with legacy or multi-platform code bases. | GCC issue: using a member of a base class that depends on a template argument The following code doesn't compile with gcc, but does with Visual Studio: template class A { public: T foo; };
template class B: public A { public: void bar() { cout << foo << endl; } }; I get the error: test.cpp: In member function ‘void B::bar()’: test.cpp:11: error: ‘foo’ was not declared in this scope But it should be! If I change bar to void bar() { cout << this->foo << endl; } then it does compile, but I don't think I have to do this. Is there something in the official specs of C++ that GCC is following here, or is it just a quirk? | TITLE:
GCC issue: using a member of a base class that depends on a template argument
QUESTION:
The following code doesn't compile with gcc, but does with Visual Studio: template class A { public: T foo; };
template class B: public A { public: void bar() { cout << foo << endl; } }; I get the error: test.cpp: In member function ‘void B::bar()’: test.cpp:11: error: ‘foo’ was not declared in this scope But it should be! If I change bar to void bar() { cout << this->foo << endl; } then it does compile, but I don't think I have to do this. Is there something in the official specs of C++ that GCC is following here, or is it just a quirk?
ANSWER:
This changed in gcc-3.4. The C++ parser got much more strict in that release -- per the spec but still kinda annoying for people with legacy or multi-platform code bases. | [
"c++",
"templates",
"base-class",
"class-members",
"name-lookup"
] | 37 | 12 | 8,267 | 5 | 0 | 2008-08-14T17:39:46.520000 | 2008-08-14T17:50:24.750000 |
11,423 | 11,428 | How to host a WPF form in a MFC application | I'm looking for any resources on hosting a WPF form within an existing MFC application. Can anyone point me in the right direction on how to do this? | From what I understand (haven't tried myself), it's almost as simple as just giving the WPF control the parent's handle. Here's a Walkthrough: Hosting WPF Content in Win32. | How to host a WPF form in a MFC application I'm looking for any resources on hosting a WPF form within an existing MFC application. Can anyone point me in the right direction on how to do this? | TITLE:
How to host a WPF form in a MFC application
QUESTION:
I'm looking for any resources on hosting a WPF form within an existing MFC application. Can anyone point me in the right direction on how to do this?
ANSWER:
From what I understand (haven't tried myself), it's almost as simple as just giving the WPF control the parent's handle. Here's a Walkthrough: Hosting WPF Content in Win32. | [
"c#",
"wpf",
"mfc"
] | 13 | 5 | 4,702 | 1 | 0 | 2008-08-14T18:04:45.237000 | 2008-08-14T18:06:36.700000 |
11,430 | 11,436 | What version of .Net framework ships with SQL Server 2008? | Does SQL Server 2008 ship with the.NET 3.5 CLR, so that stored procedures written in CLR can use 3.5 features? | Actually it ships with.NET 3.5 SP1. So yes, the stored procs can use 3.5 features and libraries. | What version of .Net framework ships with SQL Server 2008? Does SQL Server 2008 ship with the.NET 3.5 CLR, so that stored procedures written in CLR can use 3.5 features? | TITLE:
What version of .Net framework ships with SQL Server 2008?
QUESTION:
Does SQL Server 2008 ship with the.NET 3.5 CLR, so that stored procedures written in CLR can use 3.5 features?
ANSWER:
Actually it ships with.NET 3.5 SP1. So yes, the stored procs can use 3.5 features and libraries. | [
"sql-server",
"sql-server-2008"
] | 6 | 10 | 2,724 | 2 | 0 | 2008-08-14T18:08:00.567000 | 2008-08-14T18:09:59.627000 |
11,439 | 11,447 | Visual Studio Setup Project Custom Dialog | I have created a custom dialog for Visual Studio Setup Project using the steps described here Now I have a combobox in one of my dialogs. I want to populate the combobox with a list of all SQL Server instances running on the local network. It's trivial to get the server list... but I'm completely lost on how to make them display in the combobox. I would appreciate your help and some code might also be nice as I'm beginner:). | I've always found the custom dialogs in visual studio setup projects to be woefully limited and barely functional. By contrast, I normally create custom actions that display winforms gui's for any remotely difficult tasks during setup. Works really well and you can do just about anything you want by creating a custom action and passing a few parameters across. In the dayjob we built a collection of common custom actions for tasks like application config and database creation / script execution to get around custom dialog limitations. | Visual Studio Setup Project Custom Dialog I have created a custom dialog for Visual Studio Setup Project using the steps described here Now I have a combobox in one of my dialogs. I want to populate the combobox with a list of all SQL Server instances running on the local network. It's trivial to get the server list... but I'm completely lost on how to make them display in the combobox. I would appreciate your help and some code might also be nice as I'm beginner:). | TITLE:
Visual Studio Setup Project Custom Dialog
QUESTION:
I have created a custom dialog for Visual Studio Setup Project using the steps described here Now I have a combobox in one of my dialogs. I want to populate the combobox with a list of all SQL Server instances running on the local network. It's trivial to get the server list... but I'm completely lost on how to make them display in the combobox. I would appreciate your help and some code might also be nice as I'm beginner:).
ANSWER:
I've always found the custom dialogs in visual studio setup projects to be woefully limited and barely functional. By contrast, I normally create custom actions that display winforms gui's for any remotely difficult tasks during setup. Works really well and you can do just about anything you want by creating a custom action and passing a few parameters across. In the dayjob we built a collection of common custom actions for tasks like application config and database creation / script execution to get around custom dialog limitations. | [
".net",
"visual-studio",
"windows-installer",
"installation",
"projects"
] | 6 | 13 | 18,363 | 2 | 0 | 2008-08-14T18:11:31.400000 | 2008-08-14T18:17:36.613000 |
11,460 | 11,472 | ASP.NET Proxy Application | Let me try to explain what I need. I have a server that is visible from the internet. What I need is to create a ASP.NET application that get the request of a web Site and send to a internal server, then it gets the response and publish the the info. For the client this should be totally transparent. For different reasons I cannot redirect the port to the internal server. What I can do but no know how - maybe the answer is there - is to create a new Web Site that its host in the other server. | Why won't any old proxy software work for this? Why does it need to be an ASP.NET application? There are TONS of tools out there (both Windows and *nix) that will get the job done quite easily. Check Squid or NetProxy for starters. If you need to integrate with IIS, IISProxy looks like it would do the trick too. | ASP.NET Proxy Application Let me try to explain what I need. I have a server that is visible from the internet. What I need is to create a ASP.NET application that get the request of a web Site and send to a internal server, then it gets the response and publish the the info. For the client this should be totally transparent. For different reasons I cannot redirect the port to the internal server. What I can do but no know how - maybe the answer is there - is to create a new Web Site that its host in the other server. | TITLE:
ASP.NET Proxy Application
QUESTION:
Let me try to explain what I need. I have a server that is visible from the internet. What I need is to create a ASP.NET application that get the request of a web Site and send to a internal server, then it gets the response and publish the the info. For the client this should be totally transparent. For different reasons I cannot redirect the port to the internal server. What I can do but no know how - maybe the answer is there - is to create a new Web Site that its host in the other server.
ANSWER:
Why won't any old proxy software work for this? Why does it need to be an ASP.NET application? There are TONS of tools out there (both Windows and *nix) that will get the job done quite easily. Check Squid or NetProxy for starters. If you need to integrate with IIS, IISProxy looks like it would do the trick too. | [
".net",
"asp.net",
"iis"
] | 3 | 3 | 1,811 | 2 | 0 | 2008-08-14T18:28:42.990000 | 2008-08-14T18:38:24.513000 |
11,462 | 4,500,707 | Sharepoint Wikis | Ok, I've seen a few posts that mention a few other posts about not using SP wikis because they suck. Since we are looking at doing our wiki in SP, I need to know why we shouldn't do it for a group of 6 automation-developers to document the steps in various automated processes and the changes that have to be made from time to time. | Before the rant, here is my overall experience with SharePoint as a wiki. It is a poorly implemented feature that failed becouse there was a fundemental lack of investigation into what current wiki environments provide. That is why it failed in it's editor and why it misses on points like: tagging, history comparison, and poorly generated html code. You need to skip it and get something else that does the job better and link to it from SharePoint. Having production experience with both products, I'd recommend ScrewTurn over SharePoint. see edit history for rant | Sharepoint Wikis Ok, I've seen a few posts that mention a few other posts about not using SP wikis because they suck. Since we are looking at doing our wiki in SP, I need to know why we shouldn't do it for a group of 6 automation-developers to document the steps in various automated processes and the changes that have to be made from time to time. | TITLE:
Sharepoint Wikis
QUESTION:
Ok, I've seen a few posts that mention a few other posts about not using SP wikis because they suck. Since we are looking at doing our wiki in SP, I need to know why we shouldn't do it for a group of 6 automation-developers to document the steps in various automated processes and the changes that have to be made from time to time.
ANSWER:
Before the rant, here is my overall experience with SharePoint as a wiki. It is a poorly implemented feature that failed becouse there was a fundemental lack of investigation into what current wiki environments provide. That is why it failed in it's editor and why it misses on points like: tagging, history comparison, and poorly generated html code. You need to skip it and get something else that does the job better and link to it from SharePoint. Having production experience with both products, I'd recommend ScrewTurn over SharePoint. see edit history for rant | [
"sharepoint",
"automation",
"sharepoint-wiki"
] | 23 | 5 | 20,406 | 17 | 0 | 2008-08-14T18:30:01.160000 | 2010-12-21T15:13:23.837000 |
11,491 | 11,502 | String To Lower/Upper in C++ | What is the best way people have found to do String to Lower case / Upper case in C++? The issue is complicated by the fact that C++ isn't an English only programming language. Is there a good multilingual method? | #include std::string data = "Abc"; std::transform(data.begin(), data.end(), data.begin(),::toupper); http://notfaq.wordpress.com/2007/08/04/cc-convert-string-to-upperlower-case/ Also, CodeProject article for common string methods: http://www.codeproject.com/KB/stl/STL_string_util.aspx | String To Lower/Upper in C++ What is the best way people have found to do String to Lower case / Upper case in C++? The issue is complicated by the fact that C++ isn't an English only programming language. Is there a good multilingual method? | TITLE:
String To Lower/Upper in C++
QUESTION:
What is the best way people have found to do String to Lower case / Upper case in C++? The issue is complicated by the fact that C++ isn't an English only programming language. Is there a good multilingual method?
ANSWER:
#include std::string data = "Abc"; std::transform(data.begin(), data.end(), data.begin(),::toupper); http://notfaq.wordpress.com/2007/08/04/cc-convert-string-to-upperlower-case/ Also, CodeProject article for common string methods: http://www.codeproject.com/KB/stl/STL_string_util.aspx | [
"c++",
"string",
"unicode"
] | 27 | 32 | 31,102 | 10 | 0 | 2008-08-14T18:49:47.703000 | 2008-08-14T18:53:43.530000 |
11,500 | 11,521 | Speeding up an ASP.Net Web Site or Application | I have an Ajax.Net enabled ASP.Net 2.0 web site. Hosting for both the site and the database are out of my control as is the database's schema. In testing on hardware I do control the site performs well however on the client's hardware, there are noticeable delays when reloading or changing pages. What I would like to do is make my application as compact and speedy as possible when I deliver it. One idea is to set expiration dates for all of the site's static resources so they aren't recalled on page loads. By resources I mean images, linked style sheets and JavaScript source files. Is there an easy way to do this? What other ways are there to optimize a.Net web site? UPDATE: I've run YSlow on the site and the areas where I am getting hit the hardest are in the number of JavaScript and Style Sheets being loaded (23 JS files and 5 style sheets). All but one (the main style sheet) has been inserted by Ajax.net and Asp. Why so many? | Script Combining in.net 3.5 SP1 Best Practices for fast websites HTTP Compression (gzip) Compress JS / CSS (different than http compression, minify javascript) YUI Compressor.NET YUI Compressor My best advice is to check out the YUI content. They have some great articles that talk about things like CSS sprites and have some nice javascript libraries to help reduce the number of requests the browser is making. | Speeding up an ASP.Net Web Site or Application I have an Ajax.Net enabled ASP.Net 2.0 web site. Hosting for both the site and the database are out of my control as is the database's schema. In testing on hardware I do control the site performs well however on the client's hardware, there are noticeable delays when reloading or changing pages. What I would like to do is make my application as compact and speedy as possible when I deliver it. One idea is to set expiration dates for all of the site's static resources so they aren't recalled on page loads. By resources I mean images, linked style sheets and JavaScript source files. Is there an easy way to do this? What other ways are there to optimize a.Net web site? UPDATE: I've run YSlow on the site and the areas where I am getting hit the hardest are in the number of JavaScript and Style Sheets being loaded (23 JS files and 5 style sheets). All but one (the main style sheet) has been inserted by Ajax.net and Asp. Why so many? | TITLE:
Speeding up an ASP.Net Web Site or Application
QUESTION:
I have an Ajax.Net enabled ASP.Net 2.0 web site. Hosting for both the site and the database are out of my control as is the database's schema. In testing on hardware I do control the site performs well however on the client's hardware, there are noticeable delays when reloading or changing pages. What I would like to do is make my application as compact and speedy as possible when I deliver it. One idea is to set expiration dates for all of the site's static resources so they aren't recalled on page loads. By resources I mean images, linked style sheets and JavaScript source files. Is there an easy way to do this? What other ways are there to optimize a.Net web site? UPDATE: I've run YSlow on the site and the areas where I am getting hit the hardest are in the number of JavaScript and Style Sheets being loaded (23 JS files and 5 style sheets). All but one (the main style sheet) has been inserted by Ajax.net and Asp. Why so many?
ANSWER:
Script Combining in.net 3.5 SP1 Best Practices for fast websites HTTP Compression (gzip) Compress JS / CSS (different than http compression, minify javascript) YUI Compressor.NET YUI Compressor My best advice is to check out the YUI content. They have some great articles that talk about things like CSS sprites and have some nice javascript libraries to help reduce the number of requests the browser is making. | [
"asp.net",
"ajax",
"optimization",
"performance"
] | 25 | 22 | 3,351 | 12 | 0 | 2008-08-14T18:52:54.017000 | 2008-08-14T19:03:58.720000 |
11,514 | 53,412 | Is it possible to be ambikeyboardrous? | I switched to the dvorak keyboard layout about a year ago. I now use dvorak full-time at work and at home. Recently, I went on vacation to Peru and found myself in quite a conundrum. Internet cafes were qwerty-only (and Spanish qwerty, at that). I was stuck with a hunt-and-peck routine that grew old fairly quickly. That said, is it possible to be "fluent" in both qwerty and dvorak at the same time? If not, are there any good solutions to the situation I found myself in? | Web For your situation of being at a public computer that you cannot switch the keyboard layout on, you can go to this website: http://www.dvzine.org/type/DVconverter.html Use this to translate your typing and then use copy paste. I found this very useful when I was out of the country and had to write a bunch of emails at public computers. USB Drive Put this Dvorak Utility on your USB drive. Run this app and it will put a icon in the system tray on windows. This icon will switch the computer between the two keyboard layouts and it works. (If you have tried switching back and forth from dvorak to qwerty you will know what I mean. Windows does the worst job of this one bit of functionality.) | Is it possible to be ambikeyboardrous? I switched to the dvorak keyboard layout about a year ago. I now use dvorak full-time at work and at home. Recently, I went on vacation to Peru and found myself in quite a conundrum. Internet cafes were qwerty-only (and Spanish qwerty, at that). I was stuck with a hunt-and-peck routine that grew old fairly quickly. That said, is it possible to be "fluent" in both qwerty and dvorak at the same time? If not, are there any good solutions to the situation I found myself in? | TITLE:
Is it possible to be ambikeyboardrous?
QUESTION:
I switched to the dvorak keyboard layout about a year ago. I now use dvorak full-time at work and at home. Recently, I went on vacation to Peru and found myself in quite a conundrum. Internet cafes were qwerty-only (and Spanish qwerty, at that). I was stuck with a hunt-and-peck routine that grew old fairly quickly. That said, is it possible to be "fluent" in both qwerty and dvorak at the same time? If not, are there any good solutions to the situation I found myself in?
ANSWER:
Web For your situation of being at a public computer that you cannot switch the keyboard layout on, you can go to this website: http://www.dvzine.org/type/DVconverter.html Use this to translate your typing and then use copy paste. I found this very useful when I was out of the country and had to write a bunch of emails at public computers. USB Drive Put this Dvorak Utility on your USB drive. Run this app and it will put a icon in the system tray on windows. This icon will switch the computer between the two keyboard layouts and it works. (If you have tried switching back and forth from dvorak to qwerty you will know what I mean. Windows does the worst job of this one bit of functionality.) | [
"keyboard",
"dvorak",
"qwerty"
] | 15 | 11 | 8,297 | 15 | 0 | 2008-08-14T19:00:16.793000 | 2008-09-10T04:21:55.433000 |
11,516 | 12,138 | Variable Bindings in WPF | I’m creating a UserControl for a rich TreeView (one that has context menus for renaming nodes, adding child nodes, etc.). I want to be able to use this control to manage or navigate any hierarchical data structures I will create. I currently have it working for any data structure that implements the following interface (the interface need not actually be implemented, however, only the presence of these members is required): interface ITreeItem { string Header { get; set; } IEnumerable Children { get; } } Then in my UserControl, I use templates to bind my tree to the data structure, like so: What I would like to do is define the name of each of these members in my RichTreeView, allowing it to adapt to a range of different data structures, like so: class MyItem { string Name { get; set; } ObservableCollection Items; } Is there any way to expose the Path of a binding inside a UserControl as a public property of that UserControl? Is there some other way to go about solving this problem? | Perhaps this might help: Create a new Binding when you set the HeaderProperty property on the Header dependency property: Header property is your normal everyday DependencyProperty: public string Header { get { return (string)GetValue(HeaderProperty); } set { SetValue(HeaderProperty, value); } }
public static readonly DependencyProperty HeaderProperty = DependencyProperty.Register("Header", typeof(string), typeof(ownerclass)); and the property of your HeaderProperty works as follows: public static readonly DependencyProperty HeaderPropertyProperty = DependencyProperty.Register("HeaderProperty", typeof(string), typeof(ownerclass), new PropertyMetadata(OnHeaderPropertyChanged));
public string HeaderProperty { get { return (string)GetValue(HeaderPropertyProperty); } set { SetValue(HeaderPropertyProperty, value); } }
public static void OnHeaderPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) { if (args.NewValue!= null) { ownerclass c = (ownerclass) obj;
Binding b = new Binding(); b.Path = new PropertyPath(args.NewValue.ToString()); c.SetBinding(ownerclass.HeaderProperty, b); } } HeaderProperty is your normal everyday DependencyProperty, with a method that is invoked as soon as the HeaderProperty changes. So when it changes, it creates a binding on the Header which will bind to the path you set in the HeaderProperty.:) | Variable Bindings in WPF I’m creating a UserControl for a rich TreeView (one that has context menus for renaming nodes, adding child nodes, etc.). I want to be able to use this control to manage or navigate any hierarchical data structures I will create. I currently have it working for any data structure that implements the following interface (the interface need not actually be implemented, however, only the presence of these members is required): interface ITreeItem { string Header { get; set; } IEnumerable Children { get; } } Then in my UserControl, I use templates to bind my tree to the data structure, like so: What I would like to do is define the name of each of these members in my RichTreeView, allowing it to adapt to a range of different data structures, like so: class MyItem { string Name { get; set; } ObservableCollection Items; } Is there any way to expose the Path of a binding inside a UserControl as a public property of that UserControl? Is there some other way to go about solving this problem? | TITLE:
Variable Bindings in WPF
QUESTION:
I’m creating a UserControl for a rich TreeView (one that has context menus for renaming nodes, adding child nodes, etc.). I want to be able to use this control to manage or navigate any hierarchical data structures I will create. I currently have it working for any data structure that implements the following interface (the interface need not actually be implemented, however, only the presence of these members is required): interface ITreeItem { string Header { get; set; } IEnumerable Children { get; } } Then in my UserControl, I use templates to bind my tree to the data structure, like so: What I would like to do is define the name of each of these members in my RichTreeView, allowing it to adapt to a range of different data structures, like so: class MyItem { string Name { get; set; } ObservableCollection Items; } Is there any way to expose the Path of a binding inside a UserControl as a public property of that UserControl? Is there some other way to go about solving this problem?
ANSWER:
Perhaps this might help: Create a new Binding when you set the HeaderProperty property on the Header dependency property: Header property is your normal everyday DependencyProperty: public string Header { get { return (string)GetValue(HeaderProperty); } set { SetValue(HeaderProperty, value); } }
public static readonly DependencyProperty HeaderProperty = DependencyProperty.Register("Header", typeof(string), typeof(ownerclass)); and the property of your HeaderProperty works as follows: public static readonly DependencyProperty HeaderPropertyProperty = DependencyProperty.Register("HeaderProperty", typeof(string), typeof(ownerclass), new PropertyMetadata(OnHeaderPropertyChanged));
public string HeaderProperty { get { return (string)GetValue(HeaderPropertyProperty); } set { SetValue(HeaderPropertyProperty, value); } }
public static void OnHeaderPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) { if (args.NewValue!= null) { ownerclass c = (ownerclass) obj;
Binding b = new Binding(); b.Path = new PropertyPath(args.NewValue.ToString()); c.SetBinding(ownerclass.HeaderProperty, b); } } HeaderProperty is your normal everyday DependencyProperty, with a method that is invoked as soon as the HeaderProperty changes. So when it changes, it creates a binding on the Header which will bind to the path you set in the HeaderProperty.:) | [
"c#",
"wpf",
"data-binding"
] | 5 | 2 | 3,578 | 1 | 0 | 2008-08-14T19:01:02.737000 | 2008-08-15T11:08:05.780000 |
11,520 | 11,529 | What are the list of Resharper like plugins for VS I should consider? | My license for Whole Tomatoes Visual AssistX is about to expire and I'm not really planning on renewing it. I use it for spell checking but that's about it. The refactoring abilities have been a little disappointing. Before I just jump into Resharper though what are your thoughts on other possible plugins? | The other major player would be DevExpress and their CodeRush and Refactor products. Found here. | What are the list of Resharper like plugins for VS I should consider? My license for Whole Tomatoes Visual AssistX is about to expire and I'm not really planning on renewing it. I use it for spell checking but that's about it. The refactoring abilities have been a little disappointing. Before I just jump into Resharper though what are your thoughts on other possible plugins? | TITLE:
What are the list of Resharper like plugins for VS I should consider?
QUESTION:
My license for Whole Tomatoes Visual AssistX is about to expire and I'm not really planning on renewing it. I use it for spell checking but that's about it. The refactoring abilities have been a little disappointing. Before I just jump into Resharper though what are your thoughts on other possible plugins?
ANSWER:
The other major player would be DevExpress and their CodeRush and Refactor products. Found here. | [
".net",
"visual-studio"
] | 3 | 2 | 1,993 | 6 | 0 | 2008-08-14T19:03:53.590000 | 2008-08-14T19:06:54.020000 |
11,532 | 14,625 | How can I find unused functions in a PHP project | How can I find any unused functions in a PHP project? Are there features or APIs built into PHP that will allow me to analyse my codebase - for example Reflection, token_get_all()? Are these APIs feature rich enough for me not to have to rely on a third party tool to perform this type of analysis? | Thanks Greg and Dave for the feedback. Wasn't quite what I was looking for, but I decided to put a bit of time into researching it and came up with this quick and dirty solution: ". " ". " Name ". " Defined ". " Referenced ". " "; foreach ($functions as $name => $value) { echo " ". " ". htmlentities($name). " ". " ". (isset($value[0])? count($value[0]): "-"). " ". " ". (isset($value[1])? count($value[1]): "-"). " ". " "; } echo " "; function define_dir($path, &$functions) { if ($dir = opendir($path)) { while (($file = readdir($dir))!== false) { if (substr($file, 0, 1) == ".") continue; if (is_dir($path. "/". $file)) { define_dir($path. "/". $file, $functions); } else { if (substr($file, - 4, 4)!= ".php") continue; define_file($path. "/". $file, $functions); } } } } function define_file($path, &$functions) { $tokens = token_get_all(file_get_contents($path)); for ($i = 0; $i < count($tokens); $i++) { $token = $tokens[$i]; if (is_array($token)) { if ($token[0]!= T_FUNCTION) continue; $i++; $token = $tokens[$i]; if ($token[0]!= T_WHITESPACE) die("T_WHITESPACE"); $i++; $token = $tokens[$i]; if ($token[0]!= T_STRING) die("T_STRING"); $functions[$token[1]][0][] = array($path, $token[2]); } } } function reference_dir($path, &$functions) { if ($dir = opendir($path)) { while (($file = readdir($dir))!== false) { if (substr($file, 0, 1) == ".") continue; if (is_dir($path. "/". $file)) { reference_dir($path. "/". $file, $functions); } else { if (substr($file, - 4, 4)!= ".php") continue; reference_file($path. "/". $file, $functions); } } } } function reference_file($path, &$functions) { $tokens = token_get_all(file_get_contents($path)); for ($i = 0; $i < count($tokens); $i++) { $token = $tokens[$i]; if (is_array($token)) { if ($token[0]!= T_STRING) continue; if ($tokens[$i + 1]!= "(") continue; $functions[$token[1]][1][] = array($path, $token[2]); } } }?> I'll probably spend some more time on it so I can quickly find the files and line numbers of the function definitions and references; this information is being gathered, just not displayed. | How can I find unused functions in a PHP project How can I find any unused functions in a PHP project? Are there features or APIs built into PHP that will allow me to analyse my codebase - for example Reflection, token_get_all()? Are these APIs feature rich enough for me not to have to rely on a third party tool to perform this type of analysis? | TITLE:
How can I find unused functions in a PHP project
QUESTION:
How can I find any unused functions in a PHP project? Are there features or APIs built into PHP that will allow me to analyse my codebase - for example Reflection, token_get_all()? Are these APIs feature rich enough for me not to have to rely on a third party tool to perform this type of analysis?
ANSWER:
Thanks Greg and Dave for the feedback. Wasn't quite what I was looking for, but I decided to put a bit of time into researching it and came up with this quick and dirty solution: ". " ". " Name ". " Defined ". " Referenced ". " "; foreach ($functions as $name => $value) { echo " ". " ". htmlentities($name). " ". " ". (isset($value[0])? count($value[0]): "-"). " ". " ". (isset($value[1])? count($value[1]): "-"). " ". " "; } echo " "; function define_dir($path, &$functions) { if ($dir = opendir($path)) { while (($file = readdir($dir))!== false) { if (substr($file, 0, 1) == ".") continue; if (is_dir($path. "/". $file)) { define_dir($path. "/". $file, $functions); } else { if (substr($file, - 4, 4)!= ".php") continue; define_file($path. "/". $file, $functions); } } } } function define_file($path, &$functions) { $tokens = token_get_all(file_get_contents($path)); for ($i = 0; $i < count($tokens); $i++) { $token = $tokens[$i]; if (is_array($token)) { if ($token[0]!= T_FUNCTION) continue; $i++; $token = $tokens[$i]; if ($token[0]!= T_WHITESPACE) die("T_WHITESPACE"); $i++; $token = $tokens[$i]; if ($token[0]!= T_STRING) die("T_STRING"); $functions[$token[1]][0][] = array($path, $token[2]); } } } function reference_dir($path, &$functions) { if ($dir = opendir($path)) { while (($file = readdir($dir))!== false) { if (substr($file, 0, 1) == ".") continue; if (is_dir($path. "/". $file)) { reference_dir($path. "/". $file, $functions); } else { if (substr($file, - 4, 4)!= ".php") continue; reference_file($path. "/". $file, $functions); } } } } function reference_file($path, &$functions) { $tokens = token_get_all(file_get_contents($path)); for ($i = 0; $i < count($tokens); $i++) { $token = $tokens[$i]; if (is_array($token)) { if ($token[0]!= T_STRING) continue; if ($tokens[$i + 1]!= "(") continue; $functions[$token[1]][1][] = array($path, $token[2]); } } }?> I'll probably spend some more time on it so I can quickly find the files and line numbers of the function definitions and references; this information is being gathered, just not displayed. | [
"php"
] | 71 | 25 | 35,718 | 10 | 0 | 2008-08-14T19:08:21.503000 | 2008-08-18T13:47:41.860000 |
11,561 | 11,619 | What is the difference between an endpoint, a service, and a port when working with webservices? | I've used Apache CXF to expose about ten java classes as web services. I've generated clients using CXF, Axis, and.NET. In Axis and CXF a "Service" or "Locator" is generated. From this service you can get a "Port". The "Port" is used to make individual calls to the methods exposed by the web service. In.NET the "Service" directly exposes the calls to the web service. Can someone explain the difference between a port, a service, a locator, and an endpoint when it comes to web services? Axis: PatientServiceImplServiceLocator locator = new PatientServiceImplServiceLocator(); PatientService service = locator.getPatientServiceImplPort(); CXF: PatientServiceImplService locator = new PatientServiceImplService(); PatientService service = locator.getPatientServiceImplPort();.net: PatientServiceImplService service = new PatientServiceImplService(); | I'd hop over to http://www.w3.org/TR/wsdl.html which I think explains Port, Service and Endpoint reasonably well. A locator is an implementation specific mechanism that some WS stacks use to provide access to service endpoints. | What is the difference between an endpoint, a service, and a port when working with webservices? I've used Apache CXF to expose about ten java classes as web services. I've generated clients using CXF, Axis, and.NET. In Axis and CXF a "Service" or "Locator" is generated. From this service you can get a "Port". The "Port" is used to make individual calls to the methods exposed by the web service. In.NET the "Service" directly exposes the calls to the web service. Can someone explain the difference between a port, a service, a locator, and an endpoint when it comes to web services? Axis: PatientServiceImplServiceLocator locator = new PatientServiceImplServiceLocator(); PatientService service = locator.getPatientServiceImplPort(); CXF: PatientServiceImplService locator = new PatientServiceImplService(); PatientService service = locator.getPatientServiceImplPort();.net: PatientServiceImplService service = new PatientServiceImplService(); | TITLE:
What is the difference between an endpoint, a service, and a port when working with webservices?
QUESTION:
I've used Apache CXF to expose about ten java classes as web services. I've generated clients using CXF, Axis, and.NET. In Axis and CXF a "Service" or "Locator" is generated. From this service you can get a "Port". The "Port" is used to make individual calls to the methods exposed by the web service. In.NET the "Service" directly exposes the calls to the web service. Can someone explain the difference between a port, a service, a locator, and an endpoint when it comes to web services? Axis: PatientServiceImplServiceLocator locator = new PatientServiceImplServiceLocator(); PatientService service = locator.getPatientServiceImplPort(); CXF: PatientServiceImplService locator = new PatientServiceImplService(); PatientService service = locator.getPatientServiceImplPort();.net: PatientServiceImplService service = new PatientServiceImplService();
ANSWER:
I'd hop over to http://www.w3.org/TR/wsdl.html which I think explains Port, Service and Endpoint reasonably well. A locator is an implementation specific mechanism that some WS stacks use to provide access to service endpoints. | [
"java",
".net",
"web-services",
"cxf",
"axis"
] | 25 | 9 | 46,129 | 4 | 0 | 2008-08-14T19:23:54.547000 | 2008-08-14T19:54:23.860000 |
11,562 | 2,684,544 | How to overload std::swap() | std::swap() is used by many std containers (such as std::list and std::vector ) during sorting and even assignment. But the std implementation of swap() is very generalized and rather inefficient for custom types. Thus efficiency can be gained by overloading std::swap() with a custom type specific implementation. But how can you implement it so it will be used by the std containers? | The right way to overload std::swap 's implemention (aka specializing it), is to write it in the same namespace as what you're swapping, so that it can be found via argument-dependent lookup (ADL). One particularly easy thing to do is: class X { //... friend void swap(X& a, X& b) { using std::swap; // bring in swap for built-in types
swap(a.base1, b.base1); swap(a.base2, b.base2); //... swap(a.member1, b.member1); swap(a.member2, b.member2); //... } }; | How to overload std::swap() std::swap() is used by many std containers (such as std::list and std::vector ) during sorting and even assignment. But the std implementation of swap() is very generalized and rather inefficient for custom types. Thus efficiency can be gained by overloading std::swap() with a custom type specific implementation. But how can you implement it so it will be used by the std containers? | TITLE:
How to overload std::swap()
QUESTION:
std::swap() is used by many std containers (such as std::list and std::vector ) during sorting and even assignment. But the std implementation of swap() is very generalized and rather inefficient for custom types. Thus efficiency can be gained by overloading std::swap() with a custom type specific implementation. But how can you implement it so it will be used by the std containers?
ANSWER:
The right way to overload std::swap 's implemention (aka specializing it), is to write it in the same namespace as what you're swapping, so that it can be found via argument-dependent lookup (ADL). One particularly easy thing to do is: class X { //... friend void swap(X& a, X& b) { using std::swap; // bring in swap for built-in types
swap(a.base1, b.base1); swap(a.base2, b.base2); //... swap(a.member1, b.member1); swap(a.member2, b.member2); //... } }; | [
"c++",
"performance",
"optimization",
"stl",
"c++-faq"
] | 128 | 154 | 38,665 | 4 | 0 | 2008-08-14T19:24:17.260000 | 2010-04-21T16:02:22.350000 |
11,574 | 230,204 | How can I improve performance when adding InDesign XMLElements via AppleScript? | I have an AppleScript program which creates XML tags and elements within an Adobe InDesign document. The data is in tables, and tagging each cell takes.5 seconds. The entire script takes several hours to complete. I can post the inner loop code, but I'm not sure if SO is supposed to be generic or specific. I'll let the mob decide. [edit] The code builds a list (prior to this loop) which contains one item per row in the table. There is also a list containing one string for each column in the table. For each cell, the program creates an XML element and an XML tag by concatenating the items in the [row]/[column] positions of the two lists. It also associates the text in that cell to the newly-created element. I'm completely new to AppleScript so some of this code is crudely modified from Adobe's samples. If the code is atrocious I won't be offended. Here's the code: repeat with columnNumber from COL_START to COL_END
select text of cell ((columnNumber as string) & ":" & (rowNumber as string)) of ThisTable
tell activeDocument
set thisXmlTag to make XML tag with properties {name:item rowNumber of symbolList & "_" & item columnNumber of my histLabelList}
tell rootXmlElement
set thisXmlElement to make XML element with properties {markup tag:thisXmlTag}
end tell
set contents of thisXmlElement to (selection as string)
end tell
end repeat EDIT: I've rephrased the question to better reflect the correct answer. | I figured this one out. The document contains a bunch of data tables. In all, there are about 7,000 data points that need to be exported. I was creating one root element with 7,000 children. Don't do that. Adding each child to the root element got slower and slower until at about 5,000 children AppleScript timed out and the program aborted. The solution was to make my code more brittle by creating ~480 children off the root, with each child having about 16 grandchildren. Same number of nodes, but the code now runs fast enough. (It still takes about 40 minutes to process the document, but that's infinitely less time than infinity.) Incidentally, the original 7,000 children plan wasn't as stupid or as lazy as it appears. The new solution is forcing me to link the two tables together using data in the tables that I don't control. The program will now break if there's so much as a space where there shouldn't be one. (But it works.) | How can I improve performance when adding InDesign XMLElements via AppleScript? I have an AppleScript program which creates XML tags and elements within an Adobe InDesign document. The data is in tables, and tagging each cell takes.5 seconds. The entire script takes several hours to complete. I can post the inner loop code, but I'm not sure if SO is supposed to be generic or specific. I'll let the mob decide. [edit] The code builds a list (prior to this loop) which contains one item per row in the table. There is also a list containing one string for each column in the table. For each cell, the program creates an XML element and an XML tag by concatenating the items in the [row]/[column] positions of the two lists. It also associates the text in that cell to the newly-created element. I'm completely new to AppleScript so some of this code is crudely modified from Adobe's samples. If the code is atrocious I won't be offended. Here's the code: repeat with columnNumber from COL_START to COL_END
select text of cell ((columnNumber as string) & ":" & (rowNumber as string)) of ThisTable
tell activeDocument
set thisXmlTag to make XML tag with properties {name:item rowNumber of symbolList & "_" & item columnNumber of my histLabelList}
tell rootXmlElement
set thisXmlElement to make XML element with properties {markup tag:thisXmlTag}
end tell
set contents of thisXmlElement to (selection as string)
end tell
end repeat EDIT: I've rephrased the question to better reflect the correct answer. | TITLE:
How can I improve performance when adding InDesign XMLElements via AppleScript?
QUESTION:
I have an AppleScript program which creates XML tags and elements within an Adobe InDesign document. The data is in tables, and tagging each cell takes.5 seconds. The entire script takes several hours to complete. I can post the inner loop code, but I'm not sure if SO is supposed to be generic or specific. I'll let the mob decide. [edit] The code builds a list (prior to this loop) which contains one item per row in the table. There is also a list containing one string for each column in the table. For each cell, the program creates an XML element and an XML tag by concatenating the items in the [row]/[column] positions of the two lists. It also associates the text in that cell to the newly-created element. I'm completely new to AppleScript so some of this code is crudely modified from Adobe's samples. If the code is atrocious I won't be offended. Here's the code: repeat with columnNumber from COL_START to COL_END
select text of cell ((columnNumber as string) & ":" & (rowNumber as string)) of ThisTable
tell activeDocument
set thisXmlTag to make XML tag with properties {name:item rowNumber of symbolList & "_" & item columnNumber of my histLabelList}
tell rootXmlElement
set thisXmlElement to make XML element with properties {markup tag:thisXmlTag}
end tell
set contents of thisXmlElement to (selection as string)
end tell
end repeat EDIT: I've rephrased the question to better reflect the correct answer.
ANSWER:
I figured this one out. The document contains a bunch of data tables. In all, there are about 7,000 data points that need to be exported. I was creating one root element with 7,000 children. Don't do that. Adding each child to the root element got slower and slower until at about 5,000 children AppleScript timed out and the program aborted. The solution was to make my code more brittle by creating ~480 children off the root, with each child having about 16 grandchildren. Same number of nodes, but the code now runs fast enough. (It still takes about 40 minutes to process the document, but that's infinitely less time than infinity.) Incidentally, the original 7,000 children plan wasn't as stupid or as lazy as it appears. The new solution is forcing me to link the two tables together using data in the tables that I don't control. The program will now break if there's so much as a space where there shouldn't be one. (But it works.) | [
"macos",
"adobe",
"applescript",
"adobe-indesign"
] | 7 | 1 | 1,569 | 5 | 0 | 2008-08-14T19:32:03.190000 | 2008-10-23T15:33:52.443000 |
11,585 | 11,641 | Clearing Page Cache in ASP.NET | For my blog I am wanting to use the Output Cache to save a cached version of a perticular post for around 10 minutes, and thats fine... <%@OutputCache Duration="600" VaryByParam="*" %> However, if someone posts a comment, I want to clear the cache so that the page is refreshed and the comment can be seen. How do I do this in ASP.Net C#? | I've found the answer I was looking for: HttpResponse.RemoveOutputCacheItem("/caching/CacheForever.aspx"); | Clearing Page Cache in ASP.NET For my blog I am wanting to use the Output Cache to save a cached version of a perticular post for around 10 minutes, and thats fine... <%@OutputCache Duration="600" VaryByParam="*" %> However, if someone posts a comment, I want to clear the cache so that the page is refreshed and the comment can be seen. How do I do this in ASP.Net C#? | TITLE:
Clearing Page Cache in ASP.NET
QUESTION:
For my blog I am wanting to use the Output Cache to save a cached version of a perticular post for around 10 minutes, and thats fine... <%@OutputCache Duration="600" VaryByParam="*" %> However, if someone posts a comment, I want to clear the cache so that the page is refreshed and the comment can be seen. How do I do this in ASP.Net C#?
ANSWER:
I've found the answer I was looking for: HttpResponse.RemoveOutputCacheItem("/caching/CacheForever.aspx"); | [
"c#",
"asp.net",
"outputcache"
] | 53 | 49 | 110,132 | 8 | 0 | 2008-08-14T19:39:32.033000 | 2008-08-14T20:04:36.290000 |
11,586 | 11,617 | Do you use design patterns? | What's the penetration of design patterns in the real world? Do you use them in your day to day job - discussing how and where to apply them with your coworkers - or do they remain more of an academic concept? Do they actually provide actual value to your job? Or are they just something that people talk about to sound smart? Note: For the purpose of this question ignore 'simple' design patterns like Singleton. I'm talking about designing your code so you can take advantage of Model View Controller, etc. | Any large program that is well written will use design patterns, even if they aren't named or recognized as such. That's what design patterns are, designs that repeatedly and naturally occur. If you're interfacing with an ugly API, you'll likely find yourself implementing a Facade to clean it up. If you've got messaging between components that you need to decouple, you may find yourself using Observer. If you've got several interchangeable algorithms, you might end up using Strategy. It's worth knowing the design patterns because you're more likely to recognize them and then converge on a clean solution more quickly. However, even if you don't know them at all, you'll end up creating them eventually (if you are a decent programmer). And of course, if you are using a modern language, you'll probably be forced to use them for some things, because they're baked into the standard libraries. | Do you use design patterns? What's the penetration of design patterns in the real world? Do you use them in your day to day job - discussing how and where to apply them with your coworkers - or do they remain more of an academic concept? Do they actually provide actual value to your job? Or are they just something that people talk about to sound smart? Note: For the purpose of this question ignore 'simple' design patterns like Singleton. I'm talking about designing your code so you can take advantage of Model View Controller, etc. | TITLE:
Do you use design patterns?
QUESTION:
What's the penetration of design patterns in the real world? Do you use them in your day to day job - discussing how and where to apply them with your coworkers - or do they remain more of an academic concept? Do they actually provide actual value to your job? Or are they just something that people talk about to sound smart? Note: For the purpose of this question ignore 'simple' design patterns like Singleton. I'm talking about designing your code so you can take advantage of Model View Controller, etc.
ANSWER:
Any large program that is well written will use design patterns, even if they aren't named or recognized as such. That's what design patterns are, designs that repeatedly and naturally occur. If you're interfacing with an ugly API, you'll likely find yourself implementing a Facade to clean it up. If you've got messaging between components that you need to decouple, you may find yourself using Observer. If you've got several interchangeable algorithms, you might end up using Strategy. It's worth knowing the design patterns because you're more likely to recognize them and then converge on a clean solution more quickly. However, even if you don't know them at all, you'll end up creating them eventually (if you are a decent programmer). And of course, if you are using a modern language, you'll probably be forced to use them for some things, because they're baked into the standard libraries. | [
"language-agnostic",
"design-patterns"
] | 29 | 55 | 3,923 | 15 | 0 | 2008-08-14T19:39:32.813000 | 2008-08-14T19:54:09.633000 |
11,612 | 11,646 | Is there any wiki engine that supports page creation by email? | I want to consolidate all the loose information of the company I work for into a knowledge base. A wiki seems to be the way to go, but most of the relevant information is buried inside PST files, and it would take ages to convince people to manually translate their emails one by one (including attachments) into wiki pages. So I'm looking for a wiki engine that supports page creation by email, that is, capable of receiving email (supporting plain text, html and attachments) and then create the corresponding page. Supporting file indexing and looking for duplicates would be a huge bonus. I tried with WikiMatrix, but didn't find what I was looking for. I wouldn’t mind to build my own engine (borrowing a couple of snippets here and there for MIME decoding ), but I don’t think is that a rare problem so there is no implementation. | Both Jotspot and MediaWiki allow you to do this. The latter has support for a lot of plugins, of which this is one. The format is essentially PageTitle@something. Jotspot is a hosted solution where you get your own email address, MediaWiki is self-hosted and you give it a mailbox to monitor for incoming. Articles are appended to pages if they already exist, or a new page is created if it does not. This does require a degree of discipline for naming conventions, but is great for CC'ing. We use MediaWiki here and I like it a lot. It has the same flaws as many other Wiki packages (e.g difficult to reorganize without orphaning pages) but is as good if not better than other Wiki packages I've used. | Is there any wiki engine that supports page creation by email? I want to consolidate all the loose information of the company I work for into a knowledge base. A wiki seems to be the way to go, but most of the relevant information is buried inside PST files, and it would take ages to convince people to manually translate their emails one by one (including attachments) into wiki pages. So I'm looking for a wiki engine that supports page creation by email, that is, capable of receiving email (supporting plain text, html and attachments) and then create the corresponding page. Supporting file indexing and looking for duplicates would be a huge bonus. I tried with WikiMatrix, but didn't find what I was looking for. I wouldn’t mind to build my own engine (borrowing a couple of snippets here and there for MIME decoding ), but I don’t think is that a rare problem so there is no implementation. | TITLE:
Is there any wiki engine that supports page creation by email?
QUESTION:
I want to consolidate all the loose information of the company I work for into a knowledge base. A wiki seems to be the way to go, but most of the relevant information is buried inside PST files, and it would take ages to convince people to manually translate their emails one by one (including attachments) into wiki pages. So I'm looking for a wiki engine that supports page creation by email, that is, capable of receiving email (supporting plain text, html and attachments) and then create the corresponding page. Supporting file indexing and looking for duplicates would be a huge bonus. I tried with WikiMatrix, but didn't find what I was looking for. I wouldn’t mind to build my own engine (borrowing a couple of snippets here and there for MIME decoding ), but I don’t think is that a rare problem so there is no implementation.
ANSWER:
Both Jotspot and MediaWiki allow you to do this. The latter has support for a lot of plugins, of which this is one. The format is essentially PageTitle@something. Jotspot is a hosted solution where you get your own email address, MediaWiki is self-hosted and you give it a mailbox to monitor for incoming. Articles are appended to pages if they already exist, or a new page is created if it does not. This does require a degree of discipline for naming conventions, but is great for CC'ing. We use MediaWiki here and I like it a lot. It has the same flaws as many other Wiki packages (e.g difficult to reorganize without orphaning pages) but is as good if not better than other Wiki packages I've used. | [
"email",
"wiki",
"mime",
"wiki-engine"
] | 6 | 3 | 401 | 2 | 0 | 2008-08-14T19:51:52.010000 | 2008-08-14T20:06:44.180000 |
11,620 | 11,624 | How do you kill all current connections to a SQL Server 2005 database? | I want to rename a database, but keep getting the error that 'couldn't get exclusive lock' on the database, which implies there is some connection(s) still active. How can I kill all the connections to the database so that I can rename it? | The reason that the approach that Adam suggested won't work is that during the time that you are looping over the active connections new one can be established, and you'll miss those. You could instead use the following approach which does not have this drawback: -- set your current connection to use master otherwise you might get an error
use master ALTER DATABASE YourDatabase SET SINGLE_USER WITH ROLLBACK IMMEDIATE
--do you stuff here
ALTER DATABASE YourDatabase SET MULTI_USER | How do you kill all current connections to a SQL Server 2005 database? I want to rename a database, but keep getting the error that 'couldn't get exclusive lock' on the database, which implies there is some connection(s) still active. How can I kill all the connections to the database so that I can rename it? | TITLE:
How do you kill all current connections to a SQL Server 2005 database?
QUESTION:
I want to rename a database, but keep getting the error that 'couldn't get exclusive lock' on the database, which implies there is some connection(s) still active. How can I kill all the connections to the database so that I can rename it?
ANSWER:
The reason that the approach that Adam suggested won't work is that during the time that you are looping over the active connections new one can be established, and you'll miss those. You could instead use the following approach which does not have this drawback: -- set your current connection to use master otherwise you might get an error
use master ALTER DATABASE YourDatabase SET SINGLE_USER WITH ROLLBACK IMMEDIATE
--do you stuff here
ALTER DATABASE YourDatabase SET MULTI_USER | [
"sql-server",
"sql-server-2005"
] | 296 | 391 | 436,762 | 19 | 0 | 2008-08-14T19:54:25.187000 | 2008-08-14T19:56:56.633000 |
11,632 | 11,663 | What are the most important functional differences between C# and VB.NET? | Certainly there's the difference in general syntax, but what other critical distinctions exist? There are some differences, right? | The linked comparisons are very thorough, but as far as the main differences I would note the following: C# has anonymous methods VB has these now, too C# has the yield keyword (iterator blocks) VB11 added this VB supports implicit late binding (C# has explicit late binding now via the dynamic keyword) VB supports XML literals VB is case insensitive More out-of-the-box code snippets for VB More out-of-the-box refactoring tools for C# Visual Studio 2015 now provides the same refactoring tools for both VB and C#. In general the things MS focuses on for each vary, because the two languages are targeted at very different audiences. This blog post has a good summary of the target audiences. It is probably a good idea to determine which audience you are in, because it will determine what kind of tools you'll get from Microsoft. | What are the most important functional differences between C# and VB.NET? Certainly there's the difference in general syntax, but what other critical distinctions exist? There are some differences, right? | TITLE:
What are the most important functional differences between C# and VB.NET?
QUESTION:
Certainly there's the difference in general syntax, but what other critical distinctions exist? There are some differences, right?
ANSWER:
The linked comparisons are very thorough, but as far as the main differences I would note the following: C# has anonymous methods VB has these now, too C# has the yield keyword (iterator blocks) VB11 added this VB supports implicit late binding (C# has explicit late binding now via the dynamic keyword) VB supports XML literals VB is case insensitive More out-of-the-box code snippets for VB More out-of-the-box refactoring tools for C# Visual Studio 2015 now provides the same refactoring tools for both VB and C#. In general the things MS focuses on for each vary, because the two languages are targeted at very different audiences. This blog post has a good summary of the target audiences. It is probably a good idea to determine which audience you are in, because it will determine what kind of tools you'll get from Microsoft. | [
"c#",
"vb.net",
"comparison"
] | 35 | 34 | 10,415 | 14 | 0 | 2008-08-14T19:59:40.090000 | 2008-08-14T20:23:55.457000 |
11,635 | 315,463 | Case-insensitive string comparison in C++ | What is the best way of doing case-insensitive string comparison in C++ without transforming a string to all uppercase or all lowercase? Please indicate whether the methods are Unicode-friendly and how portable they are. | Boost includes a handy algorithm for this: #include // Or, for fewer header dependencies: //#include std::string str1 = "hello, world!"; std::string str2 = "HELLO, WORLD!";
if (boost::iequals(str1, str2)) { // Strings are identical } | Case-insensitive string comparison in C++ What is the best way of doing case-insensitive string comparison in C++ without transforming a string to all uppercase or all lowercase? Please indicate whether the methods are Unicode-friendly and how portable they are. | TITLE:
Case-insensitive string comparison in C++
QUESTION:
What is the best way of doing case-insensitive string comparison in C++ without transforming a string to all uppercase or all lowercase? Please indicate whether the methods are Unicode-friendly and how portable they are.
ANSWER:
Boost includes a handy algorithm for this: #include // Or, for fewer header dependencies: //#include std::string str1 = "hello, world!"; std::string str2 = "HELLO, WORLD!";
if (boost::iequals(str1, str2)) { // Strings are identical } | [
"c++",
"string"
] | 372 | 331 | 642,362 | 30 | 0 | 2008-08-14T20:01:28.497000 | 2008-11-24T21:03:58.740000 |
11,665 | 12,310 | How do I restyle an Adobe Flex Accordion to include a button in each canvas header? | Here is the sample code for my accordion: I would like to include a button in each header like so: | Thanks, I got it working using FlexLib 's CanvasButtonAccordionHeader. | How do I restyle an Adobe Flex Accordion to include a button in each canvas header? Here is the sample code for my accordion: I would like to include a button in each header like so: | TITLE:
How do I restyle an Adobe Flex Accordion to include a button in each canvas header?
QUESTION:
Here is the sample code for my accordion: I would like to include a button in each header like so:
ANSWER:
Thanks, I got it working using FlexLib 's CanvasButtonAccordionHeader. | [
"apache-flex",
"actionscript-3"
] | 2 | 2 | 5,993 | 2 | 0 | 2008-08-14T20:25:07.840000 | 2008-08-15T14:47:51.863000 |
11,676 | 11,688 | Creating a development environment for SharePoint | I haven't touched sharepoint in years. If I want to setup a development environment to get up to speed, what options do I have? I don't have an MSDN license, is there anyway I can get up and running for free? (for development only) | You need a Windows 2003 Server (or 2008 Server, but I have no experience with that), no way around that. You can then of course use Visual C# 2005 Express and the SHarepoint Services 3.0 if that's your target. If you want to do development on Sharepoint 2007, you have to buy a Sharepoint 2007 license, which has a pretty hefty fee attached to it. As a SQL, SQL 2005 Express works fine for development. There is a good Article how to set up Sharepoint on a Single Server: http://blogs.msdn.com/martinkearn/archive/2007/03/28/how-to-install-sharepoint-server-2007-on-a-single-machine.aspx You CAN use a Trial Version of Windows 2003 and Sharepoint 2007 though if it's only needed for a limited time (i believe the Trials run 180 days). | Creating a development environment for SharePoint I haven't touched sharepoint in years. If I want to setup a development environment to get up to speed, what options do I have? I don't have an MSDN license, is there anyway I can get up and running for free? (for development only) | TITLE:
Creating a development environment for SharePoint
QUESTION:
I haven't touched sharepoint in years. If I want to setup a development environment to get up to speed, what options do I have? I don't have an MSDN license, is there anyway I can get up and running for free? (for development only)
ANSWER:
You need a Windows 2003 Server (or 2008 Server, but I have no experience with that), no way around that. You can then of course use Visual C# 2005 Express and the SHarepoint Services 3.0 if that's your target. If you want to do development on Sharepoint 2007, you have to buy a Sharepoint 2007 license, which has a pretty hefty fee attached to it. As a SQL, SQL 2005 Express works fine for development. There is a good Article how to set up Sharepoint on a Single Server: http://blogs.msdn.com/martinkearn/archive/2007/03/28/how-to-install-sharepoint-server-2007-on-a-single-machine.aspx You CAN use a Trial Version of Windows 2003 and Sharepoint 2007 though if it's only needed for a limited time (i believe the Trials run 180 days). | [
"sharepoint"
] | 5 | 9 | 3,123 | 6 | 0 | 2008-08-14T20:34:07.727000 | 2008-08-14T20:49:08.633000 |
11,680 | 11,712 | Design pattern for parsing binary file data and storing in a database | Does anybody recommend a design pattern for taking a binary data file, parsing parts of it into objects and storing the resultant data into a database? I think a similar pattern could be used for taking an XML or tab-delimited file and parse it into their representative objects. A common data structure would include: (Header) (DataElement1) (DataElement1SubData1) (DataElement1SubData2)(DataElement2) (DataElement2SubData1) (DataElement2SubData2) (EOF) I think a good design would include a way to change out the parsing definition based on the file type or some defined metadata included in the header. So a Factory Pattern would be part of the overall design for the Parser part. | Write your file parser, using whatever techniques come to mind. Write lots of unit tests to make sure all your edge cases are covered. Once you've done this, you will actually have a reasonable idea of the problem/solution. Right now you just have theories floating around in your head, most of which will turn out to be misguided. Refactor mercilessly. Your aim should be to delete about half of your code. You'll find that your code at the end will either resemble an existing design pattern, or you'll have created a new one. You'll then be qualified to answer this question:-) | Design pattern for parsing binary file data and storing in a database Does anybody recommend a design pattern for taking a binary data file, parsing parts of it into objects and storing the resultant data into a database? I think a similar pattern could be used for taking an XML or tab-delimited file and parse it into their representative objects. A common data structure would include: (Header) (DataElement1) (DataElement1SubData1) (DataElement1SubData2)(DataElement2) (DataElement2SubData1) (DataElement2SubData2) (EOF) I think a good design would include a way to change out the parsing definition based on the file type or some defined metadata included in the header. So a Factory Pattern would be part of the overall design for the Parser part. | TITLE:
Design pattern for parsing binary file data and storing in a database
QUESTION:
Does anybody recommend a design pattern for taking a binary data file, parsing parts of it into objects and storing the resultant data into a database? I think a similar pattern could be used for taking an XML or tab-delimited file and parse it into their representative objects. A common data structure would include: (Header) (DataElement1) (DataElement1SubData1) (DataElement1SubData2)(DataElement2) (DataElement2SubData1) (DataElement2SubData2) (EOF) I think a good design would include a way to change out the parsing definition based on the file type or some defined metadata included in the header. So a Factory Pattern would be part of the overall design for the Parser part.
ANSWER:
Write your file parser, using whatever techniques come to mind. Write lots of unit tests to make sure all your edge cases are covered. Once you've done this, you will actually have a reasonable idea of the problem/solution. Right now you just have theories floating around in your head, most of which will turn out to be misguided. Refactor mercilessly. Your aim should be to delete about half of your code. You'll find that your code at the end will either resemble an existing design pattern, or you'll have created a new one. You'll then be qualified to answer this question:-) | [
"design-patterns",
"fileparse"
] | 6 | 22 | 8,056 | 4 | 0 | 2008-08-14T20:36:07.380000 | 2008-08-14T21:20:18.213000 |
11,686 | 11,728 | Is there any kind of non text interface to MySQL? | I have a MySQL query that returns a result with a single column of integers. Is there any way to get the MySQL C API to transfer this as actually integers rather than as ASCII text? For that matter is there a way to get MySQL to do /any/ of the API stuff as other than ASCII text. I'm thinking this would save a bit of time in sprintf/sscanf or whatever else is used as well as in bandwidth. | You're probably out of luck, to be honest. Looking at the MySQL C API ( http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html, http://dev.mysql.com/doc/refman/5.0/en/c-api-datatypes.html, look at MYSQL_ROW) there doesn't seem to be a mechanism for returning data in its actual type... the joys of using structs I guess. You could always implement a wrapper which checks against the MYSQL_ROW's type attribute ( http://dev.mysql.com/doc/refman/5.0/en/c-api-datatypes.html ) and returns a C union, but that's probably poor advice; don't do that. | Is there any kind of non text interface to MySQL? I have a MySQL query that returns a result with a single column of integers. Is there any way to get the MySQL C API to transfer this as actually integers rather than as ASCII text? For that matter is there a way to get MySQL to do /any/ of the API stuff as other than ASCII text. I'm thinking this would save a bit of time in sprintf/sscanf or whatever else is used as well as in bandwidth. | TITLE:
Is there any kind of non text interface to MySQL?
QUESTION:
I have a MySQL query that returns a result with a single column of integers. Is there any way to get the MySQL C API to transfer this as actually integers rather than as ASCII text? For that matter is there a way to get MySQL to do /any/ of the API stuff as other than ASCII text. I'm thinking this would save a bit of time in sprintf/sscanf or whatever else is used as well as in bandwidth.
ANSWER:
You're probably out of luck, to be honest. Looking at the MySQL C API ( http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html, http://dev.mysql.com/doc/refman/5.0/en/c-api-datatypes.html, look at MYSQL_ROW) there doesn't seem to be a mechanism for returning data in its actual type... the joys of using structs I guess. You could always implement a wrapper which checks against the MYSQL_ROW's type attribute ( http://dev.mysql.com/doc/refman/5.0/en/c-api-datatypes.html ) and returns a C union, but that's probably poor advice; don't do that. | [
"mysql",
"api"
] | 4 | 1 | 336 | 1 | 0 | 2008-08-14T20:47:06.860000 | 2008-08-14T21:59:12.767000 |
11,689 | 11,694 | Design debate: what are good ways to store and manipulate versioned objects? | I am intentionally leaving this quite vague at first. I'm looking for discussion and what issues are important more than I'm looking for hard answers. I'm in the middle of designing an app that does something like portfolio management. The design I have so far is Problem: a problem that needs to be solved Solution: a proposed solution to one or more problems Relationship: a relationship among two problems, two solutions, or a problem and a solution. Further broken down into: Parent-child - some sort of categorization / tree hierarchy Overlap - the degree to which two solutions or two problems really address the same concept Addresses - the degree to which a problem addresses a solution My question is about the temporal nature of these things. Problems crop up, then fade. Solutions have an expected resolution date, but that might be modified as they are developed. The degree of a relationship might change over time as problems and solutions evolve. So, the question: what is the best design for versioning of these things so I can get both a current and an historical perspective of my portfolio? Later: perhaps I should make this a more specific question, though @Eric Beard's answer is worth an up. I've considered three database designs. I'll enough of each to show their drawbacks. My question is: which to pick, or can you think of something better? 1: Problems (and separately, Solutions) are self-referential in versioning. table problems int id | string name | text description | datetime created_at | int previous_version_id
foreign key previous_version_id -> problems.id This is problematic because every time I want a new version, I have to duplicate the entire row, including that long description column. 2: Create a new Relationship type: Version. table problems int id | string name | text description | datetime created_at This simply moves the relationship from the Problems and Solutions tables into the Relationships table. Same duplication problem, but perhaps a little "cleaner" since I already have an abstract Relationship concept. 3: Use a more Subversion-like structure; move all Problem and Solution attributes into a separate table and version them. table problems int id
table attributes int id | int thing_id | string thing_type | string name | string value | datetime created_at | int previous_version_id
foreign key (thing_id, thing_type) -> problems.id or solutions.id foreign key previous_version_id -> attributes.id This means that to load the current version of a Problem or Solution I have to fetch all versions of the attribute, sort them by date and then use the most current. That might not be terrible. What seems really bad to me is that I can't type-check these attributes in the database. That value column has to be free-text. I can make the name column a reference into a separate attribute_names table that has a type column, but that doesn't force the correct type in the attributes table. later still: response to @Eric Beard's comments about multi-table foreign keys: Alas, what I've described is simplistic: there are only two types of Things (Problems and Solutions). I actually have about 9 or 10 different types of Things, so I'd have 9 or 10 columns of foreign keys under your strategy. I wanted to use single-table inheritance, but the Things have so little in common that it would be extremely wasteful to do combine them into one table. | Hmm, sounds kind of like this site... As far as a database design would go, a versioning system kind of like SVN, where you never actually do any updates, just inserts (with a version number) when things change, might be what you need. This is called MVCC, Multi-Value Concurrency Control. A wiki is another good example of this. | Design debate: what are good ways to store and manipulate versioned objects? I am intentionally leaving this quite vague at first. I'm looking for discussion and what issues are important more than I'm looking for hard answers. I'm in the middle of designing an app that does something like portfolio management. The design I have so far is Problem: a problem that needs to be solved Solution: a proposed solution to one or more problems Relationship: a relationship among two problems, two solutions, or a problem and a solution. Further broken down into: Parent-child - some sort of categorization / tree hierarchy Overlap - the degree to which two solutions or two problems really address the same concept Addresses - the degree to which a problem addresses a solution My question is about the temporal nature of these things. Problems crop up, then fade. Solutions have an expected resolution date, but that might be modified as they are developed. The degree of a relationship might change over time as problems and solutions evolve. So, the question: what is the best design for versioning of these things so I can get both a current and an historical perspective of my portfolio? Later: perhaps I should make this a more specific question, though @Eric Beard's answer is worth an up. I've considered three database designs. I'll enough of each to show their drawbacks. My question is: which to pick, or can you think of something better? 1: Problems (and separately, Solutions) are self-referential in versioning. table problems int id | string name | text description | datetime created_at | int previous_version_id
foreign key previous_version_id -> problems.id This is problematic because every time I want a new version, I have to duplicate the entire row, including that long description column. 2: Create a new Relationship type: Version. table problems int id | string name | text description | datetime created_at This simply moves the relationship from the Problems and Solutions tables into the Relationships table. Same duplication problem, but perhaps a little "cleaner" since I already have an abstract Relationship concept. 3: Use a more Subversion-like structure; move all Problem and Solution attributes into a separate table and version them. table problems int id
table attributes int id | int thing_id | string thing_type | string name | string value | datetime created_at | int previous_version_id
foreign key (thing_id, thing_type) -> problems.id or solutions.id foreign key previous_version_id -> attributes.id This means that to load the current version of a Problem or Solution I have to fetch all versions of the attribute, sort them by date and then use the most current. That might not be terrible. What seems really bad to me is that I can't type-check these attributes in the database. That value column has to be free-text. I can make the name column a reference into a separate attribute_names table that has a type column, but that doesn't force the correct type in the attributes table. later still: response to @Eric Beard's comments about multi-table foreign keys: Alas, what I've described is simplistic: there are only two types of Things (Problems and Solutions). I actually have about 9 or 10 different types of Things, so I'd have 9 or 10 columns of foreign keys under your strategy. I wanted to use single-table inheritance, but the Things have so little in common that it would be extremely wasteful to do combine them into one table. | TITLE:
Design debate: what are good ways to store and manipulate versioned objects?
QUESTION:
I am intentionally leaving this quite vague at first. I'm looking for discussion and what issues are important more than I'm looking for hard answers. I'm in the middle of designing an app that does something like portfolio management. The design I have so far is Problem: a problem that needs to be solved Solution: a proposed solution to one or more problems Relationship: a relationship among two problems, two solutions, or a problem and a solution. Further broken down into: Parent-child - some sort of categorization / tree hierarchy Overlap - the degree to which two solutions or two problems really address the same concept Addresses - the degree to which a problem addresses a solution My question is about the temporal nature of these things. Problems crop up, then fade. Solutions have an expected resolution date, but that might be modified as they are developed. The degree of a relationship might change over time as problems and solutions evolve. So, the question: what is the best design for versioning of these things so I can get both a current and an historical perspective of my portfolio? Later: perhaps I should make this a more specific question, though @Eric Beard's answer is worth an up. I've considered three database designs. I'll enough of each to show their drawbacks. My question is: which to pick, or can you think of something better? 1: Problems (and separately, Solutions) are self-referential in versioning. table problems int id | string name | text description | datetime created_at | int previous_version_id
foreign key previous_version_id -> problems.id This is problematic because every time I want a new version, I have to duplicate the entire row, including that long description column. 2: Create a new Relationship type: Version. table problems int id | string name | text description | datetime created_at This simply moves the relationship from the Problems and Solutions tables into the Relationships table. Same duplication problem, but perhaps a little "cleaner" since I already have an abstract Relationship concept. 3: Use a more Subversion-like structure; move all Problem and Solution attributes into a separate table and version them. table problems int id
table attributes int id | int thing_id | string thing_type | string name | string value | datetime created_at | int previous_version_id
foreign key (thing_id, thing_type) -> problems.id or solutions.id foreign key previous_version_id -> attributes.id This means that to load the current version of a Problem or Solution I have to fetch all versions of the attribute, sort them by date and then use the most current. That might not be terrible. What seems really bad to me is that I can't type-check these attributes in the database. That value column has to be free-text. I can make the name column a reference into a separate attribute_names table that has a type column, but that doesn't force the correct type in the attributes table. later still: response to @Eric Beard's comments about multi-table foreign keys: Alas, what I've described is simplistic: there are only two types of Things (Problems and Solutions). I actually have about 9 or 10 different types of Things, so I'd have 9 or 10 columns of foreign keys under your strategy. I wanted to use single-table inheritance, but the Things have so little in common that it would be extremely wasteful to do combine them into one table.
ANSWER:
Hmm, sounds kind of like this site... As far as a database design would go, a versioning system kind of like SVN, where you never actually do any updates, just inserts (with a version number) when things change, might be what you need. This is called MVCC, Multi-Value Concurrency Control. A wiki is another good example of this. | [
"architecture",
"time",
"rdbms",
"versions"
] | 2 | 1 | 398 | 5 | 0 | 2008-08-14T20:50:11.847000 | 2008-08-14T20:57:36.573000 |
11,690 | 11,700 | How can I get Unicode characters to display properly for the tooltip for the IMG ALT in IE7? | I've got some Japanese in the ALT attribute, but the tooltip is showing me the ugly block characters in the tooltip. The rest of the content on the page renders correctly. So far, it seems to be limited to the tooltips. | This is because the font used in the tooltip doesn't include the characters you are trying to display. Try installing a font pack that includes those characters. I'm affraid you can't do much for your site's visitors other than implementating a tooltip yourself using javascript. | How can I get Unicode characters to display properly for the tooltip for the IMG ALT in IE7? I've got some Japanese in the ALT attribute, but the tooltip is showing me the ugly block characters in the tooltip. The rest of the content on the page renders correctly. So far, it seems to be limited to the tooltips. | TITLE:
How can I get Unicode characters to display properly for the tooltip for the IMG ALT in IE7?
QUESTION:
I've got some Japanese in the ALT attribute, but the tooltip is showing me the ugly block characters in the tooltip. The rest of the content on the page renders correctly. So far, it seems to be limited to the tooltips.
ANSWER:
This is because the font used in the tooltip doesn't include the characters you are trying to display. Try installing a font pack that includes those characters. I'm affraid you can't do much for your site's visitors other than implementating a tooltip yourself using javascript. | [
"internet-explorer",
"unicode"
] | 6 | 5 | 3,385 | 6 | 0 | 2008-08-14T20:50:31.470000 | 2008-08-14T21:04:22.160000 |
11,720 | 24,369 | How can I create virtual machines as part of a build process using MSBuild and MS Virtual Server and/or Hyper-V Server Virtualization? | What I would like to do is create a clean virtual machine image as the output of a build of an application. So a new virtual machine would be created (from a template is fine, with the OS installed, and some base software installed) --- a new web site would be created in IIS, and the web app build output copied to a location on the virtual machine hard disk, and IIS configured correctly, the VM would start up and run. I know there are MSBuild tasks to script all the administrative actions in IIS, but how do you script all the actions with Virtual machines? Specifically, creating a new virtual machine from a template, naming it uniquely, starting it, configuring it, etc... Specifically I was wondering if anyone has successfully implemented any VM scripting as part of a build process. Update: I assume with Hyper-V, there is a different set of libraries/APIs to script virtual machines, anyone played around with this? And anyone with real practical experience of doing something like this? | Checkout Powershell Management library for Hyper-V on CodePlex. Some features: Finding a VM Connecting to a VM Discovering and manipulating Machine states Backing up, exporting and snapshotting VMs Adding and removing VMs, configuring motherboard settings. Manipulating Disk controllers, drives and disk images Manipluating Network Interface Cards Working with VHD files | How can I create virtual machines as part of a build process using MSBuild and MS Virtual Server and/or Hyper-V Server Virtualization? What I would like to do is create a clean virtual machine image as the output of a build of an application. So a new virtual machine would be created (from a template is fine, with the OS installed, and some base software installed) --- a new web site would be created in IIS, and the web app build output copied to a location on the virtual machine hard disk, and IIS configured correctly, the VM would start up and run. I know there are MSBuild tasks to script all the administrative actions in IIS, but how do you script all the actions with Virtual machines? Specifically, creating a new virtual machine from a template, naming it uniquely, starting it, configuring it, etc... Specifically I was wondering if anyone has successfully implemented any VM scripting as part of a build process. Update: I assume with Hyper-V, there is a different set of libraries/APIs to script virtual machines, anyone played around with this? And anyone with real practical experience of doing something like this? | TITLE:
How can I create virtual machines as part of a build process using MSBuild and MS Virtual Server and/or Hyper-V Server Virtualization?
QUESTION:
What I would like to do is create a clean virtual machine image as the output of a build of an application. So a new virtual machine would be created (from a template is fine, with the OS installed, and some base software installed) --- a new web site would be created in IIS, and the web app build output copied to a location on the virtual machine hard disk, and IIS configured correctly, the VM would start up and run. I know there are MSBuild tasks to script all the administrative actions in IIS, but how do you script all the actions with Virtual machines? Specifically, creating a new virtual machine from a template, naming it uniquely, starting it, configuring it, etc... Specifically I was wondering if anyone has successfully implemented any VM scripting as part of a build process. Update: I assume with Hyper-V, there is a different set of libraries/APIs to script virtual machines, anyone played around with this? And anyone with real practical experience of doing something like this?
ANSWER:
Checkout Powershell Management library for Hyper-V on CodePlex. Some features: Finding a VM Connecting to a VM Discovering and manipulating Machine states Backing up, exporting and snapshotting VMs Adding and removing VMs, configuring motherboard settings. Manipulating Disk controllers, drives and disk images Manipluating Network Interface Cards Working with VHD files | [
"msbuild",
"virtualization",
"hyper-v"
] | 15 | 3 | 2,196 | 2 | 0 | 2008-08-14T21:32:34.287000 | 2008-08-23T16:50:42.273000 |
11,724 | 12,989 | In Visual Studio you must be a member of Debug Users or Administrators to start debugging. What if you are but it doesn't work? | On my Windows XP machine Visual Studio 2003 2005 and 2008 all complain that I cannot start debugging my web application because I must either be a member of the Debug Users group or of the Administrators group. So, I am an Administrator and I added Debug Users just in case, and it still complains. Short of reformatting my machine and starting over, has anyone encountered this and fixed it [with some undocumented command]? | Which users and/or groups are in your "Debug programs" right (under User Rights Assignment)? Maybe that setting got overridden by group policy (Daniel's answer), or just got out of whack for some reason. It should, obviously, include the "Debug Users" group. | In Visual Studio you must be a member of Debug Users or Administrators to start debugging. What if you are but it doesn't work? On my Windows XP machine Visual Studio 2003 2005 and 2008 all complain that I cannot start debugging my web application because I must either be a member of the Debug Users group or of the Administrators group. So, I am an Administrator and I added Debug Users just in case, and it still complains. Short of reformatting my machine and starting over, has anyone encountered this and fixed it [with some undocumented command]? | TITLE:
In Visual Studio you must be a member of Debug Users or Administrators to start debugging. What if you are but it doesn't work?
QUESTION:
On my Windows XP machine Visual Studio 2003 2005 and 2008 all complain that I cannot start debugging my web application because I must either be a member of the Debug Users group or of the Administrators group. So, I am an Administrator and I added Debug Users just in case, and it still complains. Short of reformatting my machine and starting over, has anyone encountered this and fixed it [with some undocumented command]?
ANSWER:
Which users and/or groups are in your "Debug programs" right (under User Rights Assignment)? Maybe that setting got overridden by group policy (Daniel's answer), or just got out of whack for some reason. It should, obviously, include the "Debug Users" group. | [
"visual-studio",
"debugging",
"permissions"
] | 0 | 2 | 3,161 | 4 | 0 | 2008-08-14T21:48:45.660000 | 2008-08-16T04:29:43.047000 |
11,734 | 11,735 | How to intercept and cancel auto play from an application? | I am developing an application to install a large number of data files from multiple DVDs. The application will prompt the user to insert the next disk, however Windows will automatically try to open that disk either in an explorer window or ask the user what to do with the new disk. How can I intercept and cancel auto play messages from my application? | There are two approaches that I know of. The first and simplest is to register the special Windows message "QueryCancelAutoPlay" and simply return 1 when the message is handled. This only works for the current window, and not a background application. The second approach requires inserting an object that implements the COM interface IQueryCancelAutoPlay COM interface into the Running Object Table. | How to intercept and cancel auto play from an application? I am developing an application to install a large number of data files from multiple DVDs. The application will prompt the user to insert the next disk, however Windows will automatically try to open that disk either in an explorer window or ask the user what to do with the new disk. How can I intercept and cancel auto play messages from my application? | TITLE:
How to intercept and cancel auto play from an application?
QUESTION:
I am developing an application to install a large number of data files from multiple DVDs. The application will prompt the user to insert the next disk, however Windows will automatically try to open that disk either in an explorer window or ask the user what to do with the new disk. How can I intercept and cancel auto play messages from my application?
ANSWER:
There are two approaches that I know of. The first and simplest is to register the special Windows message "QueryCancelAutoPlay" and simply return 1 when the message is handled. This only works for the current window, and not a background application. The second approach requires inserting an object that implements the COM interface IQueryCancelAutoPlay COM interface into the Running Object Table. | [
"windows",
"disk"
] | 1 | 3 | 779 | 2 | 0 | 2008-08-14T22:29:57.633000 | 2008-08-14T22:30:37.570000 |
11,740 | 32,476 | Configurable Table Prefixes with a .Net OR/M? | In a web application like wiki or forums or blogging software, it is often useful to store your data in a relational database. Since many hosting companies offer a single database with their hosting plans (with additional databases costing extra) it is very useful for your users when your database objects (tables, views, constraints, and stored procedures) have a common prefix. It is typical for applications aware of database scarcity to have a hard-coded table prefix. I want more, however. Specifically, I'd like to have a table prefix that users can designate—say in the web.config file (with an appropriate default, of course). Since I hate coding CRUD operations by hand, I prefer to work through a competent OR/M and have used (and enjoyed) LINQ to SQL, Subsonic, and ADO.Net. I'm having some thrash in a new project, however, when it comes to putting a table prefix in a user's web.config file. Are there any.Net-based OR/M products that can handle this scenario elegantly? The best I have been able to come up with so far is using LINQ to SQL with an external mapping file that I'd have to update somehow based on an as-yet hypothetical web.config setting. Anyone have a better solution? I tried to make it happen in Entity Framework, but that turned into a mess quickly. (Due to my unfamiliarity with EF? Possibly.) How about SubSonic? Does it have an option to apply a table prefix besides at code generation time? | I've now researched what it takes to do this in both Entity Framework and LINQ to SQL and documented the steps required in each. It's much longer than answers here tend to be so I'll be content with a link to the answer rather than duplicate it here. It's relatively involved for each, but the LINQ to SQL is the more flexible solution and also the easiest to implment. | Configurable Table Prefixes with a .Net OR/M? In a web application like wiki or forums or blogging software, it is often useful to store your data in a relational database. Since many hosting companies offer a single database with their hosting plans (with additional databases costing extra) it is very useful for your users when your database objects (tables, views, constraints, and stored procedures) have a common prefix. It is typical for applications aware of database scarcity to have a hard-coded table prefix. I want more, however. Specifically, I'd like to have a table prefix that users can designate—say in the web.config file (with an appropriate default, of course). Since I hate coding CRUD operations by hand, I prefer to work through a competent OR/M and have used (and enjoyed) LINQ to SQL, Subsonic, and ADO.Net. I'm having some thrash in a new project, however, when it comes to putting a table prefix in a user's web.config file. Are there any.Net-based OR/M products that can handle this scenario elegantly? The best I have been able to come up with so far is using LINQ to SQL with an external mapping file that I'd have to update somehow based on an as-yet hypothetical web.config setting. Anyone have a better solution? I tried to make it happen in Entity Framework, but that turned into a mess quickly. (Due to my unfamiliarity with EF? Possibly.) How about SubSonic? Does it have an option to apply a table prefix besides at code generation time? | TITLE:
Configurable Table Prefixes with a .Net OR/M?
QUESTION:
In a web application like wiki or forums or blogging software, it is often useful to store your data in a relational database. Since many hosting companies offer a single database with their hosting plans (with additional databases costing extra) it is very useful for your users when your database objects (tables, views, constraints, and stored procedures) have a common prefix. It is typical for applications aware of database scarcity to have a hard-coded table prefix. I want more, however. Specifically, I'd like to have a table prefix that users can designate—say in the web.config file (with an appropriate default, of course). Since I hate coding CRUD operations by hand, I prefer to work through a competent OR/M and have used (and enjoyed) LINQ to SQL, Subsonic, and ADO.Net. I'm having some thrash in a new project, however, when it comes to putting a table prefix in a user's web.config file. Are there any.Net-based OR/M products that can handle this scenario elegantly? The best I have been able to come up with so far is using LINQ to SQL with an external mapping file that I'd have to update somehow based on an as-yet hypothetical web.config setting. Anyone have a better solution? I tried to make it happen in Entity Framework, but that turned into a mess quickly. (Due to my unfamiliarity with EF? Possibly.) How about SubSonic? Does it have an option to apply a table prefix besides at code generation time?
ANSWER:
I've now researched what it takes to do this in both Entity Framework and LINQ to SQL and documented the steps required in each. It's much longer than answers here tend to be so I'll be content with a link to the answer rather than duplicate it here. It's relatively involved for each, but the LINQ to SQL is the more flexible solution and also the easiest to implment. | [
".net",
"orm"
] | 4 | 2 | 1,143 | 3 | 0 | 2008-08-14T22:32:58.860000 | 2008-08-28T14:49:41.663000 |
11,761 | 11,826 | best way to persist data in .NET Web Service | I have a web service that queries data from this json file, but I don't want the web service to have to access the file every time. I'm thinking that maybe I can store the data somewhere else (maybe in memory) so the web service can just get the data from there the next time it's trying to query the same data. I kinda understand what needs to be done but I'm just not sure how to actually do it. How do we persist data in a web service? Update: Both suggestions, caching and using static variables, look good. Maybe I should just use both so I can look at one first, and if it's not in there, use the second one, if it's not in there either, then I'll look at the json file. | Extending on Ice^^Heat 's idea, you might want to think about where you would cache - either cache the contents of the json file in the Application cache like so: Context.Cache.Insert("foo", _ Foo, _ Nothing, _ DateAdd(DateInterval.Minute, 30, Now()), _ System.Web.Caching.Cache.NoSlidingExpiration) And then generate the results you need from that on every hit. Alternatively you can cache the webservice output on the function definition: _ Public Function HelloWorld() As String Return "Hello World" End Function Info gathered from XML Web Service Caching Strategies. | best way to persist data in .NET Web Service I have a web service that queries data from this json file, but I don't want the web service to have to access the file every time. I'm thinking that maybe I can store the data somewhere else (maybe in memory) so the web service can just get the data from there the next time it's trying to query the same data. I kinda understand what needs to be done but I'm just not sure how to actually do it. How do we persist data in a web service? Update: Both suggestions, caching and using static variables, look good. Maybe I should just use both so I can look at one first, and if it's not in there, use the second one, if it's not in there either, then I'll look at the json file. | TITLE:
best way to persist data in .NET Web Service
QUESTION:
I have a web service that queries data from this json file, but I don't want the web service to have to access the file every time. I'm thinking that maybe I can store the data somewhere else (maybe in memory) so the web service can just get the data from there the next time it's trying to query the same data. I kinda understand what needs to be done but I'm just not sure how to actually do it. How do we persist data in a web service? Update: Both suggestions, caching and using static variables, look good. Maybe I should just use both so I can look at one first, and if it's not in there, use the second one, if it's not in there either, then I'll look at the json file.
ANSWER:
Extending on Ice^^Heat 's idea, you might want to think about where you would cache - either cache the contents of the json file in the Application cache like so: Context.Cache.Insert("foo", _ Foo, _ Nothing, _ DateAdd(DateInterval.Minute, 30, Now()), _ System.Web.Caching.Cache.NoSlidingExpiration) And then generate the results you need from that on every hit. Alternatively you can cache the webservice output on the function definition: _ Public Function HelloWorld() As String Return "Hello World" End Function Info gathered from XML Web Service Caching Strategies. | [
".net",
"web-services",
"json",
"memory",
"persistence"
] | 5 | 6 | 9,150 | 4 | 0 | 2008-08-14T23:13:32.493000 | 2008-08-15T00:32:04.923000 |
11,762 | 26,283 | Why does a bad password cause "Padding is invalid and cannot be removed"? | I needed some simple string encryption, so I wrote the following code (with a great deal of "inspiration" from here ): // create and initialize a crypto algorithm private static SymmetricAlgorithm getAlgorithm(string password) { SymmetricAlgorithm algorithm = Rijndael.Create(); Rfc2898DeriveBytes rdb = new Rfc2898DeriveBytes( password, new byte[] { 0x53,0x6f,0x64,0x69,0x75,0x6d,0x20, // salty goodness 0x43,0x68,0x6c,0x6f,0x72,0x69,0x64,0x65 } ); algorithm.Padding = PaddingMode.ISO10126; algorithm.Key = rdb.GetBytes(32); algorithm.IV = rdb.GetBytes(16); return algorithm; }
/* * encryptString * provides simple encryption of a string, with a given password */ public static string encryptString(string clearText, string password) { SymmetricAlgorithm algorithm = getAlgorithm(password); byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, algorithm.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(clearBytes, 0, clearBytes.Length); cs.Close(); return Convert.ToBase64String(ms.ToArray()); }
/* * decryptString * provides simple decryption of a string, with a given password */ public static string decryptString(string cipherText, string password) { SymmetricAlgorithm algorithm = getAlgorithm(password); byte[] cipherBytes = Convert.FromBase64String(cipherText); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, algorithm.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(cipherBytes, 0, cipherBytes.Length); cs.Close(); return System.Text.Encoding.Unicode.GetString(ms.ToArray()); } The code appears to work fine, except that when decrypting data with an incorrect key, I get a CryptographicException - "Padding is invalid and cannot be removed" - on the cs.Close() line in decryptString. example code: string password1 = "password"; string password2 = "letmein"; string startClearText = "The quick brown fox jumps over the lazy dog"; string cipherText = encryptString(startClearText, password1); string endClearText = decryptString(cipherText, password2); // exception thrown My question is, is this to be expected? I would have thought that decrypting with the wrong password would just result in nonsense output, rather than an exception. | Although this have been already answered I think it would be a good idea to explain why it is to be expected. A padding scheme is usually applied because most cryptographic filters are not semantically secure and to prevent some forms of cryptoatacks. For example, usually in RSA the OAEP padding scheme is used which prevents some sorts of attacks (such as a chosen plaintext attack or blinding ). A padding scheme appends some (usually) random garbage to the message m before the message is sent. In the OAEP method, for example, two Oracles are used (this is a simplistic explanation): Given the size of the modulus you padd k1 bits with 0 and k0 bits with a random number. Then by applying some transformation to the message you obtain the padded message wich is encrypted and sent. That provides you with a randomization for the messages and with a way to test if the message is garbage or not. As the padding scheme is reversible, when you decrypt the message whereas you can't say anything about the integrity of the message itself you can, in fact, make some assertion about the padding and thus you can know if the message has been correctly decrypted or you're doing something wrong (i.e someone has tampered with the message or you're using the wrong key) | Why does a bad password cause "Padding is invalid and cannot be removed"? I needed some simple string encryption, so I wrote the following code (with a great deal of "inspiration" from here ): // create and initialize a crypto algorithm private static SymmetricAlgorithm getAlgorithm(string password) { SymmetricAlgorithm algorithm = Rijndael.Create(); Rfc2898DeriveBytes rdb = new Rfc2898DeriveBytes( password, new byte[] { 0x53,0x6f,0x64,0x69,0x75,0x6d,0x20, // salty goodness 0x43,0x68,0x6c,0x6f,0x72,0x69,0x64,0x65 } ); algorithm.Padding = PaddingMode.ISO10126; algorithm.Key = rdb.GetBytes(32); algorithm.IV = rdb.GetBytes(16); return algorithm; }
/* * encryptString * provides simple encryption of a string, with a given password */ public static string encryptString(string clearText, string password) { SymmetricAlgorithm algorithm = getAlgorithm(password); byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, algorithm.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(clearBytes, 0, clearBytes.Length); cs.Close(); return Convert.ToBase64String(ms.ToArray()); }
/* * decryptString * provides simple decryption of a string, with a given password */ public static string decryptString(string cipherText, string password) { SymmetricAlgorithm algorithm = getAlgorithm(password); byte[] cipherBytes = Convert.FromBase64String(cipherText); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, algorithm.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(cipherBytes, 0, cipherBytes.Length); cs.Close(); return System.Text.Encoding.Unicode.GetString(ms.ToArray()); } The code appears to work fine, except that when decrypting data with an incorrect key, I get a CryptographicException - "Padding is invalid and cannot be removed" - on the cs.Close() line in decryptString. example code: string password1 = "password"; string password2 = "letmein"; string startClearText = "The quick brown fox jumps over the lazy dog"; string cipherText = encryptString(startClearText, password1); string endClearText = decryptString(cipherText, password2); // exception thrown My question is, is this to be expected? I would have thought that decrypting with the wrong password would just result in nonsense output, rather than an exception. | TITLE:
Why does a bad password cause "Padding is invalid and cannot be removed"?
QUESTION:
I needed some simple string encryption, so I wrote the following code (with a great deal of "inspiration" from here ): // create and initialize a crypto algorithm private static SymmetricAlgorithm getAlgorithm(string password) { SymmetricAlgorithm algorithm = Rijndael.Create(); Rfc2898DeriveBytes rdb = new Rfc2898DeriveBytes( password, new byte[] { 0x53,0x6f,0x64,0x69,0x75,0x6d,0x20, // salty goodness 0x43,0x68,0x6c,0x6f,0x72,0x69,0x64,0x65 } ); algorithm.Padding = PaddingMode.ISO10126; algorithm.Key = rdb.GetBytes(32); algorithm.IV = rdb.GetBytes(16); return algorithm; }
/* * encryptString * provides simple encryption of a string, with a given password */ public static string encryptString(string clearText, string password) { SymmetricAlgorithm algorithm = getAlgorithm(password); byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, algorithm.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(clearBytes, 0, clearBytes.Length); cs.Close(); return Convert.ToBase64String(ms.ToArray()); }
/* * decryptString * provides simple decryption of a string, with a given password */ public static string decryptString(string cipherText, string password) { SymmetricAlgorithm algorithm = getAlgorithm(password); byte[] cipherBytes = Convert.FromBase64String(cipherText); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, algorithm.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(cipherBytes, 0, cipherBytes.Length); cs.Close(); return System.Text.Encoding.Unicode.GetString(ms.ToArray()); } The code appears to work fine, except that when decrypting data with an incorrect key, I get a CryptographicException - "Padding is invalid and cannot be removed" - on the cs.Close() line in decryptString. example code: string password1 = "password"; string password2 = "letmein"; string startClearText = "The quick brown fox jumps over the lazy dog"; string cipherText = encryptString(startClearText, password1); string endClearText = decryptString(cipherText, password2); // exception thrown My question is, is this to be expected? I would have thought that decrypting with the wrong password would just result in nonsense output, rather than an exception.
ANSWER:
Although this have been already answered I think it would be a good idea to explain why it is to be expected. A padding scheme is usually applied because most cryptographic filters are not semantically secure and to prevent some forms of cryptoatacks. For example, usually in RSA the OAEP padding scheme is used which prevents some sorts of attacks (such as a chosen plaintext attack or blinding ). A padding scheme appends some (usually) random garbage to the message m before the message is sent. In the OAEP method, for example, two Oracles are used (this is a simplistic explanation): Given the size of the modulus you padd k1 bits with 0 and k0 bits with a random number. Then by applying some transformation to the message you obtain the padded message wich is encrypted and sent. That provides you with a randomization for the messages and with a way to test if the message is garbage or not. As the padding scheme is reversible, when you decrypt the message whereas you can't say anything about the integrity of the message itself you can, in fact, make some assertion about the padding and thus you can know if the message has been correctly decrypted or you're doing something wrong (i.e someone has tampered with the message or you're using the wrong key) | [
"c#",
".net",
"exception",
"encryption"
] | 40 | 27 | 73,169 | 9 | 0 | 2008-08-14T23:14:38.823000 | 2008-08-25T15:46:00.960000 |
11,764 | 11,770 | Publishing to IIS - Best Practices | I'm not new to web publishing, BUT I am new to publishing against a web site that is frequently used. Previously, the apps on this server were not hit very often, but we're rolling out a high demand application. So, what is the best practice for publishing to a live web server? Is it best to wait until the middle of the night when people won't be on it (Yes, I can pretty much rely on that -- it's an intranet and therefore will have times of non-use) Publish when new updates are made to the trunk (dependent on build success of course) If 2 is true, then that seems bad if someone is using that specific page or DLL and it gets overwritten....I'm sure there are lots of great places for this kind of thing, but I didn't use the right google search terms. | @Nick DeVore wrote: If 2 is true, then that seems bad if someone is using that specific page or DLL and it gets overwritten. It's not really an issue if you're using ASP.NET stack (Webforms, MVC or rolling your own) because all your aspx files get compiled and therefore not touched by webserver. /bin/ folder is completely shadowed somewhere else, so libraries inside are not used by webserver either. IIS will wait until all requests are done (however there is some timeout though) and then will proceed with compilation (if needed) and restart of AppDomain. If only a few files have changed, there won't even be AppDomain restart. IIS will load new assemblies (or compiled aspx/asmx/ascx files) into existing AppDomain. @Nick DeVore wrote: Help me understand this a little bit more. Point me to the place where this is explained from Microsoft. Thanks! Try google for "IIS AppDomain" keywords. I found What ASP.NET Programmers Should Know About Application Domains. | Publishing to IIS - Best Practices I'm not new to web publishing, BUT I am new to publishing against a web site that is frequently used. Previously, the apps on this server were not hit very often, but we're rolling out a high demand application. So, what is the best practice for publishing to a live web server? Is it best to wait until the middle of the night when people won't be on it (Yes, I can pretty much rely on that -- it's an intranet and therefore will have times of non-use) Publish when new updates are made to the trunk (dependent on build success of course) If 2 is true, then that seems bad if someone is using that specific page or DLL and it gets overwritten....I'm sure there are lots of great places for this kind of thing, but I didn't use the right google search terms. | TITLE:
Publishing to IIS - Best Practices
QUESTION:
I'm not new to web publishing, BUT I am new to publishing against a web site that is frequently used. Previously, the apps on this server were not hit very often, but we're rolling out a high demand application. So, what is the best practice for publishing to a live web server? Is it best to wait until the middle of the night when people won't be on it (Yes, I can pretty much rely on that -- it's an intranet and therefore will have times of non-use) Publish when new updates are made to the trunk (dependent on build success of course) If 2 is true, then that seems bad if someone is using that specific page or DLL and it gets overwritten....I'm sure there are lots of great places for this kind of thing, but I didn't use the right google search terms.
ANSWER:
@Nick DeVore wrote: If 2 is true, then that seems bad if someone is using that specific page or DLL and it gets overwritten. It's not really an issue if you're using ASP.NET stack (Webforms, MVC or rolling your own) because all your aspx files get compiled and therefore not touched by webserver. /bin/ folder is completely shadowed somewhere else, so libraries inside are not used by webserver either. IIS will wait until all requests are done (however there is some timeout though) and then will proceed with compilation (if needed) and restart of AppDomain. If only a few files have changed, there won't even be AppDomain restart. IIS will load new assemblies (or compiled aspx/asmx/ascx files) into existing AppDomain. @Nick DeVore wrote: Help me understand this a little bit more. Point me to the place where this is explained from Microsoft. Thanks! Try google for "IIS AppDomain" keywords. I found What ASP.NET Programmers Should Know About Application Domains. | [
"iis",
"publish"
] | 5 | 2 | 2,235 | 2 | 0 | 2008-08-14T23:15:59.447000 | 2008-08-14T23:21:58.387000 |
11,801 | 11,803 | What's the general consensus on supporting Windows 2000? | What's the general consensus on supporting Windows 2000 for software distribution? Are people supporting Windows XP SP2+ for new software development or is this too restrictive still? | "OK" is a subjective judgement. You'll need to take a look at your client base and see what they're using. Having said that, I dropped support for Win2K over a year ago with no negative impact. | What's the general consensus on supporting Windows 2000? What's the general consensus on supporting Windows 2000 for software distribution? Are people supporting Windows XP SP2+ for new software development or is this too restrictive still? | TITLE:
What's the general consensus on supporting Windows 2000?
QUESTION:
What's the general consensus on supporting Windows 2000 for software distribution? Are people supporting Windows XP SP2+ for new software development or is this too restrictive still?
ANSWER:
"OK" is a subjective judgement. You'll need to take a look at your client base and see what they're using. Having said that, I dropped support for Win2K over a year ago with no negative impact. | [
"windows",
"deployment",
"compatibility"
] | 5 | 8 | 388 | 9 | 0 | 2008-08-15T00:05:13.760000 | 2008-08-15T00:07:22.867000 |
11,804 | 920,922 | Returning Large Results Via a Webservice | I'm working on a web service at the moment and there is the potential that the returned results could be quite large ( > 5mb). It's perfectly valid for this set of data to be this large and the web service can be called either sync or async, but I'm wondering what people's thoughts are on the following: If the connection is lost, the entire resultset will have to be regenerated and sent again. Is there any way I can do any sort of "resume" if the connection is lost or reset? Is sending a result set this large even appropriate? Would it be better to implement some sort of "paging" where the resultset is generated and stored on the server and the client can then download chunks of the resultset in smaller amounts and re-assemble the set at their end? | I have seen all three approaches, paged, store and retrieve, and massive push. I think the solution to your problem depends to some extent on why your result set is so large and how it is generated. Do your results grow over time, are they calculated all at once and then pushed, do you want to stream them back as soon as you have them? Paging Approach In my experience, using a paging approach is appropriate when the client needs quick access to reasonably sized chunks of the result set similar to pages in search results. Considerations here are overall chattiness of your protocol, caching of the entire result set between client page requests, and/or the processing time it takes to generate a page of results. Store and retrieve Store and retrieve is useful when the results are not random access and the result set grows in size as the query is processed. Issues to consider here are complexity for clients and if you can provide the user with partial results or if you need to calculate all results before returning anything to the client (think sorting of results from distributed search engines). Massive Push The massive push approach is almost certainly flawed. Even if the client needs all of the information and it needs to be pushed in a monolithic result set, I would recommend taking the approach of WS-ReliableMessaging (either directly or through your own simplified version) and chunking your results. By doing this you ensure that the pieces reach the client can discard the chunk as soon as you get a receipt from the client can reduce the possible issues with memory consumption from having to retain 5MB of XML, DOM, or whatever in memory (assuming that you aren't processing the results in a streaming manner) on the server and client sides. Like others have said though, don't do anything until you know your result set size, how it is generated, and overall performance to be actual issues. | Returning Large Results Via a Webservice I'm working on a web service at the moment and there is the potential that the returned results could be quite large ( > 5mb). It's perfectly valid for this set of data to be this large and the web service can be called either sync or async, but I'm wondering what people's thoughts are on the following: If the connection is lost, the entire resultset will have to be regenerated and sent again. Is there any way I can do any sort of "resume" if the connection is lost or reset? Is sending a result set this large even appropriate? Would it be better to implement some sort of "paging" where the resultset is generated and stored on the server and the client can then download chunks of the resultset in smaller amounts and re-assemble the set at their end? | TITLE:
Returning Large Results Via a Webservice
QUESTION:
I'm working on a web service at the moment and there is the potential that the returned results could be quite large ( > 5mb). It's perfectly valid for this set of data to be this large and the web service can be called either sync or async, but I'm wondering what people's thoughts are on the following: If the connection is lost, the entire resultset will have to be regenerated and sent again. Is there any way I can do any sort of "resume" if the connection is lost or reset? Is sending a result set this large even appropriate? Would it be better to implement some sort of "paging" where the resultset is generated and stored on the server and the client can then download chunks of the resultset in smaller amounts and re-assemble the set at their end?
ANSWER:
I have seen all three approaches, paged, store and retrieve, and massive push. I think the solution to your problem depends to some extent on why your result set is so large and how it is generated. Do your results grow over time, are they calculated all at once and then pushed, do you want to stream them back as soon as you have them? Paging Approach In my experience, using a paging approach is appropriate when the client needs quick access to reasonably sized chunks of the result set similar to pages in search results. Considerations here are overall chattiness of your protocol, caching of the entire result set between client page requests, and/or the processing time it takes to generate a page of results. Store and retrieve Store and retrieve is useful when the results are not random access and the result set grows in size as the query is processed. Issues to consider here are complexity for clients and if you can provide the user with partial results or if you need to calculate all results before returning anything to the client (think sorting of results from distributed search engines). Massive Push The massive push approach is almost certainly flawed. Even if the client needs all of the information and it needs to be pushed in a monolithic result set, I would recommend taking the approach of WS-ReliableMessaging (either directly or through your own simplified version) and chunking your results. By doing this you ensure that the pieces reach the client can discard the chunk as soon as you get a receipt from the client can reduce the possible issues with memory consumption from having to retain 5MB of XML, DOM, or whatever in memory (assuming that you aren't processing the results in a streaming manner) on the server and client sides. Like others have said though, don't do anything until you know your result set size, how it is generated, and overall performance to be actual issues. | [
"c#",
".net",
"web-services"
] | 9 | 3 | 3,815 | 4 | 0 | 2008-08-15T00:08:15.533000 | 2009-05-28T13:47:30.103000 |
11,806 | 448,051 | How do you impersonate an Active Directory user in Powershell? | I'm trying to run powershell commands through a web interface (ASP.NET/C#) in order to create mailboxes/etc on Exchange 2007. When I run the page using Visual Studio (Cassini), the page loads up correctly. However, when I run it on IIS (v5.1), I get the error "unknown user name or bad password". The biggest problem that I noticed was that Powershell was logged in as ASPNET instead of my Active Directory Account. How do I force my Powershell session to be authenticated with another Active Directory Account? Basically, the script that I have so far looks something like this: RunspaceConfiguration rc = RunspaceConfiguration.Create(); PSSnapInException snapEx = null; rc.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out snapEx);
Runspace runspace = RunspaceFactory.CreateRunspace(rc); runspace.Open();
Pipeline pipeline = runspace.CreatePipeline(); using (pipeline) { pipeline.Commands.AddScript("Get-Mailbox -identity 'user.name'"); pipeline.Commands.Add("Out-String");
Collection results = pipeline.Invoke();
if (pipeline.Error!= null && pipeline.Error.Count > 0) { foreach (object item in pipeline.Error.ReadToEnd()) resultString += "Error: " + item.ToString() + "\n"; }
runspace.Close();
foreach (PSObject obj in results) resultString += obj.ToString(); }
return resultString; | Exchange 2007 doesn't allow you to impersonate a user for security reasons. This means that it is impossible (at the moment) to create mailboxes by impersonating a user. In order to get around this problem, I created a web service which runs under AD user which has permissions to create email acounts, etc. You can then access this webservice to get access to powershell. Please remember to add the necessary security because this could potentially be a huge security hole. | How do you impersonate an Active Directory user in Powershell? I'm trying to run powershell commands through a web interface (ASP.NET/C#) in order to create mailboxes/etc on Exchange 2007. When I run the page using Visual Studio (Cassini), the page loads up correctly. However, when I run it on IIS (v5.1), I get the error "unknown user name or bad password". The biggest problem that I noticed was that Powershell was logged in as ASPNET instead of my Active Directory Account. How do I force my Powershell session to be authenticated with another Active Directory Account? Basically, the script that I have so far looks something like this: RunspaceConfiguration rc = RunspaceConfiguration.Create(); PSSnapInException snapEx = null; rc.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out snapEx);
Runspace runspace = RunspaceFactory.CreateRunspace(rc); runspace.Open();
Pipeline pipeline = runspace.CreatePipeline(); using (pipeline) { pipeline.Commands.AddScript("Get-Mailbox -identity 'user.name'"); pipeline.Commands.Add("Out-String");
Collection results = pipeline.Invoke();
if (pipeline.Error!= null && pipeline.Error.Count > 0) { foreach (object item in pipeline.Error.ReadToEnd()) resultString += "Error: " + item.ToString() + "\n"; }
runspace.Close();
foreach (PSObject obj in results) resultString += obj.ToString(); }
return resultString; | TITLE:
How do you impersonate an Active Directory user in Powershell?
QUESTION:
I'm trying to run powershell commands through a web interface (ASP.NET/C#) in order to create mailboxes/etc on Exchange 2007. When I run the page using Visual Studio (Cassini), the page loads up correctly. However, when I run it on IIS (v5.1), I get the error "unknown user name or bad password". The biggest problem that I noticed was that Powershell was logged in as ASPNET instead of my Active Directory Account. How do I force my Powershell session to be authenticated with another Active Directory Account? Basically, the script that I have so far looks something like this: RunspaceConfiguration rc = RunspaceConfiguration.Create(); PSSnapInException snapEx = null; rc.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out snapEx);
Runspace runspace = RunspaceFactory.CreateRunspace(rc); runspace.Open();
Pipeline pipeline = runspace.CreatePipeline(); using (pipeline) { pipeline.Commands.AddScript("Get-Mailbox -identity 'user.name'"); pipeline.Commands.Add("Out-String");
Collection results = pipeline.Invoke();
if (pipeline.Error!= null && pipeline.Error.Count > 0) { foreach (object item in pipeline.Error.ReadToEnd()) resultString += "Error: " + item.ToString() + "\n"; }
runspace.Close();
foreach (PSObject obj in results) resultString += obj.ToString(); }
return resultString;
ANSWER:
Exchange 2007 doesn't allow you to impersonate a user for security reasons. This means that it is impossible (at the moment) to create mailboxes by impersonating a user. In order to get around this problem, I created a web service which runs under AD user which has permissions to create email acounts, etc. You can then access this webservice to get access to powershell. Please remember to add the necessary security because this could potentially be a huge security hole. | [
"c#",
"asp.net",
"powershell",
"active-directory"
] | 13 | 1 | 15,659 | 4 | 0 | 2008-08-15T00:09:16.407000 | 2009-01-15T19:12:44.033000 |
11,809 | 11,815 | How to create an all browser-compatible hanging indent style in CSS in a span | The only thing I've found has been;.hang { text-indent: -3em; margin-left: 3em; } The only way for this to work is putting text in a paragraph, which causes those horribly unsightly extra lines. I'd much rather just have them in a type of thing. I'm also looking for a way to further indent than just a single-level of hanging. Using paragraphs to stack the indentions doesn't work. | is an inline element. The term hanging indent is meaningless unless you're talking about a paragraph (which generally means a block element). You can, of course, change the margins on or or any other block element to get rid of extra vertical space between paragraphs. You may want something like display: run-in, where the tag will become either block or inline depending on context... sadly, this is not yet universally supported by browsers. | How to create an all browser-compatible hanging indent style in CSS in a span The only thing I've found has been;.hang { text-indent: -3em; margin-left: 3em; } The only way for this to work is putting text in a paragraph, which causes those horribly unsightly extra lines. I'd much rather just have them in a type of thing. I'm also looking for a way to further indent than just a single-level of hanging. Using paragraphs to stack the indentions doesn't work. | TITLE:
How to create an all browser-compatible hanging indent style in CSS in a span
QUESTION:
The only thing I've found has been;.hang { text-indent: -3em; margin-left: 3em; } The only way for this to work is putting text in a paragraph, which causes those horribly unsightly extra lines. I'd much rather just have them in a type of thing. I'm also looking for a way to further indent than just a single-level of hanging. Using paragraphs to stack the indentions doesn't work.
ANSWER:
is an inline element. The term hanging indent is meaningless unless you're talking about a paragraph (which generally means a block element). You can, of course, change the margins on or or any other block element to get rid of extra vertical space between paragraphs. You may want something like display: run-in, where the tag will become either block or inline depending on context... sadly, this is not yet universally supported by browsers. | [
"html",
"css",
"indentation"
] | 33 | 17 | 30,109 | 3 | 0 | 2008-08-15T00:12:20.923000 | 2008-08-15T00:20:58.440000 |
11,820 | 11,832 | How much extra overhead is generated when sending a file over a web service as a byte array? | This question and answer shows how to send a file as a byte array through an XML web service. How much overhead is generated by using this method for file transfer? I assume the data looks something like this: 16 28 127... If this format is correct, the bytes must first be converted to UTF-8 characters. Each of these characters allocates 8 bytes. Are the bytes stored in base 10, hex, or binary characters? How much larger does the file appear as it is being sent due to the XML data and character encoding? Is compression built into web services? | Typically a byte array is sent as a base64 encoded string, not as individual bytes in tags. http://en.wikipedia.org/wiki/Base64 The base64 encoded version is about 137% of the size of the original content. | How much extra overhead is generated when sending a file over a web service as a byte array? This question and answer shows how to send a file as a byte array through an XML web service. How much overhead is generated by using this method for file transfer? I assume the data looks something like this: 16 28 127... If this format is correct, the bytes must first be converted to UTF-8 characters. Each of these characters allocates 8 bytes. Are the bytes stored in base 10, hex, or binary characters? How much larger does the file appear as it is being sent due to the XML data and character encoding? Is compression built into web services? | TITLE:
How much extra overhead is generated when sending a file over a web service as a byte array?
QUESTION:
This question and answer shows how to send a file as a byte array through an XML web service. How much overhead is generated by using this method for file transfer? I assume the data looks something like this: 16 28 127... If this format is correct, the bytes must first be converted to UTF-8 characters. Each of these characters allocates 8 bytes. Are the bytes stored in base 10, hex, or binary characters? How much larger does the file appear as it is being sent due to the XML data and character encoding? Is compression built into web services?
ANSWER:
Typically a byte array is sent as a base64 encoded string, not as individual bytes in tags. http://en.wikipedia.org/wiki/Base64 The base64 encoded version is about 137% of the size of the original content. | [
"xml",
"web-services"
] | 5 | 11 | 1,596 | 5 | 0 | 2008-08-15T00:29:57.563000 | 2008-08-15T00:39:05.987000 |
11,854 | 11,935 | Inheritance and Polymorphism - Ease of use vs Purity | In a project our team is using object lists to perform mass operations on sets of data that should all be processed in a similar way. In particular, different objects would ideally act the same, which would be very easily achieved with polymorphism. The problem I have with it is that inheritance implies the is a relationship, rather than the has a relationship. For example, several objects have a damage counter, but to make this easy to use in an object list, polymorphism could be used - except that would imply an is a relationship which wouldn't be true. (A person is not a damage counter.) The only solution I can think of is to have a member of the class return the proper object type when implicitly casted instead of relying on inheritance. Would it be better to forgo the is a / has a ideal in exchange for ease of programming? Edit: To be more specific, I am using C++, so using polymorphism would allow the different objects to "act the same" in the sense that the derived classes could reside within a single list and be operated upon by a virtual function of the base class. The use of an interface (or imitating them via inheritance) seems like a solution I would be willing to use. | This can be accomplished using multiple inheritance. In your specific case (C++), you can use pure virtual classes as interfaces. This allows you to have multiple inheritance without creating scope/ambiguity problems. Example: class Damage { virtual void addDamage(int d) = 0; virtual int getDamage() = 0; };
class Person: public virtual Damage { void addDamage(int d) { //... damage += d * 2; }
int getDamage() { return damage; } };
class Car: public virtual Damage { void addDamage(int d) { //... damage += d; }
int getDamage() { return damage; } }; Now both Person and Car 'is-a' Damage, meaning, they implement the Damage interface. The use of pure virtual classes (so that they are like interfaces) is key and should be used frequently. It insulates future changes from altering the entire system. Read up on the Open-Closed Principle for more information. | Inheritance and Polymorphism - Ease of use vs Purity In a project our team is using object lists to perform mass operations on sets of data that should all be processed in a similar way. In particular, different objects would ideally act the same, which would be very easily achieved with polymorphism. The problem I have with it is that inheritance implies the is a relationship, rather than the has a relationship. For example, several objects have a damage counter, but to make this easy to use in an object list, polymorphism could be used - except that would imply an is a relationship which wouldn't be true. (A person is not a damage counter.) The only solution I can think of is to have a member of the class return the proper object type when implicitly casted instead of relying on inheritance. Would it be better to forgo the is a / has a ideal in exchange for ease of programming? Edit: To be more specific, I am using C++, so using polymorphism would allow the different objects to "act the same" in the sense that the derived classes could reside within a single list and be operated upon by a virtual function of the base class. The use of an interface (or imitating them via inheritance) seems like a solution I would be willing to use. | TITLE:
Inheritance and Polymorphism - Ease of use vs Purity
QUESTION:
In a project our team is using object lists to perform mass operations on sets of data that should all be processed in a similar way. In particular, different objects would ideally act the same, which would be very easily achieved with polymorphism. The problem I have with it is that inheritance implies the is a relationship, rather than the has a relationship. For example, several objects have a damage counter, but to make this easy to use in an object list, polymorphism could be used - except that would imply an is a relationship which wouldn't be true. (A person is not a damage counter.) The only solution I can think of is to have a member of the class return the proper object type when implicitly casted instead of relying on inheritance. Would it be better to forgo the is a / has a ideal in exchange for ease of programming? Edit: To be more specific, I am using C++, so using polymorphism would allow the different objects to "act the same" in the sense that the derived classes could reside within a single list and be operated upon by a virtual function of the base class. The use of an interface (or imitating them via inheritance) seems like a solution I would be willing to use.
ANSWER:
This can be accomplished using multiple inheritance. In your specific case (C++), you can use pure virtual classes as interfaces. This allows you to have multiple inheritance without creating scope/ambiguity problems. Example: class Damage { virtual void addDamage(int d) = 0; virtual int getDamage() = 0; };
class Person: public virtual Damage { void addDamage(int d) { //... damage += d * 2; }
int getDamage() { return damage; } };
class Car: public virtual Damage { void addDamage(int d) { //... damage += d; }
int getDamage() { return damage; } }; Now both Person and Car 'is-a' Damage, meaning, they implement the Damage interface. The use of pure virtual classes (so that they are like interfaces) is key and should be used frequently. It insulates future changes from altering the entire system. Read up on the Open-Closed Principle for more information. | [
"c++",
"inheritance",
"oop",
"polymorphism"
] | 6 | 3 | 1,635 | 10 | 0 | 2008-08-15T01:00:47.690000 | 2008-08-15T03:41:05.930000 |
11,878 | 11,932 | Best .NET Solution for Frequently Changed Database | I am currently architecting a small CRUD applicaton. Their database is a huge mess and will be changing frequently over the course of the next 6 months to a year. What would you recommend for my data layer: 1) ORM (if so, which one?) 2) Linq2Sql 3) Stored Procedures 4) Parametrized Queries I really need a solution that will be dynamic enough (both fast and easy) where I can replace tables and add/delete columns frequently. Note: I do not have much experience with ORM (only a little SubSonic) and generally tend to use stored procedures so maybe that would be the way to go. I would love to learn Ling2Sql or NHibernate if either would allow for the situation I've described above. | One key thing to be aware of here is that if the database schema is changing frequently, you want to have some level of compile time type safety. I've found this to be a problem with NHibernate because it uses xml mapping files so if you change something in your database schema, you don't know until runtime that the mapping is broken. It will also be a problem with stored procs. Using Linq2Sql will give you the advantage of knowing where exactly your code is breaking when you change a schema at compile time. This for me, is something that would take precedence over everything else if I'm working with a frequently changing schema | Best .NET Solution for Frequently Changed Database I am currently architecting a small CRUD applicaton. Their database is a huge mess and will be changing frequently over the course of the next 6 months to a year. What would you recommend for my data layer: 1) ORM (if so, which one?) 2) Linq2Sql 3) Stored Procedures 4) Parametrized Queries I really need a solution that will be dynamic enough (both fast and easy) where I can replace tables and add/delete columns frequently. Note: I do not have much experience with ORM (only a little SubSonic) and generally tend to use stored procedures so maybe that would be the way to go. I would love to learn Ling2Sql or NHibernate if either would allow for the situation I've described above. | TITLE:
Best .NET Solution for Frequently Changed Database
QUESTION:
I am currently architecting a small CRUD applicaton. Their database is a huge mess and will be changing frequently over the course of the next 6 months to a year. What would you recommend for my data layer: 1) ORM (if so, which one?) 2) Linq2Sql 3) Stored Procedures 4) Parametrized Queries I really need a solution that will be dynamic enough (both fast and easy) where I can replace tables and add/delete columns frequently. Note: I do not have much experience with ORM (only a little SubSonic) and generally tend to use stored procedures so maybe that would be the way to go. I would love to learn Ling2Sql or NHibernate if either would allow for the situation I've described above.
ANSWER:
One key thing to be aware of here is that if the database schema is changing frequently, you want to have some level of compile time type safety. I've found this to be a problem with NHibernate because it uses xml mapping files so if you change something in your database schema, you don't know until runtime that the mapping is broken. It will also be a problem with stored procs. Using Linq2Sql will give you the advantage of knowing where exactly your code is breaking when you change a schema at compile time. This for me, is something that would take precedence over everything else if I'm working with a frequently changing schema | [
".net",
"database",
"change-management"
] | 8 | 6 | 863 | 12 | 0 | 2008-08-15T01:50:02.473000 | 2008-08-15T03:37:32.430000 |
11,879 | 11,899 | Is it possible to return objects from a WebService? | Instead of returning a common string, is there a way to return classic objects? If not: what are the best practices? Do you transpose your object to xml and rebuild the object on the other side? What are the other possibilities? | As mentioned, you can do this in.net via serialization. By default all native types are serializable so this happens automagically for you. However if you have complex types, you need to mark the object with the [Serializable] attribute. The same goes with complex types as properties. So for example you need to have: [Serializable] public class MyClass { public string MyString {get; set;}
[Serializable] public MyOtherClass MyOtherClassProperty {get; set;} } | Is it possible to return objects from a WebService? Instead of returning a common string, is there a way to return classic objects? If not: what are the best practices? Do you transpose your object to xml and rebuild the object on the other side? What are the other possibilities? | TITLE:
Is it possible to return objects from a WebService?
QUESTION:
Instead of returning a common string, is there a way to return classic objects? If not: what are the best practices? Do you transpose your object to xml and rebuild the object on the other side? What are the other possibilities?
ANSWER:
As mentioned, you can do this in.net via serialization. By default all native types are serializable so this happens automagically for you. However if you have complex types, you need to mark the object with the [Serializable] attribute. The same goes with complex types as properties. So for example you need to have: [Serializable] public class MyClass { public string MyString {get; set;}
[Serializable] public MyOtherClass MyOtherClassProperty {get; set;} } | [
"web-services"
] | 6 | 7 | 5,457 | 11 | 0 | 2008-08-15T01:51:48.663000 | 2008-08-15T02:23:16.150000 |
11,887 | 11,898 | sn.exe fails with Access Denied error message | I get an Access is Denied error message when I use the strong name tool to create a new key to sign a.NET assembly. This works just fine on a Windows XP machine but it does not work on my Vista machine. PS C:\users\brian\Dev\Projects\BELib\BELib> sn -k keypair.snk
Microsoft (R).NET Framework Strong Name Utility Version 3.5.21022.8 Copyright (c) Microsoft Corporation. All rights reserved.
Failed to generate a strong name key pair -- Access is denied. What causes this problem and how can I fix it? Are you running your PowerShell or Command Prompt as an Administrator? I found this to be the first place to look until you get used to User Access Control or by turning User Access Control off. Yes I have tried running PS and the regular command prompt as administrator. The same error message comes up. | Yes I have tried running PS and the regular command prompt as administrator. The same error message comes up. Another possible solution could be that you need to give your user account access to the key container located at C:\Documents and Settings\All Users\Application Data\Microsoft\Crypto\RSA\MachineKeys | sn.exe fails with Access Denied error message I get an Access is Denied error message when I use the strong name tool to create a new key to sign a.NET assembly. This works just fine on a Windows XP machine but it does not work on my Vista machine. PS C:\users\brian\Dev\Projects\BELib\BELib> sn -k keypair.snk
Microsoft (R).NET Framework Strong Name Utility Version 3.5.21022.8 Copyright (c) Microsoft Corporation. All rights reserved.
Failed to generate a strong name key pair -- Access is denied. What causes this problem and how can I fix it? Are you running your PowerShell or Command Prompt as an Administrator? I found this to be the first place to look until you get used to User Access Control or by turning User Access Control off. Yes I have tried running PS and the regular command prompt as administrator. The same error message comes up. | TITLE:
sn.exe fails with Access Denied error message
QUESTION:
I get an Access is Denied error message when I use the strong name tool to create a new key to sign a.NET assembly. This works just fine on a Windows XP machine but it does not work on my Vista machine. PS C:\users\brian\Dev\Projects\BELib\BELib> sn -k keypair.snk
Microsoft (R).NET Framework Strong Name Utility Version 3.5.21022.8 Copyright (c) Microsoft Corporation. All rights reserved.
Failed to generate a strong name key pair -- Access is denied. What causes this problem and how can I fix it? Are you running your PowerShell or Command Prompt as an Administrator? I found this to be the first place to look until you get used to User Access Control or by turning User Access Control off. Yes I have tried running PS and the regular command prompt as administrator. The same error message comes up.
ANSWER:
Yes I have tried running PS and the regular command prompt as administrator. The same error message comes up. Another possible solution could be that you need to give your user account access to the key container located at C:\Documents and Settings\All Users\Application Data\Microsoft\Crypto\RSA\MachineKeys | [
".net",
"strongname",
"sn.exe"
] | 15 | 31 | 8,654 | 6 | 0 | 2008-08-15T02:01:13.217000 | 2008-08-15T02:22:18.227000 |
11,903 | 13,820 | OpenID Attribute Exchange - should I use it? | My website will be using only OpenID for authentication. I'd like to pull user details down via attribute exchange, but attribute exchange seems to have caused a lot of grief for StackOverflow. What is the current state of play in the industry? Does any OpenID provider do a decent job of attribute exchange? Should I just steer away from OpenID attribute exchange altogether? How can I deal with inconsistent support for functionality? | Here on Stack Overflow, we're just using the Simple Registration extension for now, as there were some issues with Attribute Exchange (AX). The biggest was OpenID Providers (OP) not agreeing on which attribute type urls to use. The finalized spec for AX says that attribute urls should come from http://www.axschema.org/ However, some OPs, especially our favorite http://myopenid.com, recognize other urls. I wasn't going to keep a list of which ones were naughty and which were nice! The other problem was that most of the OPs I tried just didn't return information when queried with AX - I might have been doing something wrong (happens quite frequently:) ), but I had made relevant details public on my profiles and we're using the latest, most excellent.NET library, DotNetOpenId. We'll definitely revisit AX here on Stack Overflow when we get a little more time, as a seamless user experience is very important to us! | OpenID Attribute Exchange - should I use it? My website will be using only OpenID for authentication. I'd like to pull user details down via attribute exchange, but attribute exchange seems to have caused a lot of grief for StackOverflow. What is the current state of play in the industry? Does any OpenID provider do a decent job of attribute exchange? Should I just steer away from OpenID attribute exchange altogether? How can I deal with inconsistent support for functionality? | TITLE:
OpenID Attribute Exchange - should I use it?
QUESTION:
My website will be using only OpenID for authentication. I'd like to pull user details down via attribute exchange, but attribute exchange seems to have caused a lot of grief for StackOverflow. What is the current state of play in the industry? Does any OpenID provider do a decent job of attribute exchange? Should I just steer away from OpenID attribute exchange altogether? How can I deal with inconsistent support for functionality?
ANSWER:
Here on Stack Overflow, we're just using the Simple Registration extension for now, as there were some issues with Attribute Exchange (AX). The biggest was OpenID Providers (OP) not agreeing on which attribute type urls to use. The finalized spec for AX says that attribute urls should come from http://www.axschema.org/ However, some OPs, especially our favorite http://myopenid.com, recognize other urls. I wasn't going to keep a list of which ones were naughty and which were nice! The other problem was that most of the OPs I tried just didn't return information when queried with AX - I might have been doing something wrong (happens quite frequently:) ), but I had made relevant details public on my profiles and we're using the latest, most excellent.NET library, DotNetOpenId. We'll definitely revisit AX here on Stack Overflow when we get a little more time, as a seamless user experience is very important to us! | [
"authentication",
"openid"
] | 10 | 17 | 2,893 | 2 | 0 | 2008-08-15T02:29:50.553000 | 2008-08-17T18:42:03.340000 |
11,915 | 11,920 | RSS Feeds in ASP.NET MVC | How would you reccommend handling RSS Feeds in ASP.NET MVC? Using a third party library? Using the RSS stuff in the BCL? Just making an RSS view that renders the XML? Or something completely different? | Here is what I recommend: Create a class called RssResult that inherits off the abstract base class ActionResult. Override the ExecuteResult method. ExecuteResult has the ControllerContext passed to it by the caller and with this you can get the data and content type. Once you change the content type to rss, you will want to serialize the data to RSS (using your own code or another library) and write to the response. Create an action on a controller that you want to return rss and set the return type as RssResult. Grab the data from your model based on what you want to return. Then any request to this action will receive rss of whatever data you choose. That is probably the quickest and reusable way of returning rss has a response to a request in ASP.NET MVC. | RSS Feeds in ASP.NET MVC How would you reccommend handling RSS Feeds in ASP.NET MVC? Using a third party library? Using the RSS stuff in the BCL? Just making an RSS view that renders the XML? Or something completely different? | TITLE:
RSS Feeds in ASP.NET MVC
QUESTION:
How would you reccommend handling RSS Feeds in ASP.NET MVC? Using a third party library? Using the RSS stuff in the BCL? Just making an RSS view that renders the XML? Or something completely different?
ANSWER:
Here is what I recommend: Create a class called RssResult that inherits off the abstract base class ActionResult. Override the ExecuteResult method. ExecuteResult has the ControllerContext passed to it by the caller and with this you can get the data and content type. Once you change the content type to rss, you will want to serialize the data to RSS (using your own code or another library) and write to the response. Create an action on a controller that you want to return rss and set the return type as RssResult. Grab the data from your model based on what you want to return. Then any request to this action will receive rss of whatever data you choose. That is probably the quickest and reusable way of returning rss has a response to a request in ASP.NET MVC. | [
"asp.net-mvc",
"rss"
] | 115 | 65 | 44,617 | 5 | 0 | 2008-08-15T02:56:41.030000 | 2008-08-15T03:12:49.623000 |
11,919 | 11,924 | How do I get PHP and MySQL working on IIS 7.0? | Okay, I've looked all over the internet for a good solution to get PHP and MySQL working on IIS7.0. It's nearly impossible, I've tried it so many times and given up in vain. Please please help by linking some great step-by-step tutorial to adding PHP and MySQL on IIS7.0 from scratch. PHP and MySQL are essential for installing any CMS. | Have you taken a look at this: http://learn.iis.net/page.aspx/246/using-fastcgi-to-host-php-applications-on-iis7/ MySQL should be pretty straight forward. Let us know what problems you're encountering... | How do I get PHP and MySQL working on IIS 7.0? Okay, I've looked all over the internet for a good solution to get PHP and MySQL working on IIS7.0. It's nearly impossible, I've tried it so many times and given up in vain. Please please help by linking some great step-by-step tutorial to adding PHP and MySQL on IIS7.0 from scratch. PHP and MySQL are essential for installing any CMS. | TITLE:
How do I get PHP and MySQL working on IIS 7.0?
QUESTION:
Okay, I've looked all over the internet for a good solution to get PHP and MySQL working on IIS7.0. It's nearly impossible, I've tried it so many times and given up in vain. Please please help by linking some great step-by-step tutorial to adding PHP and MySQL on IIS7.0 from scratch. PHP and MySQL are essential for installing any CMS.
ANSWER:
Have you taken a look at this: http://learn.iis.net/page.aspx/246/using-fastcgi-to-host-php-applications-on-iis7/ MySQL should be pretty straight forward. Let us know what problems you're encountering... | [
"php",
"mysql",
"iis-7"
] | 10 | 6 | 10,109 | 7 | 0 | 2008-08-15T03:05:13.273000 | 2008-08-15T03:24:09.337000 |
11,926 | 11,957 | ASP.Net MVC route mapping | I'm new to MVC (and ASP.Net routing). I'm trying to map *.aspx to a controller called PageController. routes.MapRoute( "Page", "{name}.aspx", new { controller = "Page", action = "Index", id = "" } ); Wouldn't the code above map *.aspx to PageController? When I run this and type in any.aspx page I get the following error: The controller for path '/Page.aspx' could not be found or it does not implement the IController interface. Parameter name: controllerType Is there something I'm not doing here? | I just answered my own question. I had the routes backwards (Default was above page). Yeah, you have to put all custom routes above the Default route. So this brings up the next question... how does the "Default" route match (I assume they use regular expressions here) the "Page" route? The Default route matches based on what we call Convention over Configuration. Scott Guthrie explains it well in his first blog post on ASP.NET MVC. I recommend that you read through it and also his other posts. Keep in mind that these were posted based on the first CTP and the framework has changed. You can also find web cast on ASP.NET MVC on the asp.net site by Scott Hanselman. http://weblogs.asp.net/scottgu/archive/2007/11/13/asp-net-mvc-framework-part-1.aspx http://www.asp.net/MVC/ | ASP.Net MVC route mapping I'm new to MVC (and ASP.Net routing). I'm trying to map *.aspx to a controller called PageController. routes.MapRoute( "Page", "{name}.aspx", new { controller = "Page", action = "Index", id = "" } ); Wouldn't the code above map *.aspx to PageController? When I run this and type in any.aspx page I get the following error: The controller for path '/Page.aspx' could not be found or it does not implement the IController interface. Parameter name: controllerType Is there something I'm not doing here? | TITLE:
ASP.Net MVC route mapping
QUESTION:
I'm new to MVC (and ASP.Net routing). I'm trying to map *.aspx to a controller called PageController. routes.MapRoute( "Page", "{name}.aspx", new { controller = "Page", action = "Index", id = "" } ); Wouldn't the code above map *.aspx to PageController? When I run this and type in any.aspx page I get the following error: The controller for path '/Page.aspx' could not be found or it does not implement the IController interface. Parameter name: controllerType Is there something I'm not doing here?
ANSWER:
I just answered my own question. I had the routes backwards (Default was above page). Yeah, you have to put all custom routes above the Default route. So this brings up the next question... how does the "Default" route match (I assume they use regular expressions here) the "Page" route? The Default route matches based on what we call Convention over Configuration. Scott Guthrie explains it well in his first blog post on ASP.NET MVC. I recommend that you read through it and also his other posts. Keep in mind that these were posted based on the first CTP and the framework has changed. You can also find web cast on ASP.NET MVC on the asp.net site by Scott Hanselman. http://weblogs.asp.net/scottgu/archive/2007/11/13/asp-net-mvc-framework-part-1.aspx http://www.asp.net/MVC/ | [
"c#",
"asp.net",
"asp.net-mvc",
"routes"
] | 13 | 6 | 22,385 | 5 | 0 | 2008-08-15T03:25:31.657000 | 2008-08-15T04:24:44.190000 |
11,930 | 12,030 | How can I determine the IP of my router/gateway in Java? | How can I determine the IP of my router/gateway in Java? I can get my IP easily enough. I can get my internet IP using a service on a website. But how can I determine my gateway's IP? This is somewhat easy in.NET if you know your way around. But how do you do it in Java? | Java doesn't make this as pleasant as other languages, unfortunately. Here's what I did: import java.io.*; import java.util.*;
public class ExecTest { public static void main(String[] args) throws IOException { Process result = Runtime.getRuntime().exec("traceroute -m 1 www.amazon.com");
BufferedReader output = new BufferedReader(new InputStreamReader(result.getInputStream())); String thisLine = output.readLine(); StringTokenizer st = new StringTokenizer(thisLine); st.nextToken(); String gateway = st.nextToken(); System.out.printf("The gateway is %s\n", gateway); } } This presumes that the gateway is the second token and not the third. If it is, you need to add an extra st.nextToken(); to advance the tokenizer one more spot. | How can I determine the IP of my router/gateway in Java? How can I determine the IP of my router/gateway in Java? I can get my IP easily enough. I can get my internet IP using a service on a website. But how can I determine my gateway's IP? This is somewhat easy in.NET if you know your way around. But how do you do it in Java? | TITLE:
How can I determine the IP of my router/gateway in Java?
QUESTION:
How can I determine the IP of my router/gateway in Java? I can get my IP easily enough. I can get my internet IP using a service on a website. But how can I determine my gateway's IP? This is somewhat easy in.NET if you know your way around. But how do you do it in Java?
ANSWER:
Java doesn't make this as pleasant as other languages, unfortunately. Here's what I did: import java.io.*; import java.util.*;
public class ExecTest { public static void main(String[] args) throws IOException { Process result = Runtime.getRuntime().exec("traceroute -m 1 www.amazon.com");
BufferedReader output = new BufferedReader(new InputStreamReader(result.getInputStream())); String thisLine = output.readLine(); StringTokenizer st = new StringTokenizer(thisLine); st.nextToken(); String gateway = st.nextToken(); System.out.printf("The gateway is %s\n", gateway); } } This presumes that the gateway is the second token and not the third. If it is, you need to add an extra st.nextToken(); to advance the tokenizer one more spot. | [
"java",
"sockets",
"ip",
"router"
] | 17 | 13 | 32,864 | 16 | 0 | 2008-08-15T03:32:28.897000 | 2008-08-15T06:38:21.813000 |
11,950 | 11,967 | How do you log errors (Exceptions) in your ASP.NET apps? | I'm looking for the best way to log errors in an ASP.NET application. I want to be able to receive emails when errors occurs in my application, with detailed information about the Exception and the current Request. In my company we used to have our own ErrorMailer, catching everything in the Global.asax Application_Error. It was "Ok" but not very flexible nor configurable. We switched recently to NLog. It's much more configurable, we can define different targets for the errors, filter them, buffer them (not tried yet). It's a very good improvement. But I discovered lately that there's a whole Namespace in the.Net framework for this purpose: System.Web.Management and it can be configured in the healthMonitoring section of web.config. Have you ever worked with.Net health monitoring? What is your solution for error logging? | I use elmah. It has some really nice features and here is a CodeProject article on it. I think the StackOverflow team uses elmah also! | How do you log errors (Exceptions) in your ASP.NET apps? I'm looking for the best way to log errors in an ASP.NET application. I want to be able to receive emails when errors occurs in my application, with detailed information about the Exception and the current Request. In my company we used to have our own ErrorMailer, catching everything in the Global.asax Application_Error. It was "Ok" but not very flexible nor configurable. We switched recently to NLog. It's much more configurable, we can define different targets for the errors, filter them, buffer them (not tried yet). It's a very good improvement. But I discovered lately that there's a whole Namespace in the.Net framework for this purpose: System.Web.Management and it can be configured in the healthMonitoring section of web.config. Have you ever worked with.Net health monitoring? What is your solution for error logging? | TITLE:
How do you log errors (Exceptions) in your ASP.NET apps?
QUESTION:
I'm looking for the best way to log errors in an ASP.NET application. I want to be able to receive emails when errors occurs in my application, with detailed information about the Exception and the current Request. In my company we used to have our own ErrorMailer, catching everything in the Global.asax Application_Error. It was "Ok" but not very flexible nor configurable. We switched recently to NLog. It's much more configurable, we can define different targets for the errors, filter them, buffer them (not tried yet). It's a very good improvement. But I discovered lately that there's a whole Namespace in the.Net framework for this purpose: System.Web.Management and it can be configured in the healthMonitoring section of web.config. Have you ever worked with.Net health monitoring? What is your solution for error logging?
ANSWER:
I use elmah. It has some really nice features and here is a CodeProject article on it. I think the StackOverflow team uses elmah also! | [
"asp.net",
"error-handling",
"nlog",
"health-monitoring"
] | 30 | 29 | 41,693 | 8 | 0 | 2008-08-15T04:05:10.843000 | 2008-08-15T04:34:49.817000 |
11,964 | 11,973 | Pay for vmware or use Open Source? | What should I use to virtualize my desktop, vmx, xen, or vmware? Needs to work on a linux or windows host, sorry virtual pc. @Derek Park: Free as in speech, not beer. I want to be able to make a new virtual machine from my own licensed copies of windows, for that vmware is kind of expensive. | Try VirtualBox. It's free, open source, and it runs on Windows, Linux, Macintosh and OpenSolaris. | Pay for vmware or use Open Source? What should I use to virtualize my desktop, vmx, xen, or vmware? Needs to work on a linux or windows host, sorry virtual pc. @Derek Park: Free as in speech, not beer. I want to be able to make a new virtual machine from my own licensed copies of windows, for that vmware is kind of expensive. | TITLE:
Pay for vmware or use Open Source?
QUESTION:
What should I use to virtualize my desktop, vmx, xen, or vmware? Needs to work on a linux or windows host, sorry virtual pc. @Derek Park: Free as in speech, not beer. I want to be able to make a new virtual machine from my own licensed copies of windows, for that vmware is kind of expensive.
ANSWER:
Try VirtualBox. It's free, open source, and it runs on Windows, Linux, Macintosh and OpenSolaris. | [
"virtualization"
] | 3 | 11 | 3,613 | 7 | 0 | 2008-08-15T04:32:29.883000 | 2008-08-15T04:43:48.440000 |
11,974 | 12,057 | What is the best way to upload a file via an HTTP POST with a web form? | Basically, something better than this: First of all, the browse button looks different on every browser. Unlike the submit button on a form, you have to come up with some hack-y way to style it. Secondly, there's no progress indicator showing you how much of the file has uploaded. You usually have to implement some kind of client-side way to disable multiple submits (e.g. change the submit button to a disabled button showing "Form submitting... please wait.") or flash a giant warning. Are there any good solutions to this that don't use Flash or Java? Yaakov: That product looks to be exactly what I'm looking for, but the cost is $1000 and its specifically for ASP.NET. Are there any open source projects that cover the same or similar functionality? | File upload boxes is where we're currently at if you don't want to involve other technologies like Flash, Java or ActiveX. With plain HTML you are pretty much limited to the experience you've described (no progress bar, double submits, etc). If you are willing to use some javascript, you can solve some of the problems by giving feedback that the upload is in progress and even showing the upload progress (it is a hack because you shouldn't have to do a full round-trip to the server and back, but at least it works). If you are willing to use Flash (which is available pretty much anywhere and on many platforms), you can overcome pretty much all of these problems. A quick googling turned up two such components, both of them free and open source. I never used any of them, but they look good. BTW, Flash isn't without its problems either, for example when using the multi-file uploader for slide share, the browser kept constantly crashing on me:-( Probably the best solution currently is to detect dynamically if the user has Flash, and if it's the case, give her the flash version of the uploader, while still making it possible to choose the basic HTML one. HTH | What is the best way to upload a file via an HTTP POST with a web form? Basically, something better than this: First of all, the browse button looks different on every browser. Unlike the submit button on a form, you have to come up with some hack-y way to style it. Secondly, there's no progress indicator showing you how much of the file has uploaded. You usually have to implement some kind of client-side way to disable multiple submits (e.g. change the submit button to a disabled button showing "Form submitting... please wait.") or flash a giant warning. Are there any good solutions to this that don't use Flash or Java? Yaakov: That product looks to be exactly what I'm looking for, but the cost is $1000 and its specifically for ASP.NET. Are there any open source projects that cover the same or similar functionality? | TITLE:
What is the best way to upload a file via an HTTP POST with a web form?
QUESTION:
Basically, something better than this: First of all, the browse button looks different on every browser. Unlike the submit button on a form, you have to come up with some hack-y way to style it. Secondly, there's no progress indicator showing you how much of the file has uploaded. You usually have to implement some kind of client-side way to disable multiple submits (e.g. change the submit button to a disabled button showing "Form submitting... please wait.") or flash a giant warning. Are there any good solutions to this that don't use Flash or Java? Yaakov: That product looks to be exactly what I'm looking for, but the cost is $1000 and its specifically for ASP.NET. Are there any open source projects that cover the same or similar functionality?
ANSWER:
File upload boxes is where we're currently at if you don't want to involve other technologies like Flash, Java or ActiveX. With plain HTML you are pretty much limited to the experience you've described (no progress bar, double submits, etc). If you are willing to use some javascript, you can solve some of the problems by giving feedback that the upload is in progress and even showing the upload progress (it is a hack because you shouldn't have to do a full round-trip to the server and back, but at least it works). If you are willing to use Flash (which is available pretty much anywhere and on many platforms), you can overcome pretty much all of these problems. A quick googling turned up two such components, both of them free and open source. I never used any of them, but they look good. BTW, Flash isn't without its problems either, for example when using the multi-file uploader for slide share, the browser kept constantly crashing on me:-( Probably the best solution currently is to detect dynamically if the user has Flash, and if it's the case, give her the flash version of the uploader, while still making it possible to choose the basic HTML one. HTH | [
"html",
"http",
"forms",
"post",
"upload"
] | 5 | 9 | 3,959 | 4 | 0 | 2008-08-15T04:54:05.613000 | 2008-08-15T07:54:33.063000 |
11,975 | 11,983 | Handling timezones in storage? | Store everything in GMT? Store everything the way it was entered with an embedded offset? Do the math everytime you render? Display relative Times "1 minutes ago"? | You have to store in UTC - if you don't, your historic reporting and behaviour during things like Daylight Savings goes... funny. GMT is a local time, subject to Daylight Savings relative to UTC (which is not). Presentation to users in different time-zones can be a real bastard if you're storing local time. It's easy to adjust to local if your raw data is in UTC - just add your user's offset and you're done! Joel talked about this in one of the podcasts (in a round-about way) - he said to store your data in the highest resolution possible (search for 'fidelity'), because you can always munge it when it goes out again. That's why I say store it as UTC, as local time you need to adjust for anyone who's not in that timezone, and that's a lot of hard work. And you need to store whether, for example, daylight savings was in effect when you stored the time. Yuk. Often in databases in the past I've stored two - UTC for sorting, local time for display. That way neither the user nor the computer get confused. Now, as to display: Sure, you can do the "3 minutes ago" thing, but only if you store UTC - otherwise, data entered in different timezones is going to do things like display as "-4 hours ago", which will freak people out. If you're going to display an actual time, people love to have it in their local time - and if data's being entered in multiple timezones you can only do that with ease if you're storing UTC. | Handling timezones in storage? Store everything in GMT? Store everything the way it was entered with an embedded offset? Do the math everytime you render? Display relative Times "1 minutes ago"? | TITLE:
Handling timezones in storage?
QUESTION:
Store everything in GMT? Store everything the way it was entered with an embedded offset? Do the math everytime you render? Display relative Times "1 minutes ago"?
ANSWER:
You have to store in UTC - if you don't, your historic reporting and behaviour during things like Daylight Savings goes... funny. GMT is a local time, subject to Daylight Savings relative to UTC (which is not). Presentation to users in different time-zones can be a real bastard if you're storing local time. It's easy to adjust to local if your raw data is in UTC - just add your user's offset and you're done! Joel talked about this in one of the podcasts (in a round-about way) - he said to store your data in the highest resolution possible (search for 'fidelity'), because you can always munge it when it goes out again. That's why I say store it as UTC, as local time you need to adjust for anyone who's not in that timezone, and that's a lot of hard work. And you need to store whether, for example, daylight savings was in effect when you stored the time. Yuk. Often in databases in the past I've stored two - UTC for sorting, local time for display. That way neither the user nor the computer get confused. Now, as to display: Sure, you can do the "3 minutes ago" thing, but only if you store UTC - otherwise, data entered in different timezones is going to do things like display as "-4 hours ago", which will freak people out. If you're going to display an actual time, people love to have it in their local time - and if data's being entered in multiple timezones you can only do that with ease if you're storing UTC. | [
"localization",
"internationalization",
"timezone",
"globalization"
] | 20 | 39 | 5,720 | 13 | 0 | 2008-08-15T04:54:59.510000 | 2008-08-15T05:19:37.603000 |
11,986 | 32,898 | Why does sqlite3-ruby-1.2.2 not work on OS X? | I am running OS X 10.5, Ruby 1.8.6, Rails 2.1, sqlite3-ruby 1.2.2 and I get the following error when trying to rake db:migrate on an app that works find connected to MySQL. rake aborted! no such file to load -- sqlite3/database | Jamis has just released 1.2.4, and the comment history on that bug suggests that the fix is in 1.2.3 and later versions. As a quick test, I did the following on an OS X 10.5 box with Ruby 1.8.6: sudo gem install sqlite3-ruby (verified version number of 1.2.4) rails test (used default database.yml with sqlite3) cd test./script/generate model Person name:string rake db:migrate Ran fine. The error would have happened when sqlite3 was require d before the migration finished, so it looks like they've fixed the issue. | Why does sqlite3-ruby-1.2.2 not work on OS X? I am running OS X 10.5, Ruby 1.8.6, Rails 2.1, sqlite3-ruby 1.2.2 and I get the following error when trying to rake db:migrate on an app that works find connected to MySQL. rake aborted! no such file to load -- sqlite3/database | TITLE:
Why does sqlite3-ruby-1.2.2 not work on OS X?
QUESTION:
I am running OS X 10.5, Ruby 1.8.6, Rails 2.1, sqlite3-ruby 1.2.2 and I get the following error when trying to rake db:migrate on an app that works find connected to MySQL. rake aborted! no such file to load -- sqlite3/database
ANSWER:
Jamis has just released 1.2.4, and the comment history on that bug suggests that the fix is in 1.2.3 and later versions. As a quick test, I did the following on an OS X 10.5 box with Ruby 1.8.6: sudo gem install sqlite3-ruby (verified version number of 1.2.4) rails test (used default database.yml with sqlite3) cd test./script/generate model Person name:string rake db:migrate Ran fine. The error would have happened when sqlite3 was require d before the migration finished, so it looks like they've fixed the issue. | [
"ruby-on-rails",
"ruby",
"sqlite"
] | 3 | 2 | 548 | 2 | 0 | 2008-08-15T05:23:02.153000 | 2008-08-28T17:48:16.883000 |
12,008 | 12,047 | How do you do system integration? | I curious to how different people solve integration of systems. I have a feeling that the last years more and more work has gone into integrating systems and that this kind of work need will increase as well. I wondering if you solve it developing your own small services that are then connected or if you use some sort of product (WebSphere, BizTalk, Mule etc). I'd also think it'd be interesting to know how these kind of solutions are managed and maintained (how do you solve security, instrumentation etc, etc), what kind of problems have you experienced with your solution and so on. | wow - Ok - will get a post on this but will be big. Intergration needs to be backed up with a big understanding by the business on the benefits - Get an opertating model sorted out - as the business may acutally need to standardise instead of intergrate, as this can be costly - its why most SOA fail! Enterprise Architecture: Driving Business Benefits from IT Author(s): Jeanne W. Ross If intergration is needed you then need to settle on type of integration. What are the speed and performance metrics? We have a.NET SOA with a Composite Application that uses BizTalk 2006 and webservices with Line of Business Applications. Performance of the application at the composite end (consuming) - is limited to the speed of the webservices (and their implementation) in the line of business application! We need sub <3 second return on results - list of cases. Could not be acheived in the webservices so we need to get go to the database directly for initial search. Then over the webservices for case creation. Cost implications and maintance becomes an issue here. The point here is to look at the performance criteria in the specs and business requirements this will help in look at the type of integration that you need to do - WebServices (HTTP), File Drop/ EDI etc Functionally for intergration you need to then look at the points of failure in the proposed architecture - as this will lead to a chain of responisblity in SLA/OLA. You may need to wrapper the intergration/faliure points into things that you control. On similar point about integration with Line of Business is with how much do you need to know about the other product before you can integrate? Yeah Webservices are supposed to be design by contract but the implementation is often leaky and you need to understand alot about what is happening - and if this is a product that you dont control the abstraction even with webservices leaks into your intergation technology aka BizTalk. Couple these two points together and you the best advise is to get a intergration hub type like BizTalk - wrapper the line of business applications in webservices you create - so the BizTalk side can be free from leaky abstractions then you also can reduce the points of failure as the you have decoupled the line of business application from the intergration hub and the point of failure to a single source rather than inside an orchestration. Instrumentation and diagnosics in SOA and Intergation Porjects are hard to acheive! - Dont let any shiney sales person try and tell you differently! Yeah MOM with MOM Ent can do this UniCenter can do blah. The main problem is understand what the error aka burps in the intergation mean and how to recover from them... You end up with messages stuck and you need to understand what that means to that busienss process. You can get an alert to say - processers are 100% Ram 100% orchestrations have failed - but no real meaning. You have to engineer this stuff in to the solution from the outset - and hopefully into you points of failure. Types of intergration patterns and how to do them do need to be considered too. The above is a real world view of a.NET SOA with BizTalk in a LIVE implementation. But it is also due to the architectural limitations of this - BizTalk mainly is a HUB and SPOKE pattern. Check out Enterprise Application Patterns by Martin Fowler There are many ways to skin the task! Other considerations... Platform/Developer Languages etc. One of the big factors for us was the skills needed to start this stuff. We had OO devs with Java and C# understanding, but mainly C#. So we went for the MS stack. But when you choose the intergration type and the product to manage this they will need more skills in understanding that technology. But hey this is normall for us Devs right? Wrong many developers regardless of there expereince can come unstuck with the likes of BizTalk! Big shift in paradigm - which in part is due to messaging shift rather than code. Best bit for last! Numbers of transactions that are likely to be faced in the integration is probable the single biggest factor in all of this. As this will guide what pattern, points of failure and tolarance for such things. You need to select best on anticpated volumes the right one. Something that can scale up and scale out! We selected BizTalk since it can scale up and scale out correctly and with better understanding than some others. If you dont have volumes then look at not getting something to manage them and go for a webservice to webservice type style with no management - performance and failure understanding will need to be coded into them. If your on windows platform with.net 3 take look at WWF/WCF as this can help in webservice to webservice - lots more in the acutal platform now for all these concerns without the overhead of BizTalk and others. Hope this helps. | How do you do system integration? I curious to how different people solve integration of systems. I have a feeling that the last years more and more work has gone into integrating systems and that this kind of work need will increase as well. I wondering if you solve it developing your own small services that are then connected or if you use some sort of product (WebSphere, BizTalk, Mule etc). I'd also think it'd be interesting to know how these kind of solutions are managed and maintained (how do you solve security, instrumentation etc, etc), what kind of problems have you experienced with your solution and so on. | TITLE:
How do you do system integration?
QUESTION:
I curious to how different people solve integration of systems. I have a feeling that the last years more and more work has gone into integrating systems and that this kind of work need will increase as well. I wondering if you solve it developing your own small services that are then connected or if you use some sort of product (WebSphere, BizTalk, Mule etc). I'd also think it'd be interesting to know how these kind of solutions are managed and maintained (how do you solve security, instrumentation etc, etc), what kind of problems have you experienced with your solution and so on.
ANSWER:
wow - Ok - will get a post on this but will be big. Intergration needs to be backed up with a big understanding by the business on the benefits - Get an opertating model sorted out - as the business may acutally need to standardise instead of intergrate, as this can be costly - its why most SOA fail! Enterprise Architecture: Driving Business Benefits from IT Author(s): Jeanne W. Ross If intergration is needed you then need to settle on type of integration. What are the speed and performance metrics? We have a.NET SOA with a Composite Application that uses BizTalk 2006 and webservices with Line of Business Applications. Performance of the application at the composite end (consuming) - is limited to the speed of the webservices (and their implementation) in the line of business application! We need sub <3 second return on results - list of cases. Could not be acheived in the webservices so we need to get go to the database directly for initial search. Then over the webservices for case creation. Cost implications and maintance becomes an issue here. The point here is to look at the performance criteria in the specs and business requirements this will help in look at the type of integration that you need to do - WebServices (HTTP), File Drop/ EDI etc Functionally for intergration you need to then look at the points of failure in the proposed architecture - as this will lead to a chain of responisblity in SLA/OLA. You may need to wrapper the intergration/faliure points into things that you control. On similar point about integration with Line of Business is with how much do you need to know about the other product before you can integrate? Yeah Webservices are supposed to be design by contract but the implementation is often leaky and you need to understand alot about what is happening - and if this is a product that you dont control the abstraction even with webservices leaks into your intergation technology aka BizTalk. Couple these two points together and you the best advise is to get a intergration hub type like BizTalk - wrapper the line of business applications in webservices you create - so the BizTalk side can be free from leaky abstractions then you also can reduce the points of failure as the you have decoupled the line of business application from the intergration hub and the point of failure to a single source rather than inside an orchestration. Instrumentation and diagnosics in SOA and Intergation Porjects are hard to acheive! - Dont let any shiney sales person try and tell you differently! Yeah MOM with MOM Ent can do this UniCenter can do blah. The main problem is understand what the error aka burps in the intergation mean and how to recover from them... You end up with messages stuck and you need to understand what that means to that busienss process. You can get an alert to say - processers are 100% Ram 100% orchestrations have failed - but no real meaning. You have to engineer this stuff in to the solution from the outset - and hopefully into you points of failure. Types of intergration patterns and how to do them do need to be considered too. The above is a real world view of a.NET SOA with BizTalk in a LIVE implementation. But it is also due to the architectural limitations of this - BizTalk mainly is a HUB and SPOKE pattern. Check out Enterprise Application Patterns by Martin Fowler There are many ways to skin the task! Other considerations... Platform/Developer Languages etc. One of the big factors for us was the skills needed to start this stuff. We had OO devs with Java and C# understanding, but mainly C#. So we went for the MS stack. But when you choose the intergration type and the product to manage this they will need more skills in understanding that technology. But hey this is normall for us Devs right? Wrong many developers regardless of there expereince can come unstuck with the likes of BizTalk! Big shift in paradigm - which in part is due to messaging shift rather than code. Best bit for last! Numbers of transactions that are likely to be faced in the integration is probable the single biggest factor in all of this. As this will guide what pattern, points of failure and tolarance for such things. You need to select best on anticpated volumes the right one. Something that can scale up and scale out! We selected BizTalk since it can scale up and scale out correctly and with better understanding than some others. If you dont have volumes then look at not getting something to manage them and go for a webservice to webservice type style with no management - performance and failure understanding will need to be coded into them. If your on windows platform with.net 3 take look at WWF/WCF as this can help in webservice to webservice - lots more in the acutal platform now for all these concerns without the overhead of BizTalk and others. Hope this helps. | [
"architecture",
"system-integration"
] | 5 | 10 | 3,149 | 5 | 0 | 2008-08-15T06:06:13.720000 | 2008-08-15T07:10:14.217000 |
12,009 | 12,032 | Piping password to smbpasswd | How can I pipe the new password to smbpasswd so I can automate my installation process. | Thanks to Mark I found the answer: (echo newpassword; echo confirmNewPassword) | smbpasswd -s BTW: (echo oldpasswd; echo newpasswd) | smbpasswd -s does not work. | Piping password to smbpasswd How can I pipe the new password to smbpasswd so I can automate my installation process. | TITLE:
Piping password to smbpasswd
QUESTION:
How can I pipe the new password to smbpasswd so I can automate my installation process.
ANSWER:
Thanks to Mark I found the answer: (echo newpassword; echo confirmNewPassword) | smbpasswd -s BTW: (echo oldpasswd; echo newpasswd) | smbpasswd -s does not work. | [
"automation",
"installation",
"debian",
"samba"
] | 36 | 51 | 35,297 | 7 | 0 | 2008-08-15T06:08:55.243000 | 2008-08-15T06:38:59.287000 |
12,045 | 12,054 | Unit testing a timer based application? | I am currently writing a simple, timer-based mini app in C# that performs an action n times every k seconds. I am trying to adopt a test-driven development style, so my goal is to unit-test all parts of the app. So, my question is: Is there a good way to unit test a timer-based class? The problem, as I see it, is that there is a big risk that the tests will take uncomfortably long to execute since they must wait so and so long for the desired actions to happen. Especially if one wants realistic data ( seconds ), instead of using the minimal time resolution allowed by the framework ( 1 ms?). I am using a mock object for the action, to register the number of times the action was called, and so that the action takes practically no time. | What I have done is to mock the timer, and also the current system time, so that my events could be triggered immediately, but as far as the code under test was concerned time elapsed was seconds. | Unit testing a timer based application? I am currently writing a simple, timer-based mini app in C# that performs an action n times every k seconds. I am trying to adopt a test-driven development style, so my goal is to unit-test all parts of the app. So, my question is: Is there a good way to unit test a timer-based class? The problem, as I see it, is that there is a big risk that the tests will take uncomfortably long to execute since they must wait so and so long for the desired actions to happen. Especially if one wants realistic data ( seconds ), instead of using the minimal time resolution allowed by the framework ( 1 ms?). I am using a mock object for the action, to register the number of times the action was called, and so that the action takes practically no time. | TITLE:
Unit testing a timer based application?
QUESTION:
I am currently writing a simple, timer-based mini app in C# that performs an action n times every k seconds. I am trying to adopt a test-driven development style, so my goal is to unit-test all parts of the app. So, my question is: Is there a good way to unit test a timer-based class? The problem, as I see it, is that there is a big risk that the tests will take uncomfortably long to execute since they must wait so and so long for the desired actions to happen. Especially if one wants realistic data ( seconds ), instead of using the minimal time resolution allowed by the framework ( 1 ms?). I am using a mock object for the action, to register the number of times the action was called, and so that the action takes practically no time.
ANSWER:
What I have done is to mock the timer, and also the current system time, so that my events could be triggered immediately, but as far as the code under test was concerned time elapsed was seconds. | [
"c#",
".net",
"unit-testing",
"timer"
] | 21 | 12 | 8,026 | 4 | 0 | 2008-08-15T07:02:45.993000 | 2008-08-15T07:43:18.110000 |
12,051 | 12,052 | Calling the base constructor in C# | If I inherit from a base class and want to pass something from the constructor of the inherited class to the constructor of the base class, how do I do that? For example, if I inherit from the Exception class I want to do something like this: class MyExceptionClass: Exception { public MyExceptionClass(string message, string extraInfo) { //This is where it's all falling apart base(message); } } Basically what I want is to be able to pass the string message to the base Exception class. | Modify your constructor to the following so that it calls the base class constructor properly: public class MyExceptionClass: Exception { public MyExceptionClass(string message, string extrainfo): base(message) { //other stuff here } } Note that a constructor is not something that you can call anytime within a method. That's the reason you're getting errors in your call in the constructor body. | Calling the base constructor in C# If I inherit from a base class and want to pass something from the constructor of the inherited class to the constructor of the base class, how do I do that? For example, if I inherit from the Exception class I want to do something like this: class MyExceptionClass: Exception { public MyExceptionClass(string message, string extraInfo) { //This is where it's all falling apart base(message); } } Basically what I want is to be able to pass the string message to the base Exception class. | TITLE:
Calling the base constructor in C#
QUESTION:
If I inherit from a base class and want to pass something from the constructor of the inherited class to the constructor of the base class, how do I do that? For example, if I inherit from the Exception class I want to do something like this: class MyExceptionClass: Exception { public MyExceptionClass(string message, string extraInfo) { //This is where it's all falling apart base(message); } } Basically what I want is to be able to pass the string message to the base Exception class.
ANSWER:
Modify your constructor to the following so that it calls the base class constructor properly: public class MyExceptionClass: Exception { public MyExceptionClass(string message, string extrainfo): base(message) { //other stuff here } } Note that a constructor is not something that you can call anytime within a method. That's the reason you're getting errors in your call in the constructor body. | [
"c#",
".net",
"inheritance",
"constructor"
] | 1,856 | 2,220 | 1,409,678 | 10 | 0 | 2008-08-15T07:39:23.097000 | 2008-08-15T07:40:22.157000 |
12,075 | 12,080 | Should I be worried about obfuscating my .NET code? | I'm sure many readers on SO have used Lutz Roeder 's.NET reflector to decompile their.NET code. I was amazed just how accurately our source code could be recontructed from our compiled assemblies. I'd be interested in hearing how many of you use obfuscation, and for what sort of products? I'm sure that this is a much more important issue for, say, a.NET application that you offer for download over the internet as opposed to something that is built bespoke for a particular client. | I wouldn't worry about it too much. I'd rather focus on putting out an awesome product, getting a good user base, and treating your customers right than worry about the minimal percentage of users concerned with stealing your code or looking at the source. | Should I be worried about obfuscating my .NET code? I'm sure many readers on SO have used Lutz Roeder 's.NET reflector to decompile their.NET code. I was amazed just how accurately our source code could be recontructed from our compiled assemblies. I'd be interested in hearing how many of you use obfuscation, and for what sort of products? I'm sure that this is a much more important issue for, say, a.NET application that you offer for download over the internet as opposed to something that is built bespoke for a particular client. | TITLE:
Should I be worried about obfuscating my .NET code?
QUESTION:
I'm sure many readers on SO have used Lutz Roeder 's.NET reflector to decompile their.NET code. I was amazed just how accurately our source code could be recontructed from our compiled assemblies. I'd be interested in hearing how many of you use obfuscation, and for what sort of products? I'm sure that this is a much more important issue for, say, a.NET application that you offer for download over the internet as opposed to something that is built bespoke for a particular client.
ANSWER:
I wouldn't worry about it too much. I'd rather focus on putting out an awesome product, getting a good user base, and treating your customers right than worry about the minimal percentage of users concerned with stealing your code or looking at the source. | [
".net",
"obfuscation"
] | 26 | 21 | 6,482 | 10 | 0 | 2008-08-15T08:36:19.783000 | 2008-08-15T08:39:57.140000 |
12,088 | 12,133 | Do you obfuscate your commercial Java code? | I wonder if anyone uses commercial/free java obfuscators on his own commercial product. I know only about one project that actually had an obfuscating step in the ant build step for releases. Do you obfuscate? And if so, why do you obfuscate? Is it really a way to protect the code or is it just a better feeling for the developers/managers? edit: Ok, I to be exact about my point: Do you obfuscate to protect your IP (your algorithms, the work you've put into your product)? I won't obfuscate for security reasons, that doesn't feel right. So I'm only talking about protecting your applications code against competitors. @staffan has a good point: The reason to stay away from chaining code flow is that some of those changes makes it impossible for the JVM to efficiently optimize the code. In effect it will actually degrade the performance of your application. | If you do obfuscate, stay away from obfuscators that modify the code by changing code flow and/or adding exception blocks and such to make it hard to disassemble it. To make the code unreadable it is usually enough to just change all names of methods, fields and classes. The reason to stay away from changing code flow is that some of those changes makes it impossible for the JVM to efficiently optimize the code. In effect it will actually degrade the performance of your application. | Do you obfuscate your commercial Java code? I wonder if anyone uses commercial/free java obfuscators on his own commercial product. I know only about one project that actually had an obfuscating step in the ant build step for releases. Do you obfuscate? And if so, why do you obfuscate? Is it really a way to protect the code or is it just a better feeling for the developers/managers? edit: Ok, I to be exact about my point: Do you obfuscate to protect your IP (your algorithms, the work you've put into your product)? I won't obfuscate for security reasons, that doesn't feel right. So I'm only talking about protecting your applications code against competitors. @staffan has a good point: The reason to stay away from chaining code flow is that some of those changes makes it impossible for the JVM to efficiently optimize the code. In effect it will actually degrade the performance of your application. | TITLE:
Do you obfuscate your commercial Java code?
QUESTION:
I wonder if anyone uses commercial/free java obfuscators on his own commercial product. I know only about one project that actually had an obfuscating step in the ant build step for releases. Do you obfuscate? And if so, why do you obfuscate? Is it really a way to protect the code or is it just a better feeling for the developers/managers? edit: Ok, I to be exact about my point: Do you obfuscate to protect your IP (your algorithms, the work you've put into your product)? I won't obfuscate for security reasons, that doesn't feel right. So I'm only talking about protecting your applications code against competitors. @staffan has a good point: The reason to stay away from chaining code flow is that some of those changes makes it impossible for the JVM to efficiently optimize the code. In effect it will actually degrade the performance of your application.
ANSWER:
If you do obfuscate, stay away from obfuscators that modify the code by changing code flow and/or adding exception blocks and such to make it hard to disassemble it. To make the code unreadable it is usually enough to just change all names of methods, fields and classes. The reason to stay away from changing code flow is that some of those changes makes it impossible for the JVM to efficiently optimize the code. In effect it will actually degrade the performance of your application. | [
"java",
"obfuscation"
] | 51 | 64 | 53,130 | 7 | 0 | 2008-08-15T08:55:28.997000 | 2008-08-15T10:57:31.463000 |
12,095 | 12,119 | Windows Forms Threading and Events - ListBox updates promptly but progressbar experiences huge delay | Our team is creating a new recruitment workflow system to replace an old one. I have been tasked with migrating the old data into the new schema. I have decided to do this by creating a small Windows Forms project as the schema are radically different and straight TSQL scripts are not an adequate solution. The main sealed class 'ImportController' that does the work declares the following delegate event: public delegate void ImportProgressEventHandler(object sender, ImportProgressEventArgs e); public static event ImportProgressEventHandler importProgressEvent; The main window starts a static method in that class using a new thread: Thread dataProcessingThread = new Thread(new ParameterizedThreadStart(ImportController.ImportData)); dataProcessingThread.Name = "Data Importer: Data Processing Thread"; dataProcessingThread.Start(settings); the ImportProgressEvent args carries a string message, a max int value for the progress bar and an current progress int value. The Windows form subcribes to the event: ImportController.importProgressEvent += new ImportController.ImportProgressEventHandler(ImportController_importProgressEvent); And responds to the event in this manner using it's own delegate: private delegate void TaskCompletedUIDelegate(string completedTask, int currentProgress, int progressMax);
private void ImportController_importProgressEvent(object sender, ImportProgressEventArgs e) { this.Invoke(new TaskCompletedUIDelegate(this.DisplayCompletedTask), e.CompletedTask, e.CurrentProgress, e.ProgressMax); } Finally the progress bar and listbox are updated: private void DisplayCompletedTask(string completedTask, int currentProgress, int progressMax) { string[] items = completedTask.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
foreach (string item in items) { this.lstTasks.Items.Add(item); }
if (currentProgress >= 0 && progressMax > 0 && currentProgress <= progressMax) { this.ImportProgressBar.Maximum = progressMax; this.ImportProgressBar.Value = currentProgress; } } The thing is the ListBox seems to update very quickly, but the progress bar never moves until the batch is almost complete anyway??? what gives? | @John Thanks for the links. @Will There's no gain from threadpooling as I know it will only ever spawn one thread. The use of a thread is purely to have a responsive UI while SQL Server is being pounded with reads and writes. It's certainly not a short lived thread. Regarding sledge-hammers you're right. But, as it turns out my problem was between screen and chair after all. I seem to have an unusal batch of data that has many many many more foreign key records than the other batches and just happens to get selected early in the process meaning the currentProgress doesn't get ++'d for a good 10 seconds. @All Thanks for all your input, it got me thinking, which got me looking elsewhere in the code, which led to my ahaa moment of humility where I prove yet again the error is usually human:) | Windows Forms Threading and Events - ListBox updates promptly but progressbar experiences huge delay Our team is creating a new recruitment workflow system to replace an old one. I have been tasked with migrating the old data into the new schema. I have decided to do this by creating a small Windows Forms project as the schema are radically different and straight TSQL scripts are not an adequate solution. The main sealed class 'ImportController' that does the work declares the following delegate event: public delegate void ImportProgressEventHandler(object sender, ImportProgressEventArgs e); public static event ImportProgressEventHandler importProgressEvent; The main window starts a static method in that class using a new thread: Thread dataProcessingThread = new Thread(new ParameterizedThreadStart(ImportController.ImportData)); dataProcessingThread.Name = "Data Importer: Data Processing Thread"; dataProcessingThread.Start(settings); the ImportProgressEvent args carries a string message, a max int value for the progress bar and an current progress int value. The Windows form subcribes to the event: ImportController.importProgressEvent += new ImportController.ImportProgressEventHandler(ImportController_importProgressEvent); And responds to the event in this manner using it's own delegate: private delegate void TaskCompletedUIDelegate(string completedTask, int currentProgress, int progressMax);
private void ImportController_importProgressEvent(object sender, ImportProgressEventArgs e) { this.Invoke(new TaskCompletedUIDelegate(this.DisplayCompletedTask), e.CompletedTask, e.CurrentProgress, e.ProgressMax); } Finally the progress bar and listbox are updated: private void DisplayCompletedTask(string completedTask, int currentProgress, int progressMax) { string[] items = completedTask.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
foreach (string item in items) { this.lstTasks.Items.Add(item); }
if (currentProgress >= 0 && progressMax > 0 && currentProgress <= progressMax) { this.ImportProgressBar.Maximum = progressMax; this.ImportProgressBar.Value = currentProgress; } } The thing is the ListBox seems to update very quickly, but the progress bar never moves until the batch is almost complete anyway??? what gives? | TITLE:
Windows Forms Threading and Events - ListBox updates promptly but progressbar experiences huge delay
QUESTION:
Our team is creating a new recruitment workflow system to replace an old one. I have been tasked with migrating the old data into the new schema. I have decided to do this by creating a small Windows Forms project as the schema are radically different and straight TSQL scripts are not an adequate solution. The main sealed class 'ImportController' that does the work declares the following delegate event: public delegate void ImportProgressEventHandler(object sender, ImportProgressEventArgs e); public static event ImportProgressEventHandler importProgressEvent; The main window starts a static method in that class using a new thread: Thread dataProcessingThread = new Thread(new ParameterizedThreadStart(ImportController.ImportData)); dataProcessingThread.Name = "Data Importer: Data Processing Thread"; dataProcessingThread.Start(settings); the ImportProgressEvent args carries a string message, a max int value for the progress bar and an current progress int value. The Windows form subcribes to the event: ImportController.importProgressEvent += new ImportController.ImportProgressEventHandler(ImportController_importProgressEvent); And responds to the event in this manner using it's own delegate: private delegate void TaskCompletedUIDelegate(string completedTask, int currentProgress, int progressMax);
private void ImportController_importProgressEvent(object sender, ImportProgressEventArgs e) { this.Invoke(new TaskCompletedUIDelegate(this.DisplayCompletedTask), e.CompletedTask, e.CurrentProgress, e.ProgressMax); } Finally the progress bar and listbox are updated: private void DisplayCompletedTask(string completedTask, int currentProgress, int progressMax) { string[] items = completedTask.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
foreach (string item in items) { this.lstTasks.Items.Add(item); }
if (currentProgress >= 0 && progressMax > 0 && currentProgress <= progressMax) { this.ImportProgressBar.Maximum = progressMax; this.ImportProgressBar.Value = currentProgress; } } The thing is the ListBox seems to update very quickly, but the progress bar never moves until the batch is almost complete anyway??? what gives?
ANSWER:
@John Thanks for the links. @Will There's no gain from threadpooling as I know it will only ever spawn one thread. The use of a thread is purely to have a responsive UI while SQL Server is being pounded with reads and writes. It's certainly not a short lived thread. Regarding sledge-hammers you're right. But, as it turns out my problem was between screen and chair after all. I seem to have an unusal batch of data that has many many many more foreign key records than the other batches and just happens to get selected early in the process meaning the currentProgress doesn't get ++'d for a good 10 seconds. @All Thanks for all your input, it got me thinking, which got me looking elsewhere in the code, which led to my ahaa moment of humility where I prove yet again the error is usually human:) | [
"windows",
"multithreading",
"events",
"forms",
"delegates"
] | 4 | 0 | 1,615 | 6 | 0 | 2008-08-15T09:19:04.050000 | 2008-08-15T10:07:06.447000 |
12,103 | 12,108 | Why doesn't my Perl map return anything? | When I am running the following statement: @filtered = map {s/ //g} @outdata; it is returning an empty list instead of the filtered list that I expected. What I am trying to do is remove every occurrence of from an array of string (which is an XML file). Obviously, I am not understanding something. Can anyone tell me the correct way to do this might be, and why this isn't working for me as is? | Try this: @filtered = map {s/ //g; $_} @outdata; The problem is the s operator in perl modifies $_ but actually returns the number of changes it made. So, the extra $_ at the end causes perl to return the modified string for each element of @outdata. | Why doesn't my Perl map return anything? When I am running the following statement: @filtered = map {s/ //g} @outdata; it is returning an empty list instead of the filtered list that I expected. What I am trying to do is remove every occurrence of from an array of string (which is an XML file). Obviously, I am not understanding something. Can anyone tell me the correct way to do this might be, and why this isn't working for me as is? | TITLE:
Why doesn't my Perl map return anything?
QUESTION:
When I am running the following statement: @filtered = map {s/ //g} @outdata; it is returning an empty list instead of the filtered list that I expected. What I am trying to do is remove every occurrence of from an array of string (which is an XML file). Obviously, I am not understanding something. Can anyone tell me the correct way to do this might be, and why this isn't working for me as is?
ANSWER:
Try this: @filtered = map {s/ //g; $_} @outdata; The problem is the s operator in perl modifies $_ but actually returns the number of changes it made. So, the extra $_ at the end causes perl to return the modified string for each element of @outdata. | [
"perl",
"dictionary"
] | 5 | 10 | 1,499 | 7 | 0 | 2008-08-15T09:38:31.250000 | 2008-08-15T09:49:17.153000 |
12,107 | 12,114 | Configuring VisualSVN Server to use _svn instead of .svn | We were having a problem with our build server not checking out modifications from source control despite recognizing that there had been changes. It was traced to the control folder (not sure what it's real name is), the existing working builds were using _svn. Clearing the working folder forced a new complete checkout and I noticed that now the control folder is.svn. It looks like originally our integration routines were checking out code using _svn but now it is using.svn. The svn.exe being used during integration is from VisualSVN Server can I set this up to use _svn again? How the original working copies were using _svn I don't know! - we only ever ever used VisualSVN Server and haven't changed this. We had setup TortoiseSVN to use _svn following the recommendation that this works better for Visual Studio and have also installed TortoiseSVN on the build server in case it is ever needed. Could this be the cause? Also is this really necessary? As MSBuild is Microsoft's is it recommended as it is for Visual Studio? | The business about _svn vs..svn was an issue with Visual Studio web projects only (and I'm fairly sure it was fixed in VS2005 anyway), it's not a general "_svn works better with VS" thing. It's also only a working-copy issue, not a repository issue - i.e. it doesn't matter if some users of SVN are using clients set up to do _svn and some are using.svn - the repository won't know or care - (unless somehow you end-up with a load of these _svn/.svn files actually checked-into the repository which would be confusing in the extreme.) Unless you have absolute concrete evidence that.SVN is causing you problems, then I would stick with that wherever you can. | Configuring VisualSVN Server to use _svn instead of .svn We were having a problem with our build server not checking out modifications from source control despite recognizing that there had been changes. It was traced to the control folder (not sure what it's real name is), the existing working builds were using _svn. Clearing the working folder forced a new complete checkout and I noticed that now the control folder is.svn. It looks like originally our integration routines were checking out code using _svn but now it is using.svn. The svn.exe being used during integration is from VisualSVN Server can I set this up to use _svn again? How the original working copies were using _svn I don't know! - we only ever ever used VisualSVN Server and haven't changed this. We had setup TortoiseSVN to use _svn following the recommendation that this works better for Visual Studio and have also installed TortoiseSVN on the build server in case it is ever needed. Could this be the cause? Also is this really necessary? As MSBuild is Microsoft's is it recommended as it is for Visual Studio? | TITLE:
Configuring VisualSVN Server to use _svn instead of .svn
QUESTION:
We were having a problem with our build server not checking out modifications from source control despite recognizing that there had been changes. It was traced to the control folder (not sure what it's real name is), the existing working builds were using _svn. Clearing the working folder forced a new complete checkout and I noticed that now the control folder is.svn. It looks like originally our integration routines were checking out code using _svn but now it is using.svn. The svn.exe being used during integration is from VisualSVN Server can I set this up to use _svn again? How the original working copies were using _svn I don't know! - we only ever ever used VisualSVN Server and haven't changed this. We had setup TortoiseSVN to use _svn following the recommendation that this works better for Visual Studio and have also installed TortoiseSVN on the build server in case it is ever needed. Could this be the cause? Also is this really necessary? As MSBuild is Microsoft's is it recommended as it is for Visual Studio?
ANSWER:
The business about _svn vs..svn was an issue with Visual Studio web projects only (and I'm fairly sure it was fixed in VS2005 anyway), it's not a general "_svn works better with VS" thing. It's also only a working-copy issue, not a repository issue - i.e. it doesn't matter if some users of SVN are using clients set up to do _svn and some are using.svn - the repository won't know or care - (unless somehow you end-up with a load of these _svn/.svn files actually checked-into the repository which would be confusing in the extreme.) Unless you have absolute concrete evidence that.SVN is causing you problems, then I would stick with that wherever you can. | [
"svn",
"version-control",
"visualsvn-server"
] | 3 | 7 | 3,884 | 3 | 0 | 2008-08-15T09:47:38.110000 | 2008-08-15T09:57:38.620000 |
12,135 | 12,160 | FileNotFoundException for mscorlib.XmlSerializers.DLL, which doesn't exist | I'm using an XmlSerializer to deserialize a particular type in mscorelib.dll XmlSerializer ser = new XmlSerializer( typeof( [.Net type in System] ) ); return ([.Net type in System]) ser.Deserialize( new StringReader( xmlValue ) ); This throws a caught FileNotFoundException when the assembly is loaded: "Could not load file or assembly 'mscorlib.XmlSerializers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. The system cannot find the file specified." FusionLog: === Pre-bind state information === LOG: User = ### LOG: DisplayName = mscorlib.XmlSerializers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=x86 (Fully-specified) LOG: Appbase = file:///C:/localdir LOG: Initial PrivatePath = NULL Calling assembly: System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089. === LOG: This bind starts in default load context. LOG: Using application configuration file: C:\localdir\bin\Debug\appname.vshost.exe.Config LOG: Using machine configuration file from c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\config\machine.config. LOG: Post-policy reference: mscorlib.XmlSerializers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=x86 LOG: Attempting download of new URL file:///C:/localdir/bin/Debug/mscorlib.XmlSerializers.DLL. LOG: Attempting download of new URL file:///C:/localdir/bin/Debug/mscorlib.XmlSerializers/mscorlib.XmlSerializers.DLL. LOG: Attempting download of new URL file:///C:/localdir/bin/Debug/mscorlib.XmlSerializers.EXE. LOG: Attempting download of new URL file:///C:/localdir/bin/Debug/mscorlib.XmlSerializers/mscorlib.XmlSerializers.EXE. As far as I know there is no mscorlib.XmlSerializers.DLL, I think the DLL name has bee auto generated by.Net looking for the serializer. You have the option of creating a myApplication.XmlSerializers.DLL when compiling to optimise serializations, so I assume this is part of the framework's checking for it. The problem is that this appears to be causing a delay in loading the application - it seems to hang for a few seconds at this point. Any ideas how to avoid this or speed it up? | I'm guessing now. but: The system might be generating a serializer for the whole of mscorlib, which could be very slow. You could probably avoid this by wrapping the system type in your own type and serialising that instead - then you'd get a serializer for your own assembly. You might be able to build the serializer for mscorlib with sgen.exe, which was the old way of building serializer dlls before it got integrated into VS. | FileNotFoundException for mscorlib.XmlSerializers.DLL, which doesn't exist I'm using an XmlSerializer to deserialize a particular type in mscorelib.dll XmlSerializer ser = new XmlSerializer( typeof( [.Net type in System] ) ); return ([.Net type in System]) ser.Deserialize( new StringReader( xmlValue ) ); This throws a caught FileNotFoundException when the assembly is loaded: "Could not load file or assembly 'mscorlib.XmlSerializers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. The system cannot find the file specified." FusionLog: === Pre-bind state information === LOG: User = ### LOG: DisplayName = mscorlib.XmlSerializers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=x86 (Fully-specified) LOG: Appbase = file:///C:/localdir LOG: Initial PrivatePath = NULL Calling assembly: System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089. === LOG: This bind starts in default load context. LOG: Using application configuration file: C:\localdir\bin\Debug\appname.vshost.exe.Config LOG: Using machine configuration file from c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\config\machine.config. LOG: Post-policy reference: mscorlib.XmlSerializers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=x86 LOG: Attempting download of new URL file:///C:/localdir/bin/Debug/mscorlib.XmlSerializers.DLL. LOG: Attempting download of new URL file:///C:/localdir/bin/Debug/mscorlib.XmlSerializers/mscorlib.XmlSerializers.DLL. LOG: Attempting download of new URL file:///C:/localdir/bin/Debug/mscorlib.XmlSerializers.EXE. LOG: Attempting download of new URL file:///C:/localdir/bin/Debug/mscorlib.XmlSerializers/mscorlib.XmlSerializers.EXE. As far as I know there is no mscorlib.XmlSerializers.DLL, I think the DLL name has bee auto generated by.Net looking for the serializer. You have the option of creating a myApplication.XmlSerializers.DLL when compiling to optimise serializations, so I assume this is part of the framework's checking for it. The problem is that this appears to be causing a delay in loading the application - it seems to hang for a few seconds at this point. Any ideas how to avoid this or speed it up? | TITLE:
FileNotFoundException for mscorlib.XmlSerializers.DLL, which doesn't exist
QUESTION:
I'm using an XmlSerializer to deserialize a particular type in mscorelib.dll XmlSerializer ser = new XmlSerializer( typeof( [.Net type in System] ) ); return ([.Net type in System]) ser.Deserialize( new StringReader( xmlValue ) ); This throws a caught FileNotFoundException when the assembly is loaded: "Could not load file or assembly 'mscorlib.XmlSerializers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. The system cannot find the file specified." FusionLog: === Pre-bind state information === LOG: User = ### LOG: DisplayName = mscorlib.XmlSerializers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=x86 (Fully-specified) LOG: Appbase = file:///C:/localdir LOG: Initial PrivatePath = NULL Calling assembly: System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089. === LOG: This bind starts in default load context. LOG: Using application configuration file: C:\localdir\bin\Debug\appname.vshost.exe.Config LOG: Using machine configuration file from c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\config\machine.config. LOG: Post-policy reference: mscorlib.XmlSerializers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=x86 LOG: Attempting download of new URL file:///C:/localdir/bin/Debug/mscorlib.XmlSerializers.DLL. LOG: Attempting download of new URL file:///C:/localdir/bin/Debug/mscorlib.XmlSerializers/mscorlib.XmlSerializers.DLL. LOG: Attempting download of new URL file:///C:/localdir/bin/Debug/mscorlib.XmlSerializers.EXE. LOG: Attempting download of new URL file:///C:/localdir/bin/Debug/mscorlib.XmlSerializers/mscorlib.XmlSerializers.EXE. As far as I know there is no mscorlib.XmlSerializers.DLL, I think the DLL name has bee auto generated by.Net looking for the serializer. You have the option of creating a myApplication.XmlSerializers.DLL when compiling to optimise serializations, so I assume this is part of the framework's checking for it. The problem is that this appears to be causing a delay in loading the application - it seems to hang for a few seconds at this point. Any ideas how to avoid this or speed it up?
ANSWER:
I'm guessing now. but: The system might be generating a serializer for the whole of mscorlib, which could be very slow. You could probably avoid this by wrapping the system type in your own type and serialising that instead - then you'd get a serializer for your own assembly. You might be able to build the serializer for mscorlib with sgen.exe, which was the old way of building serializer dlls before it got integrated into VS. | [
"c#",
".net",
"serialization",
"assemblies"
] | 12 | 2 | 16,741 | 3 | 0 | 2008-08-15T11:03:30.157000 | 2008-08-15T11:44:33.513000 |
12,140 | 12,185 | Access to global application settings | A database application that I'm currently working on, stores all sorts of settings in the database. Most of those settings are there to customize certain business rules, but there's also some other stuff in there. The app contains objects that specifically do a certain task, e.g., a certain complicated calculation. Those non-UI objects are unit-tested, but also need access to lots of those global settings. The way we've implemented this right now, is by giving the objects properties that are filled by the Application Controller at runtime. When testing, we create the objects in the test and fill in values for testing (not from the database). This works better, in any case much better than having all those objects need some global Settings object --- that of course effectively makes unit testing impossible:) Disadvantage can be that you sometimes need to set a dozen of properties, or that you need to let those properties 'percolate' into sub-objects. So the general question is: how do you provide access to global application settings in your projects, without the need for global variables, while still being able to unit test your code? This must be a problem that's been solved 100's of times... (Note: I'm not too much of an experienced programmer, as you'll have noticed; but I love to learn! And of course, I've already done research into this topic, but I'm really looking for some first-hand experiences) | You could use Martin Fowlers ServiceLocator pattern. In php it could look like this: class ServiceLocator { private static $soleInstance; private $globalSettings;
public static function load($locator) { self::$soleInstance = $locator; }
public static function globalSettings() { if (!isset(self::$soleInstance->globalSettings)) { self::$soleInstance->setGlobalSettings(new GlobalSettings()); } return self::$soleInstance->globalSettings; } } Your production code then initializes the service locator like this: ServiceLocator::load(new ServiceLocator()); In your test-code, you insert your mock-settings like this: ServiceLocator s = new ServiceLocator(); s->setGlobalSettings(new MockGlobalSettings()); ServiceLocator::load(s); It's a repository for singletons that can be exchanged for testing purposes. | Access to global application settings A database application that I'm currently working on, stores all sorts of settings in the database. Most of those settings are there to customize certain business rules, but there's also some other stuff in there. The app contains objects that specifically do a certain task, e.g., a certain complicated calculation. Those non-UI objects are unit-tested, but also need access to lots of those global settings. The way we've implemented this right now, is by giving the objects properties that are filled by the Application Controller at runtime. When testing, we create the objects in the test and fill in values for testing (not from the database). This works better, in any case much better than having all those objects need some global Settings object --- that of course effectively makes unit testing impossible:) Disadvantage can be that you sometimes need to set a dozen of properties, or that you need to let those properties 'percolate' into sub-objects. So the general question is: how do you provide access to global application settings in your projects, without the need for global variables, while still being able to unit test your code? This must be a problem that's been solved 100's of times... (Note: I'm not too much of an experienced programmer, as you'll have noticed; but I love to learn! And of course, I've already done research into this topic, but I'm really looking for some first-hand experiences) | TITLE:
Access to global application settings
QUESTION:
A database application that I'm currently working on, stores all sorts of settings in the database. Most of those settings are there to customize certain business rules, but there's also some other stuff in there. The app contains objects that specifically do a certain task, e.g., a certain complicated calculation. Those non-UI objects are unit-tested, but also need access to lots of those global settings. The way we've implemented this right now, is by giving the objects properties that are filled by the Application Controller at runtime. When testing, we create the objects in the test and fill in values for testing (not from the database). This works better, in any case much better than having all those objects need some global Settings object --- that of course effectively makes unit testing impossible:) Disadvantage can be that you sometimes need to set a dozen of properties, or that you need to let those properties 'percolate' into sub-objects. So the general question is: how do you provide access to global application settings in your projects, without the need for global variables, while still being able to unit test your code? This must be a problem that's been solved 100's of times... (Note: I'm not too much of an experienced programmer, as you'll have noticed; but I love to learn! And of course, I've already done research into this topic, but I'm really looking for some first-hand experiences)
ANSWER:
You could use Martin Fowlers ServiceLocator pattern. In php it could look like this: class ServiceLocator { private static $soleInstance; private $globalSettings;
public static function load($locator) { self::$soleInstance = $locator; }
public static function globalSettings() { if (!isset(self::$soleInstance->globalSettings)) { self::$soleInstance->setGlobalSettings(new GlobalSettings()); } return self::$soleInstance->globalSettings; } } Your production code then initializes the service locator like this: ServiceLocator::load(new ServiceLocator()); In your test-code, you insert your mock-settings like this: ServiceLocator s = new ServiceLocator(); s->setGlobalSettings(new MockGlobalSettings()); ServiceLocator::load(s); It's a repository for singletons that can be exchanged for testing purposes. | [
"language-agnostic",
"oop"
] | 2 | 1 | 681 | 4 | 0 | 2008-08-15T11:12:35.240000 | 2008-08-15T12:25:19.483000 |
12,142 | 12,441 | Update database schema in Entity Framework | I installed VS SP1 and played around with Entity Framework. I created a schema from an existing database and tried some basic operations. Most of it went well, except the database schema update. I changed the database in every basic way: added a new table deleted a table added a new column to an existing table deleted a column from an existing table changed the type of an existing column The first three went well, but the type change and the column deletion did not followed the database changes. Is there any way to make is work from the designer? Or is it not supported at the moment? I didn't find any related material yet, but still searching. | I would guess that possibly those don't happen because they would break the build for existing code, but that's just a guess on my part. Here's my logic: First, EF is supposed to be more than 1:1 table mapping, so it's quite possible that just because you are deleting a column from table A doesn't mean that for that entity, there shouldn't be a property Description. You might just map that property to another table. Second, changing a type could just break builds. that's the only rationale there. | Update database schema in Entity Framework I installed VS SP1 and played around with Entity Framework. I created a schema from an existing database and tried some basic operations. Most of it went well, except the database schema update. I changed the database in every basic way: added a new table deleted a table added a new column to an existing table deleted a column from an existing table changed the type of an existing column The first three went well, but the type change and the column deletion did not followed the database changes. Is there any way to make is work from the designer? Or is it not supported at the moment? I didn't find any related material yet, but still searching. | TITLE:
Update database schema in Entity Framework
QUESTION:
I installed VS SP1 and played around with Entity Framework. I created a schema from an existing database and tried some basic operations. Most of it went well, except the database schema update. I changed the database in every basic way: added a new table deleted a table added a new column to an existing table deleted a column from an existing table changed the type of an existing column The first three went well, but the type change and the column deletion did not followed the database changes. Is there any way to make is work from the designer? Or is it not supported at the moment? I didn't find any related material yet, but still searching.
ANSWER:
I would guess that possibly those don't happen because they would break the build for existing code, but that's just a guess on my part. Here's my logic: First, EF is supposed to be more than 1:1 table mapping, so it's quite possible that just because you are deleting a column from table A doesn't mean that for that entity, there shouldn't be a property Description. You might just map that property to another table. Second, changing a type could just break builds. that's the only rationale there. | [
".net",
"entity-framework",
"schema"
] | 8 | 6 | 16,777 | 7 | 0 | 2008-08-15T11:15:05.080000 | 2008-08-15T16:18:22.633000 |
12,144 | 12,256 | Application configuration files | OK, so I don't want to start a holy-war here, but we're in the process of trying to consolidate the way we handle our application configuration files and we're struggling to make a decision on the best approach to take. At the moment, every application we distribute is using it's own ad-hoc configuration files, whether it's property files (ini style), XML or JSON (internal use only at the moment!). Most of our code is Java at the moment, so we've been looking at Apache Commons Config, but we've found it to be quite verbose. We've also looked at XMLBeans, but it seems like a lot of faffing around. I also feel as though I'm being pushed towards XML as a format, but my clients and colleagues are apprehensive about trying something else. I can understand it from the client's perspective, everybody's heard of XML, but at the end of the day, shouldn't be using the right tool for the job? What formats and libraries are people using in production systems these days, is anyone else trying to avoid the angle bracket tax? Edit: really needs to be a cross platform solution: Linux, Windows, Solaris etc. and the choice of library used to interface with configuration files is just as important as the choice of format. | XML XML XML XML. We're talking config files here. There is no "angle bracket tax" if you're not serializing objects in a performance-intense situation. Config files must be human readable and human understandable, in addition to machine readable. XML is a good compromise between the two. If your shop has people that are afraid of that new-fangled XML technology, I feel bad for you. | Application configuration files OK, so I don't want to start a holy-war here, but we're in the process of trying to consolidate the way we handle our application configuration files and we're struggling to make a decision on the best approach to take. At the moment, every application we distribute is using it's own ad-hoc configuration files, whether it's property files (ini style), XML or JSON (internal use only at the moment!). Most of our code is Java at the moment, so we've been looking at Apache Commons Config, but we've found it to be quite verbose. We've also looked at XMLBeans, but it seems like a lot of faffing around. I also feel as though I'm being pushed towards XML as a format, but my clients and colleagues are apprehensive about trying something else. I can understand it from the client's perspective, everybody's heard of XML, but at the end of the day, shouldn't be using the right tool for the job? What formats and libraries are people using in production systems these days, is anyone else trying to avoid the angle bracket tax? Edit: really needs to be a cross platform solution: Linux, Windows, Solaris etc. and the choice of library used to interface with configuration files is just as important as the choice of format. | TITLE:
Application configuration files
QUESTION:
OK, so I don't want to start a holy-war here, but we're in the process of trying to consolidate the way we handle our application configuration files and we're struggling to make a decision on the best approach to take. At the moment, every application we distribute is using it's own ad-hoc configuration files, whether it's property files (ini style), XML or JSON (internal use only at the moment!). Most of our code is Java at the moment, so we've been looking at Apache Commons Config, but we've found it to be quite verbose. We've also looked at XMLBeans, but it seems like a lot of faffing around. I also feel as though I'm being pushed towards XML as a format, but my clients and colleagues are apprehensive about trying something else. I can understand it from the client's perspective, everybody's heard of XML, but at the end of the day, shouldn't be using the right tool for the job? What formats and libraries are people using in production systems these days, is anyone else trying to avoid the angle bracket tax? Edit: really needs to be a cross platform solution: Linux, Windows, Solaris etc. and the choice of library used to interface with configuration files is just as important as the choice of format.
ANSWER:
XML XML XML XML. We're talking config files here. There is no "angle bracket tax" if you're not serializing objects in a performance-intense situation. Config files must be human readable and human understandable, in addition to machine readable. XML is a good compromise between the two. If your shop has people that are afraid of that new-fangled XML technology, I feel bad for you. | [
"java",
"xml",
"json",
"cross-platform",
"configuration-files"
] | 42 | 11 | 22,702 | 15 | 0 | 2008-08-15T11:19:51.137000 | 2008-08-15T13:45:26.670000 |
12,176 | 12,189 | SVN Revision Version in .NET Assembly w/ out CC.NET | Is there any way to include the SVN repository revision number in the version string of a.NET assembly? Something like Major.Minor.SVNRev I've seen mention of doing this with something like CC.NET (although on ASP.NET actually), but is there any way to do it without any extra software? I've done similar things in C/C++ before using build batch scripts, but in was accomplished by reading the version number, then having the script write out a file called "ver.h" everytime with something to the effect of: #define MAJORVER 4 #define MINORVER 23 #define SOURCEVER 965 We would then use these defines to generate the version string. Is something like this possible for.NET? | Have a look at SubWCRev - http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-subwcrev.html The assembly version numbers are usually in assemblyinfo.cs | SVN Revision Version in .NET Assembly w/ out CC.NET Is there any way to include the SVN repository revision number in the version string of a.NET assembly? Something like Major.Minor.SVNRev I've seen mention of doing this with something like CC.NET (although on ASP.NET actually), but is there any way to do it without any extra software? I've done similar things in C/C++ before using build batch scripts, but in was accomplished by reading the version number, then having the script write out a file called "ver.h" everytime with something to the effect of: #define MAJORVER 4 #define MINORVER 23 #define SOURCEVER 965 We would then use these defines to generate the version string. Is something like this possible for.NET? | TITLE:
SVN Revision Version in .NET Assembly w/ out CC.NET
QUESTION:
Is there any way to include the SVN repository revision number in the version string of a.NET assembly? Something like Major.Minor.SVNRev I've seen mention of doing this with something like CC.NET (although on ASP.NET actually), but is there any way to do it without any extra software? I've done similar things in C/C++ before using build batch scripts, but in was accomplished by reading the version number, then having the script write out a file called "ver.h" everytime with something to the effect of: #define MAJORVER 4 #define MINORVER 23 #define SOURCEVER 965 We would then use these defines to generate the version string. Is something like this possible for.NET?
ANSWER:
Have a look at SubWCRev - http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-subwcrev.html The assembly version numbers are usually in assemblyinfo.cs | [
".net",
"svn",
"versioning"
] | 26 | 6 | 11,436 | 8 | 0 | 2008-08-15T12:15:31.250000 | 2008-08-15T12:29:04.327000 |
12,225 | 16,718 | Problem databinding an ASP.Net AJAX toolkit MaskedEditExtender | I have a database that contains a date and we are using the MaskedEditExtender (MEE) and MaskedEditValidator to make sure the dates are appropriate. However, we want the Admins to be able to go in and change the data (specifically the date) if necessary. How can I have the MEE field pre-populate with the database value when the data is shown on the page? I've tried to use 'bind' in the 'InitialValue' property but it doesn't populate the textbox. Thanks. | We found out this morning why our code was mishandling the extender. Since the db was handling the date as a date/time it was returning the date in this format 99/99/9999 99:99:99 but we had the extender mask looking for this format 99/99/9999 99:99 Mask="99/99/9999 99:99:99" the above code fixed the problem. thanks to everyone for their help. | Problem databinding an ASP.Net AJAX toolkit MaskedEditExtender I have a database that contains a date and we are using the MaskedEditExtender (MEE) and MaskedEditValidator to make sure the dates are appropriate. However, we want the Admins to be able to go in and change the data (specifically the date) if necessary. How can I have the MEE field pre-populate with the database value when the data is shown on the page? I've tried to use 'bind' in the 'InitialValue' property but it doesn't populate the textbox. Thanks. | TITLE:
Problem databinding an ASP.Net AJAX toolkit MaskedEditExtender
QUESTION:
I have a database that contains a date and we are using the MaskedEditExtender (MEE) and MaskedEditValidator to make sure the dates are appropriate. However, we want the Admins to be able to go in and change the data (specifically the date) if necessary. How can I have the MEE field pre-populate with the database value when the data is shown on the page? I've tried to use 'bind' in the 'InitialValue' property but it doesn't populate the textbox. Thanks.
ANSWER:
We found out this morning why our code was mishandling the extender. Since the db was handling the date as a date/time it was returning the date in this format 99/99/9999 99:99:99 but we had the extender mask looking for this format 99/99/9999 99:99 Mask="99/99/9999 99:99:99" the above code fixed the problem. thanks to everyone for their help. | [
"asp.net",
"validation",
"asp.net-ajax"
] | 2 | 1 | 3,028 | 2 | 0 | 2008-08-15T13:16:25.263000 | 2008-08-19T18:44:53.757000 |
12,243 | 12,247 | Namespace/solution structure | I apologize for asking such a generalized question, but it's something that can prove challenging for me. My team is about to embark on a large project that will hopefully drag together all of the random one-off codebases that have evolved through the years. Given that this project will cover standardizing logical entities across the company ("Customer", "Employee"), small tasks, large tasks that control the small tasks, and utility services, I'm struggling to figure out the best way to structure the namespaces and code structure. Though I guess I'm not giving you enough specifics to go on, do you have any resources or advice on how to approach splitting your domains up logically? In case it helps, most of this functionality will be revealed via web services, and we're a Microsoft shop with all the latest gizmos and gadgets. I'm debating one massive solution with subprojects to make references easier, but will that make it too unwieldy? Should I wrap up legacy application functionality, or leave that completely agnostic in the namespace (making an OurCRMProduct.Customer class versus a generic Customer class, for instance)? Should each service/project have its own BAL and DAL, or should that be an entirely separate assembly that everything references? I don't have experience with organizing such far-reaching projects, only one-offs, so I'm looking for any guidance I can get. | There's a million ways to skin a cat. However, the simplest one is always the best. Which way is the simplest for you? Depends on your requirements. But there are some general rules of thumb I follow. First, reduce the overall number of projects as much as possible. When you compile twenty times a day, that extra minute adds up. If your app is designed for extensibility, consider splitting your assemblies along the lines of design vs. implementation. Place your interfaces and base classes in a public assembly. Create an assembly for your company's implementations of these classes. For large applications, keep your UI logic and business logic separate. SIMPLIFY your solution. If it looks too complex, it probably is. Combine, reduce. | Namespace/solution structure I apologize for asking such a generalized question, but it's something that can prove challenging for me. My team is about to embark on a large project that will hopefully drag together all of the random one-off codebases that have evolved through the years. Given that this project will cover standardizing logical entities across the company ("Customer", "Employee"), small tasks, large tasks that control the small tasks, and utility services, I'm struggling to figure out the best way to structure the namespaces and code structure. Though I guess I'm not giving you enough specifics to go on, do you have any resources or advice on how to approach splitting your domains up logically? In case it helps, most of this functionality will be revealed via web services, and we're a Microsoft shop with all the latest gizmos and gadgets. I'm debating one massive solution with subprojects to make references easier, but will that make it too unwieldy? Should I wrap up legacy application functionality, or leave that completely agnostic in the namespace (making an OurCRMProduct.Customer class versus a generic Customer class, for instance)? Should each service/project have its own BAL and DAL, or should that be an entirely separate assembly that everything references? I don't have experience with organizing such far-reaching projects, only one-offs, so I'm looking for any guidance I can get. | TITLE:
Namespace/solution structure
QUESTION:
I apologize for asking such a generalized question, but it's something that can prove challenging for me. My team is about to embark on a large project that will hopefully drag together all of the random one-off codebases that have evolved through the years. Given that this project will cover standardizing logical entities across the company ("Customer", "Employee"), small tasks, large tasks that control the small tasks, and utility services, I'm struggling to figure out the best way to structure the namespaces and code structure. Though I guess I'm not giving you enough specifics to go on, do you have any resources or advice on how to approach splitting your domains up logically? In case it helps, most of this functionality will be revealed via web services, and we're a Microsoft shop with all the latest gizmos and gadgets. I'm debating one massive solution with subprojects to make references easier, but will that make it too unwieldy? Should I wrap up legacy application functionality, or leave that completely agnostic in the namespace (making an OurCRMProduct.Customer class versus a generic Customer class, for instance)? Should each service/project have its own BAL and DAL, or should that be an entirely separate assembly that everything references? I don't have experience with organizing such far-reaching projects, only one-offs, so I'm looking for any guidance I can get.
ANSWER:
There's a million ways to skin a cat. However, the simplest one is always the best. Which way is the simplest for you? Depends on your requirements. But there are some general rules of thumb I follow. First, reduce the overall number of projects as much as possible. When you compile twenty times a day, that extra minute adds up. If your app is designed for extensibility, consider splitting your assemblies along the lines of design vs. implementation. Place your interfaces and base classes in a public assembly. Create an assembly for your company's implementations of these classes. For large applications, keep your UI logic and business logic separate. SIMPLIFY your solution. If it looks too complex, it probably is. Combine, reduce. | [
"architecture",
"module",
"namespaces",
"legacy"
] | 10 | 12 | 2,596 | 6 | 0 | 2008-08-15T13:30:42.690000 | 2008-08-15T13:39:01.987000 |
12,271 | 12,491 | Creating Visual Studio templates under the "Windows" category. | I have created a template for Visual Studio 2008 and it currently shows up under File->New Project->Visual C#. However, it is only really specific to Visual C#/Windows but I can't work out how to get it to show up under the "Windows" category and not the more general "Visual C#". | Check out MSDN " How to: Locate and Organize Project and Item Templates " Create a folder within one of these \Common7\IDE\ItemTemplates\CSharp\ My Documents\Visual Studio 2008\Templates\ProjectTemplates\CSharp\ | Creating Visual Studio templates under the "Windows" category. I have created a template for Visual Studio 2008 and it currently shows up under File->New Project->Visual C#. However, it is only really specific to Visual C#/Windows but I can't work out how to get it to show up under the "Windows" category and not the more general "Visual C#". | TITLE:
Creating Visual Studio templates under the "Windows" category.
QUESTION:
I have created a template for Visual Studio 2008 and it currently shows up under File->New Project->Visual C#. However, it is only really specific to Visual C#/Windows but I can't work out how to get it to show up under the "Windows" category and not the more general "Visual C#".
ANSWER:
Check out MSDN " How to: Locate and Organize Project and Item Templates " Create a folder within one of these \Common7\IDE\ItemTemplates\CSharp\ My Documents\Visual Studio 2008\Templates\ProjectTemplates\CSharp\ | [
"visual-studio",
"templates"
] | 3 | 5 | 307 | 2 | 0 | 2008-08-15T14:04:01.017000 | 2008-08-15T17:17:11.797000 |
12,290 | 15,488 | Considering N2 CMS but worried about performance. Is this justified? | Hy, does anyone worked with N2 Content Management System( http://www.codeplex.com/n2 ). If yes, how does it perform, performance wise(under heavy load)? It seems pretty simple and easy to use. Adrian | Maybe try this question at http://www.codeplex.com/n2/Thread/List.aspx They might be able to tell you about performance limitations or bottlenecks. | Considering N2 CMS but worried about performance. Is this justified? Hy, does anyone worked with N2 Content Management System( http://www.codeplex.com/n2 ). If yes, how does it perform, performance wise(under heavy load)? It seems pretty simple and easy to use. Adrian | TITLE:
Considering N2 CMS but worried about performance. Is this justified?
QUESTION:
Hy, does anyone worked with N2 Content Management System( http://www.codeplex.com/n2 ). If yes, how does it perform, performance wise(under heavy load)? It seems pretty simple and easy to use. Adrian
ANSWER:
Maybe try this question at http://www.codeplex.com/n2/Thread/List.aspx They might be able to tell you about performance limitations or bottlenecks. | [
"asp.net",
"performance",
".net-3.5",
"content-management-system",
"n2"
] | 6 | 3 | 3,181 | 5 | 0 | 2008-08-15T14:29:20.887000 | 2008-08-19T01:24:09.923000 |
12,294 | 12,295 | Any good tools for creating timelines? | I need to create a historical timeline starting from 1600's to the present day. I also need to have some way of showing events on the timeline so that they do not appear cluttered when many events are close together. I have tried using Visio 2007 as well as Excel 2007 Radar Charts, but I could not get the results I wanted. the timeline templates in Visio are not great and using Radar charts in Excel leads to cluttered data. Are there any other tools or techniques I could use to create these? @Darren: The first link looks great. Thanks! The second link did not work in Firefox and was rendered as ASCII. It opened up fine in IE. And yes, this is for the end users. So I want it to look as presentable as possible, if you know what I mean. Thanks again! | SIMILIE Timeline would probably suit your needs. http://simile.mit.edu/timeline/ Timeline.NET: http://www.codeplex.com/timelinenet Oh, i guess i should ask... for personal use or for display to end users? that might change what i would suggest, but this could work for internal purposes too i suppose. | Any good tools for creating timelines? I need to create a historical timeline starting from 1600's to the present day. I also need to have some way of showing events on the timeline so that they do not appear cluttered when many events are close together. I have tried using Visio 2007 as well as Excel 2007 Radar Charts, but I could not get the results I wanted. the timeline templates in Visio are not great and using Radar charts in Excel leads to cluttered data. Are there any other tools or techniques I could use to create these? @Darren: The first link looks great. Thanks! The second link did not work in Firefox and was rendered as ASCII. It opened up fine in IE. And yes, this is for the end users. So I want it to look as presentable as possible, if you know what I mean. Thanks again! | TITLE:
Any good tools for creating timelines?
QUESTION:
I need to create a historical timeline starting from 1600's to the present day. I also need to have some way of showing events on the timeline so that they do not appear cluttered when many events are close together. I have tried using Visio 2007 as well as Excel 2007 Radar Charts, but I could not get the results I wanted. the timeline templates in Visio are not great and using Radar charts in Excel leads to cluttered data. Are there any other tools or techniques I could use to create these? @Darren: The first link looks great. Thanks! The second link did not work in Firefox and was rendered as ASCII. It opened up fine in IE. And yes, this is for the end users. So I want it to look as presentable as possible, if you know what I mean. Thanks again!
ANSWER:
SIMILIE Timeline would probably suit your needs. http://simile.mit.edu/timeline/ Timeline.NET: http://www.codeplex.com/timelinenet Oh, i guess i should ask... for personal use or for display to end users? that might change what i would suggest, but this could work for internal purposes too i suppose. | [
"charts",
"timeline"
] | 8 | 6 | 5,375 | 6 | 0 | 2008-08-15T14:32:52.003000 | 2008-08-15T14:33:25.123000 |
12,297 | 12,373 | How can I remove nodes from a SiteMapNodeCollection? | I've got a Repeater that lists all the web.sitemap child pages on an ASP.NET page. Its DataSource is a SiteMapNodeCollection. But, I don't want my registration form page to show up there. Dim Children As SiteMapNodeCollection = SiteMap.CurrentNode.ChildNodes
'remove registration page from collection For Each n As SiteMapNode In SiteMap.CurrentNode.ChildNodes If n.Url = "/Registration.aspx" Then Children.Remove(n) End If Next
RepeaterSubordinatePages.DataSource = Children The SiteMapNodeCollection.Remove() method throws a NotSupportedException: "Collection is read-only". How can I remove the node from the collection before DataBinding the Repeater? | Your shouldn't need CType Dim children = _ From n In SiteMap.CurrentNode.ChildNodes.Cast(Of SiteMapNode)() _ Where n.Url <> "/Registration.aspx" _ Select n | How can I remove nodes from a SiteMapNodeCollection? I've got a Repeater that lists all the web.sitemap child pages on an ASP.NET page. Its DataSource is a SiteMapNodeCollection. But, I don't want my registration form page to show up there. Dim Children As SiteMapNodeCollection = SiteMap.CurrentNode.ChildNodes
'remove registration page from collection For Each n As SiteMapNode In SiteMap.CurrentNode.ChildNodes If n.Url = "/Registration.aspx" Then Children.Remove(n) End If Next
RepeaterSubordinatePages.DataSource = Children The SiteMapNodeCollection.Remove() method throws a NotSupportedException: "Collection is read-only". How can I remove the node from the collection before DataBinding the Repeater? | TITLE:
How can I remove nodes from a SiteMapNodeCollection?
QUESTION:
I've got a Repeater that lists all the web.sitemap child pages on an ASP.NET page. Its DataSource is a SiteMapNodeCollection. But, I don't want my registration form page to show up there. Dim Children As SiteMapNodeCollection = SiteMap.CurrentNode.ChildNodes
'remove registration page from collection For Each n As SiteMapNode In SiteMap.CurrentNode.ChildNodes If n.Url = "/Registration.aspx" Then Children.Remove(n) End If Next
RepeaterSubordinatePages.DataSource = Children The SiteMapNodeCollection.Remove() method throws a NotSupportedException: "Collection is read-only". How can I remove the node from the collection before DataBinding the Repeater?
ANSWER:
Your shouldn't need CType Dim children = _ From n In SiteMap.CurrentNode.ChildNodes.Cast(Of SiteMapNode)() _ Where n.Url <> "/Registration.aspx" _ Select n | [
"asp.net",
".net",
"vb.net",
"repeater",
"sitemap"
] | 1 | 1 | 4,103 | 3 | 0 | 2008-08-15T14:38:18.920000 | 2008-08-15T15:28:40.987000 |
12,306 | 12,342 | Can I serialize a C# Type object? | I'm trying to serialize a Type object in the following way: Type myType = typeof (StringBuilder); var serializer = new XmlSerializer(typeof(Type)); TextWriter writer = new StringWriter(); serializer.Serialize(writer, myType); When I do this, the call to Serialize throws the following exception: "The type System.Text.StringBuilder was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically." Is there a way for me to serialize the Type object? Note that I am not trying to serialize the StringBuilder itself, but the Type object containing the metadata about the StringBuilder class. | I wasn't aware that a Type object could be created with only a string containing the fully-qualified name. To get the fully qualified name, you can use the following: string typeName = typeof (StringBuilder).FullName; You can then persist this string however needed, then reconstruct the type like this: Type t = Type.GetType(typeName); If you need to create an instance of the type, you can do this: object o = Activator.CreateInstance(t); If you check the value of o.GetType(), it will be StringBuilder, just as you would expect. | Can I serialize a C# Type object? I'm trying to serialize a Type object in the following way: Type myType = typeof (StringBuilder); var serializer = new XmlSerializer(typeof(Type)); TextWriter writer = new StringWriter(); serializer.Serialize(writer, myType); When I do this, the call to Serialize throws the following exception: "The type System.Text.StringBuilder was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically." Is there a way for me to serialize the Type object? Note that I am not trying to serialize the StringBuilder itself, but the Type object containing the metadata about the StringBuilder class. | TITLE:
Can I serialize a C# Type object?
QUESTION:
I'm trying to serialize a Type object in the following way: Type myType = typeof (StringBuilder); var serializer = new XmlSerializer(typeof(Type)); TextWriter writer = new StringWriter(); serializer.Serialize(writer, myType); When I do this, the call to Serialize throws the following exception: "The type System.Text.StringBuilder was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically." Is there a way for me to serialize the Type object? Note that I am not trying to serialize the StringBuilder itself, but the Type object containing the metadata about the StringBuilder class.
ANSWER:
I wasn't aware that a Type object could be created with only a string containing the fully-qualified name. To get the fully qualified name, you can use the following: string typeName = typeof (StringBuilder).FullName; You can then persist this string however needed, then reconstruct the type like this: Type t = Type.GetType(typeName); If you need to create an instance of the type, you can do this: object o = Activator.CreateInstance(t); If you check the value of o.GetType(), it will be StringBuilder, just as you would expect. | [
"c#",
"serialization"
] | 60 | 104 | 77,345 | 6 | 0 | 2008-08-15T14:46:07.687000 | 2008-08-15T15:12:43.373000 |
12,319 | 265,407 | _wfopen equivalent under Mac OS X | I'm looking to the equivalent of Windows _wfopen() under Mac OS X. Any idea? I need this in order to port a Windows library that uses wchar* for its File interface. As this is intended to be a cross-platform library, I am unable to rely on how the client application will get the file path and give it to the library. | POSIX API in Mac OS X are usable with UTF-8 strings. In order to convert a wchar_t string to UTF-8, it is possible to use the CoreFoundation framework from Mac OS X. Here is a class that will wrap an UTF-8 generated string from a wchar_t string. class Utf8 { public: Utf8(const wchar_t* wsz): m_utf8(NULL) { // OS X uses 32-bit wchar const int bytes = wcslen(wsz) * sizeof(wchar_t); // comp_bLittleEndian is in the lib I use in order to detect PowerPC/Intel CFStringEncoding encoding = comp_bLittleEndian? kCFStringEncodingUTF32LE: kCFStringEncodingUTF32BE; CFStringRef str = CFStringCreateWithBytesNoCopy(NULL, (const UInt8*)wsz, bytes, encoding, false, kCFAllocatorNull );
const int bytesUtf8 = CFStringGetMaximumSizeOfFileSystemRepresentation(str); m_utf8 = new char[bytesUtf8]; CFStringGetFileSystemRepresentation(str, m_utf8, bytesUtf8); CFRelease(str); }
~Utf8() { if( m_utf8 ) { delete[] m_utf8; } }
public: operator const char*() const { return m_utf8; }
private: char* m_utf8; }; Usage: const wchar_t wsz = L"Here is some Unicode content: éà€œæ"; const Utf8 utf8 = wsz; FILE* file = fopen(utf8, "r"); This will work for reading or writing files. | _wfopen equivalent under Mac OS X I'm looking to the equivalent of Windows _wfopen() under Mac OS X. Any idea? I need this in order to port a Windows library that uses wchar* for its File interface. As this is intended to be a cross-platform library, I am unable to rely on how the client application will get the file path and give it to the library. | TITLE:
_wfopen equivalent under Mac OS X
QUESTION:
I'm looking to the equivalent of Windows _wfopen() under Mac OS X. Any idea? I need this in order to port a Windows library that uses wchar* for its File interface. As this is intended to be a cross-platform library, I am unable to rely on how the client application will get the file path and give it to the library.
ANSWER:
POSIX API in Mac OS X are usable with UTF-8 strings. In order to convert a wchar_t string to UTF-8, it is possible to use the CoreFoundation framework from Mac OS X. Here is a class that will wrap an UTF-8 generated string from a wchar_t string. class Utf8 { public: Utf8(const wchar_t* wsz): m_utf8(NULL) { // OS X uses 32-bit wchar const int bytes = wcslen(wsz) * sizeof(wchar_t); // comp_bLittleEndian is in the lib I use in order to detect PowerPC/Intel CFStringEncoding encoding = comp_bLittleEndian? kCFStringEncodingUTF32LE: kCFStringEncodingUTF32BE; CFStringRef str = CFStringCreateWithBytesNoCopy(NULL, (const UInt8*)wsz, bytes, encoding, false, kCFAllocatorNull );
const int bytesUtf8 = CFStringGetMaximumSizeOfFileSystemRepresentation(str); m_utf8 = new char[bytesUtf8]; CFStringGetFileSystemRepresentation(str, m_utf8, bytesUtf8); CFRelease(str); }
~Utf8() { if( m_utf8 ) { delete[] m_utf8; } }
public: operator const char*() const { return m_utf8; }
private: char* m_utf8; }; Usage: const wchar_t wsz = L"Here is some Unicode content: éà€œæ"; const Utf8 utf8 = wsz; FILE* file = fopen(utf8, "r"); This will work for reading or writing files. | [
"c++",
"winapi",
"macos",
"porting",
"fopen"
] | 18 | 15 | 10,907 | 5 | 0 | 2008-08-15T14:59:11.653000 | 2008-11-05T15:07:26.817000 |
12,330 | 12,381 | Programmatically list WMI classes and their properties | Is there any known way of listing the WMI classes and their properties available for a particular system? Im interested in a vbscript approach, but please suggest anything really:) P.S. Great site. | I believe this is what you want. WMI Code Creator A part of this nifty utility allows you to browse namespaces/classes/properties on the local and remote PCs, not to mention generating WMI code in VBScript/C#/VB on the fly. Very useful. Also, the source code used to create the utility is included in the download, which could provide a reference if you wanted to create your own browser like interface. | Programmatically list WMI classes and their properties Is there any known way of listing the WMI classes and their properties available for a particular system? Im interested in a vbscript approach, but please suggest anything really:) P.S. Great site. | TITLE:
Programmatically list WMI classes and their properties
QUESTION:
Is there any known way of listing the WMI classes and their properties available for a particular system? Im interested in a vbscript approach, but please suggest anything really:) P.S. Great site.
ANSWER:
I believe this is what you want. WMI Code Creator A part of this nifty utility allows you to browse namespaces/classes/properties on the local and remote PCs, not to mention generating WMI code in VBScript/C#/VB on the fly. Very useful. Also, the source code used to create the utility is included in the download, which could provide a reference if you wanted to create your own browser like interface. | [
"vbscript",
"wmi"
] | 7 | 5 | 8,478 | 2 | 0 | 2008-08-15T15:06:31.873000 | 2008-08-15T15:33:42.847000 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.