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
31,163
31,170
Forcing the Solution Explorer to select the file in the editor in visual studio 2005
In Visual Studio 2005, whenever I would view a file in the main editor, the Solution Explorer would find and highlight that file. Some time ago, this stopped working and the Solution Explorer would do nothing. This has become quite a pain since following a chain of "Go To Definition"s can lead you all over your solution. Where is the setting to turn this back on?
Click on the Tools → Options menu. Select the Projects and Solutions → General option page. Make sure "Track active item in Solution Explorer" is checked. That should do it.
Forcing the Solution Explorer to select the file in the editor in visual studio 2005 In Visual Studio 2005, whenever I would view a file in the main editor, the Solution Explorer would find and highlight that file. Some time ago, this stopped working and the Solution Explorer would do nothing. This has become quite a pain since following a chain of "Go To Definition"s can lead you all over your solution. Where is the setting to turn this back on?
TITLE: Forcing the Solution Explorer to select the file in the editor in visual studio 2005 QUESTION: In Visual Studio 2005, whenever I would view a file in the main editor, the Solution Explorer would find and highlight that file. Some time ago, this stopped working and the Solution Explorer would do nothing. This has become quite a pain since following a chain of "Go To Definition"s can lead you all over your solution. Where is the setting to turn this back on? ANSWER: Click on the Tools → Options menu. Select the Projects and Solutions → General option page. Make sure "Track active item in Solution Explorer" is checked. That should do it.
[ "visual-studio" ]
43
63
10,337
6
0
2008-08-27T20:22:53.960000
2008-08-27T20:24:56.687000
31,192
31,217
Migrating from ASP Classic to .NET and pain mitigation
We're in the process of redesigning the customer-facing section of our site in.NET 3.5. It's been going well so far, we're using the same workflow and stored procedures, for the most part, the biggest changes are the UI, the ORM (from dictionaries to LINQ), and obviously the language. Most of the pages to this point have been trivial, but now we're working on the heaviest workflow pages. The main page of our offer acceptance section is 1500 lines, about 90% of that is ASP, with probably another 1000 lines in function calls to includes. I think the 1500 lines is a bit deceiving too since we're working with gems like this function GetDealText(sUSCurASCII, sUSCurName, sTemplateOptionID, sSellerCompany, sOfferAmount, sSellerPremPercent, sTotalOfferToSeller, sSellerPremium, sMode, sSellerCurASCII, sSellerCurName, sTotalOfferToSeller_SellerCurr, sOfferAmount_SellerCurr, sSellerPremium_SellerCurr, sConditions, sListID, sDescription, sSKU, sInv_tag, sFasc_loc, sSerialNoandModel, sQTY, iLoopCount, iBidCount, sHTMLConditions, sBidStatus, sBidID, byRef bAlreadyAccepted, sFasc_Address1, sFasc_City, sFasc_State_id, sFasc_Country_id, sFasc_Company_name, sListingCustID, sAskPrice_SellerCurr, sMinPrice_SellerCurr, sListingCur, sOrigLocation) The standard practice I've been using so far is to spend maybe an hour or so reading over the app both to familiarize myself with it, but also to strip out commented-out/deprecated code. Then to work in a depth-first fashion. I'll start at the top and copy a segment of code in the aspx.cs file and start rewriting, making obvious refactorings as I go especially to take advantage of our ORM. If I get a function call that we don't have, I'll write out the definition. After I have everything coded I'll do a few passes at refactoring/testing. I'm just wondering if anyone has any tips on how to make this process a little easier/more efficient.
Believe me, I know exactly where you are coming from.. I am currently migrating a large app from ASP classic to.NET.. And I am still learning ASP.NET!:S (yes, I am terrified!). The main things I have kept in my mind is this: I dont stray too far from the current design (i.e. no massive "lets rip ALL of this out and make it ASP.NET magical!) due to the incredibly high amount of coupling that ASP classic tends to have, this would be very dangerous. Of course, if you are confident, fill your boots:) This can always be refactored later. Back everything up with tests, tests and more tests! I am really trying hard to get into TDD, but its very difficult to test existing apps, so every time I remove a chunk of classic and replace with.NET, I ensure I have as much green-light tests backing me as possible. Research a lot, there are some MAJOR changes between classic and.NET and sometimes what can be many lines of code and includes in classic can be achieved in a few lines of code, think before coding.. I've learnt this the hard way, several times:D Its very much like playing Jenga with your code:) Best of luck with the project, any more questions, then please ask:)
Migrating from ASP Classic to .NET and pain mitigation We're in the process of redesigning the customer-facing section of our site in.NET 3.5. It's been going well so far, we're using the same workflow and stored procedures, for the most part, the biggest changes are the UI, the ORM (from dictionaries to LINQ), and obviously the language. Most of the pages to this point have been trivial, but now we're working on the heaviest workflow pages. The main page of our offer acceptance section is 1500 lines, about 90% of that is ASP, with probably another 1000 lines in function calls to includes. I think the 1500 lines is a bit deceiving too since we're working with gems like this function GetDealText(sUSCurASCII, sUSCurName, sTemplateOptionID, sSellerCompany, sOfferAmount, sSellerPremPercent, sTotalOfferToSeller, sSellerPremium, sMode, sSellerCurASCII, sSellerCurName, sTotalOfferToSeller_SellerCurr, sOfferAmount_SellerCurr, sSellerPremium_SellerCurr, sConditions, sListID, sDescription, sSKU, sInv_tag, sFasc_loc, sSerialNoandModel, sQTY, iLoopCount, iBidCount, sHTMLConditions, sBidStatus, sBidID, byRef bAlreadyAccepted, sFasc_Address1, sFasc_City, sFasc_State_id, sFasc_Country_id, sFasc_Company_name, sListingCustID, sAskPrice_SellerCurr, sMinPrice_SellerCurr, sListingCur, sOrigLocation) The standard practice I've been using so far is to spend maybe an hour or so reading over the app both to familiarize myself with it, but also to strip out commented-out/deprecated code. Then to work in a depth-first fashion. I'll start at the top and copy a segment of code in the aspx.cs file and start rewriting, making obvious refactorings as I go especially to take advantage of our ORM. If I get a function call that we don't have, I'll write out the definition. After I have everything coded I'll do a few passes at refactoring/testing. I'm just wondering if anyone has any tips on how to make this process a little easier/more efficient.
TITLE: Migrating from ASP Classic to .NET and pain mitigation QUESTION: We're in the process of redesigning the customer-facing section of our site in.NET 3.5. It's been going well so far, we're using the same workflow and stored procedures, for the most part, the biggest changes are the UI, the ORM (from dictionaries to LINQ), and obviously the language. Most of the pages to this point have been trivial, but now we're working on the heaviest workflow pages. The main page of our offer acceptance section is 1500 lines, about 90% of that is ASP, with probably another 1000 lines in function calls to includes. I think the 1500 lines is a bit deceiving too since we're working with gems like this function GetDealText(sUSCurASCII, sUSCurName, sTemplateOptionID, sSellerCompany, sOfferAmount, sSellerPremPercent, sTotalOfferToSeller, sSellerPremium, sMode, sSellerCurASCII, sSellerCurName, sTotalOfferToSeller_SellerCurr, sOfferAmount_SellerCurr, sSellerPremium_SellerCurr, sConditions, sListID, sDescription, sSKU, sInv_tag, sFasc_loc, sSerialNoandModel, sQTY, iLoopCount, iBidCount, sHTMLConditions, sBidStatus, sBidID, byRef bAlreadyAccepted, sFasc_Address1, sFasc_City, sFasc_State_id, sFasc_Country_id, sFasc_Company_name, sListingCustID, sAskPrice_SellerCurr, sMinPrice_SellerCurr, sListingCur, sOrigLocation) The standard practice I've been using so far is to spend maybe an hour or so reading over the app both to familiarize myself with it, but also to strip out commented-out/deprecated code. Then to work in a depth-first fashion. I'll start at the top and copy a segment of code in the aspx.cs file and start rewriting, making obvious refactorings as I go especially to take advantage of our ORM. If I get a function call that we don't have, I'll write out the definition. After I have everything coded I'll do a few passes at refactoring/testing. I'm just wondering if anyone has any tips on how to make this process a little easier/more efficient. ANSWER: Believe me, I know exactly where you are coming from.. I am currently migrating a large app from ASP classic to.NET.. And I am still learning ASP.NET!:S (yes, I am terrified!). The main things I have kept in my mind is this: I dont stray too far from the current design (i.e. no massive "lets rip ALL of this out and make it ASP.NET magical!) due to the incredibly high amount of coupling that ASP classic tends to have, this would be very dangerous. Of course, if you are confident, fill your boots:) This can always be refactored later. Back everything up with tests, tests and more tests! I am really trying hard to get into TDD, but its very difficult to test existing apps, so every time I remove a chunk of classic and replace with.NET, I ensure I have as much green-light tests backing me as possible. Research a lot, there are some MAJOR changes between classic and.NET and sometimes what can be many lines of code and includes in classic can be achieved in a few lines of code, think before coding.. I've learnt this the hard way, several times:D Its very much like playing Jenga with your code:) Best of luck with the project, any more questions, then please ask:)
[ "asp.net", "asp-classic", "migration" ]
5
6
1,885
8
0
2008-08-27T20:32:18.307000
2008-08-27T20:40:31
31,201
31,218
How do you get a reference to the enclosing class from an anonymous inner class in Java?
I'm currently creating an explicit reference to this in the outer class so that I have a name to refer to in the anonymous inner class. Is there a better way to do this?
I just found this recently. Use OuterClassName.this. class Outer { void foo() { new Thread() { public void run() { Outer.this.bar(); } }.start(); } void bar() { System.out.println("BAR!"); } } Updated If you just want the object itself (instead of invoking members), then Outer.this is the way to go.
How do you get a reference to the enclosing class from an anonymous inner class in Java? I'm currently creating an explicit reference to this in the outer class so that I have a name to refer to in the anonymous inner class. Is there a better way to do this?
TITLE: How do you get a reference to the enclosing class from an anonymous inner class in Java? QUESTION: I'm currently creating an explicit reference to this in the outer class so that I have a name to refer to in the anonymous inner class. Is there a better way to do this? ANSWER: I just found this recently. Use OuterClassName.this. class Outer { void foo() { new Thread() { public void run() { Outer.this.bar(); } }.start(); } void bar() { System.out.println("BAR!"); } } Updated If you just want the object itself (instead of invoking members), then Outer.this is the way to go.
[ "java", "oop" ]
52
95
17,056
3
0
2008-08-27T20:36:14.723000
2008-08-27T20:40:40.300000
31,215
31,220
Constructors with the same argument type
I have a Person object with two constructors - one takes an int (personId), the other a string (logonName). I would like another constructor that takes a string (badgeNumber). I know this can't be done, but seems it might be a common situation. Is there a graceful way of handling this? I suppose this would apply to any overloaded method. Code: public class Person { public Person() {} public Person(int personId) { this.Load(personId); } public Person(string logonName) { this.Load(logonName); } public Person(string badgeNumber) { //load logic here... }...etc.
You might consider using custom types. For example, create LogonName and BadgeNumber classes. Then your function declarations look like... public Person(LogonName ln) { this.Load(ln.ToString()); } public Person(BadgeNumber bn) { //load logic here... } Such a solution might give you a good place to keep the business logic that governs the format and usage of these strings.
Constructors with the same argument type I have a Person object with two constructors - one takes an int (personId), the other a string (logonName). I would like another constructor that takes a string (badgeNumber). I know this can't be done, but seems it might be a common situation. Is there a graceful way of handling this? I suppose this would apply to any overloaded method. Code: public class Person { public Person() {} public Person(int personId) { this.Load(personId); } public Person(string logonName) { this.Load(logonName); } public Person(string badgeNumber) { //load logic here... }...etc.
TITLE: Constructors with the same argument type QUESTION: I have a Person object with two constructors - one takes an int (personId), the other a string (logonName). I would like another constructor that takes a string (badgeNumber). I know this can't be done, but seems it might be a common situation. Is there a graceful way of handling this? I suppose this would apply to any overloaded method. Code: public class Person { public Person() {} public Person(int personId) { this.Load(personId); } public Person(string logonName) { this.Load(logonName); } public Person(string badgeNumber) { //load logic here... }...etc. ANSWER: You might consider using custom types. For example, create LogonName and BadgeNumber classes. Then your function declarations look like... public Person(LogonName ln) { this.Load(ln.ToString()); } public Person(BadgeNumber bn) { //load logic here... } Such a solution might give you a good place to keep the business logic that governs the format and usage of these strings.
[ "c#", ".net", "oop" ]
7
7
3,588
13
0
2008-08-27T20:39:51.517000
2008-08-27T20:41:16.210000
31,221
31,437
Response.Redirect using ~ Path
I have a method that where I want to redirect the user back to a login page located at the root of my web application. I'm using the following code: Response.Redirect("~/Login.aspx?ReturnPath=" + Request.Url.ToString()); This doesn't work though. My assumption was that ASP.NET would automatically resolve the URL into the correct path. Normally, I would just use Response.Redirect("../Login.aspx?ReturnPath=" + Request.Url.ToString()); but this code is on a master page, and can be executed from any folder level. How do I get around this issue?
I think you need to drop the "~/" and replace it with just "/", I believe / is the root STOP RIGHT THERE!:-) unless you want to hardcode your web app so that it can only be installed at the root of a web site. "~/" is the correct thing to use, but the reason that your original code didn't work as expected is that ResolveUrl (which is used internally by Redirect ) tries to first work out if the path you are passing it is an absolute URL (e.g. "** http://server/ **foo/bar.htm" as opposed to "foo/bar.htm") - but unfortunately it does this by simply looking for a colon character ':' in the URL you give it. But in this case it finds a colon in the URL you give in the ReturnPath query string value, which fools it - therefore your '~/' doesn't get resolved. The fix is that you should be URL-encoding the ReturnPath value which escapes the problematic ':' along with any other special characters. Response.Redirect("~/Login.aspx?ReturnPath=" + Server.UrlEncode(Request.Url.ToString())); Additionally, I recommend that you (or anyone) never use Uri.ToString - because it gives a human-readable, more "friendly" version of the URL - not a necessarily correct one (it unescapes things). Instead use Uri.AbsoluteUri - like so: Response.Redirect("~/Login.aspx?ReturnPath=" + Server.UrlEncode(Request.Url.AbsoluteUri));
Response.Redirect using ~ Path I have a method that where I want to redirect the user back to a login page located at the root of my web application. I'm using the following code: Response.Redirect("~/Login.aspx?ReturnPath=" + Request.Url.ToString()); This doesn't work though. My assumption was that ASP.NET would automatically resolve the URL into the correct path. Normally, I would just use Response.Redirect("../Login.aspx?ReturnPath=" + Request.Url.ToString()); but this code is on a master page, and can be executed from any folder level. How do I get around this issue?
TITLE: Response.Redirect using ~ Path QUESTION: I have a method that where I want to redirect the user back to a login page located at the root of my web application. I'm using the following code: Response.Redirect("~/Login.aspx?ReturnPath=" + Request.Url.ToString()); This doesn't work though. My assumption was that ASP.NET would automatically resolve the URL into the correct path. Normally, I would just use Response.Redirect("../Login.aspx?ReturnPath=" + Request.Url.ToString()); but this code is on a master page, and can be executed from any folder level. How do I get around this issue? ANSWER: I think you need to drop the "~/" and replace it with just "/", I believe / is the root STOP RIGHT THERE!:-) unless you want to hardcode your web app so that it can only be installed at the root of a web site. "~/" is the correct thing to use, but the reason that your original code didn't work as expected is that ResolveUrl (which is used internally by Redirect ) tries to first work out if the path you are passing it is an absolute URL (e.g. "** http://server/ **foo/bar.htm" as opposed to "foo/bar.htm") - but unfortunately it does this by simply looking for a colon character ':' in the URL you give it. But in this case it finds a colon in the URL you give in the ReturnPath query string value, which fools it - therefore your '~/' doesn't get resolved. The fix is that you should be URL-encoding the ReturnPath value which escapes the problematic ':' along with any other special characters. Response.Redirect("~/Login.aspx?ReturnPath=" + Server.UrlEncode(Request.Url.ToString())); Additionally, I recommend that you (or anyone) never use Uri.ToString - because it gives a human-readable, more "friendly" version of the URL - not a necessarily correct one (it unescapes things). Instead use Uri.AbsoluteUri - like so: Response.Redirect("~/Login.aspx?ReturnPath=" + Server.UrlEncode(Request.Url.AbsoluteUri));
[ "c#", "asp.net", "response.redirect" ]
34
77
75,256
3
0
2008-08-27T20:41:23.357000
2008-08-28T00:40:27.633000
31,226
35,517
Lightweight rich-text XML format?
I am writing a basic word processing application and am trying to settle on a native "internal" format, the one that my code parses in order to render to the screen. I'd like this to be XML so that I can, in the future, just write XSLT to convert it to ODF or XHTML or whatever. When searching for existing standards to use, the only one that looks promising is ODF. But that looks like massive overkill for what I need. All I need is paragraph tags, font selection, font size & decoration...that's pretty much it. It would take me a long time to implement even a minimal ODF renderer, and I'm not sure it's worth the trouble. Right now I'm thinking of making my own XML format, but that's not really good practice. Better to use a standard, especially since then I can probably find the XSLTs I might need in the future already written. Or should I just bite the bullet and implement ODF? EDIT: Regarding the Answer I knew about XSL-FO before, but due to the weight of the spec hadn't really consdiered it. But you're right, a subset would give me everything I need to work with and room to grow. Thanks so much the reminder. Plus, by including a rendering library like FOP or RenderX, I get PDF generation for free. Not bad...
As you are sure about needing to represent the presentational side of things, it may be worth looking at the XSL-FO W3C Recommendation. This is a full-blown page description language and the (deeply unfashionable) other half of the better-known XSLT. Clearly the whole thing is anything but "lightwight", but if you just incorporated a very limited subset - which could even just be (to match your spec of "paragraph tags, font selection, font size & decoration") fo:block and the common font properties, something like: Example Heading Paragraph text here etc etc... This would perhaps have a few advantages over just rolling your own. There's an open specification to work from, and all that implies. It reuses CSS properties as XML attributes (in a similar manner to SVG), so many of the formatting details will seem somewhat familiar. You'd have an upgrade path if you later decided that, say, intelligent paging was a must-have feature - including more sections of the spec as they become relevant to your application. There's one other thing you might get from investigating XSL-FO - seeing how even just-doing-paragraphs-and-fonts can be horrendously complicated. Trying to do text layout and line breaking 'The Right Way' for various different languages and use cases seems very daunting to me.
Lightweight rich-text XML format? I am writing a basic word processing application and am trying to settle on a native "internal" format, the one that my code parses in order to render to the screen. I'd like this to be XML so that I can, in the future, just write XSLT to convert it to ODF or XHTML or whatever. When searching for existing standards to use, the only one that looks promising is ODF. But that looks like massive overkill for what I need. All I need is paragraph tags, font selection, font size & decoration...that's pretty much it. It would take me a long time to implement even a minimal ODF renderer, and I'm not sure it's worth the trouble. Right now I'm thinking of making my own XML format, but that's not really good practice. Better to use a standard, especially since then I can probably find the XSLTs I might need in the future already written. Or should I just bite the bullet and implement ODF? EDIT: Regarding the Answer I knew about XSL-FO before, but due to the weight of the spec hadn't really consdiered it. But you're right, a subset would give me everything I need to work with and room to grow. Thanks so much the reminder. Plus, by including a rendering library like FOP or RenderX, I get PDF generation for free. Not bad...
TITLE: Lightweight rich-text XML format? QUESTION: I am writing a basic word processing application and am trying to settle on a native "internal" format, the one that my code parses in order to render to the screen. I'd like this to be XML so that I can, in the future, just write XSLT to convert it to ODF or XHTML or whatever. When searching for existing standards to use, the only one that looks promising is ODF. But that looks like massive overkill for what I need. All I need is paragraph tags, font selection, font size & decoration...that's pretty much it. It would take me a long time to implement even a minimal ODF renderer, and I'm not sure it's worth the trouble. Right now I'm thinking of making my own XML format, but that's not really good practice. Better to use a standard, especially since then I can probably find the XSLTs I might need in the future already written. Or should I just bite the bullet and implement ODF? EDIT: Regarding the Answer I knew about XSL-FO before, but due to the weight of the spec hadn't really consdiered it. But you're right, a subset would give me everything I need to work with and room to grow. Thanks so much the reminder. Plus, by including a rendering library like FOP or RenderX, I get PDF generation for free. Not bad... ANSWER: As you are sure about needing to represent the presentational side of things, it may be worth looking at the XSL-FO W3C Recommendation. This is a full-blown page description language and the (deeply unfashionable) other half of the better-known XSLT. Clearly the whole thing is anything but "lightwight", but if you just incorporated a very limited subset - which could even just be (to match your spec of "paragraph tags, font selection, font size & decoration") fo:block and the common font properties, something like: Example Heading Paragraph text here etc etc... This would perhaps have a few advantages over just rolling your own. There's an open specification to work from, and all that implies. It reuses CSS properties as XML attributes (in a similar manner to SVG), so many of the formatting details will seem somewhat familiar. You'd have an upgrade path if you later decided that, say, intelligent paging was a must-have feature - including more sections of the spec as they become relevant to your application. There's one other thing you might get from investigating XSL-FO - seeing how even just-doing-paragraphs-and-fonts can be horrendously complicated. Trying to do text layout and line breaking 'The Right Way' for various different languages and use cases seems very daunting to me.
[ "xml", "standards" ]
5
5
2,261
5
0
2008-08-27T20:42:22.230000
2008-08-30T00:36:55.490000
31,237
31,288
Passing around sets of data
A question that has pondered me for the last while. I am primarily a.net developer who dabbles in Objective-C for iPhone and Mac. How do you go about sending "datasets" between methods in objective-c. For example in C# you can populate a custom class with data and pass it around in a List of type custom class. EG if you had a customer class you would just do something like: List customers = DataLayer.GetAllCustomers(); The only way I can see how this could be done in obj-c would be to populate an NSArray with custom objects? Is this an efficient way to do things? Any other recommendations? I am using sqlite as the database/data I want to return.
You're on the right track. Cocoa's collection classes — which all have mutable an immutable variants — are: NSArray: ordered, can contain an object multiple times NSDictionary: unordered, mapping from keys to values, keys are copied NSSet: unordered, can contain an object only once NSCountedSet: unordered, can contain an object multiple times The immutable variants help a lot with efficiency. The standard pattern for accessors of classes that have mutable variants is to copy rather than retain. This is codified in the @property mechanism, by using the copy attribute on the property: // Department.h @interface Department: NSObject @property (readwrite, copy) NSSet *employees; @end This means that if you pass a mutable array to something that takes an array, it will be copied, and if you pass that to something else, it will be copied again. The trick is though that "copying" an immutable object really just retains it, so you only take a hit for that first copy. You probably want to make a copy that first time anyway so you don't pass a mutable array to something else, then mutate it behind the back of whatever you passed it to. For Cocoa on Mac OS X, I'd also strongly encourage you to take a look at Core Data. It's an alternative to the "data set" pattern you might be used to from.NET/ADO/etc. With Core Data, you don't "get all customers" and then pass that collection around. Instead you query for the customers you care about, and as you traverse relationships of the objects you've queried for, other objects will be pulled in for you automatically. Core Data also gets you features like visual modeling of your entities, automatic generation of property getters & setters, fine-grained control over migration from one schema version to another, and so on.
Passing around sets of data A question that has pondered me for the last while. I am primarily a.net developer who dabbles in Objective-C for iPhone and Mac. How do you go about sending "datasets" between methods in objective-c. For example in C# you can populate a custom class with data and pass it around in a List of type custom class. EG if you had a customer class you would just do something like: List customers = DataLayer.GetAllCustomers(); The only way I can see how this could be done in obj-c would be to populate an NSArray with custom objects? Is this an efficient way to do things? Any other recommendations? I am using sqlite as the database/data I want to return.
TITLE: Passing around sets of data QUESTION: A question that has pondered me for the last while. I am primarily a.net developer who dabbles in Objective-C for iPhone and Mac. How do you go about sending "datasets" between methods in objective-c. For example in C# you can populate a custom class with data and pass it around in a List of type custom class. EG if you had a customer class you would just do something like: List customers = DataLayer.GetAllCustomers(); The only way I can see how this could be done in obj-c would be to populate an NSArray with custom objects? Is this an efficient way to do things? Any other recommendations? I am using sqlite as the database/data I want to return. ANSWER: You're on the right track. Cocoa's collection classes — which all have mutable an immutable variants — are: NSArray: ordered, can contain an object multiple times NSDictionary: unordered, mapping from keys to values, keys are copied NSSet: unordered, can contain an object only once NSCountedSet: unordered, can contain an object multiple times The immutable variants help a lot with efficiency. The standard pattern for accessors of classes that have mutable variants is to copy rather than retain. This is codified in the @property mechanism, by using the copy attribute on the property: // Department.h @interface Department: NSObject @property (readwrite, copy) NSSet *employees; @end This means that if you pass a mutable array to something that takes an array, it will be copied, and if you pass that to something else, it will be copied again. The trick is though that "copying" an immutable object really just retains it, so you only take a hit for that first copy. You probably want to make a copy that first time anyway so you don't pass a mutable array to something else, then mutate it behind the back of whatever you passed it to. For Cocoa on Mac OS X, I'd also strongly encourage you to take a look at Core Data. It's an alternative to the "data set" pattern you might be used to from.NET/ADO/etc. With Core Data, you don't "get all customers" and then pass that collection around. Instead you query for the customers you care about, and as you traverse relationships of the objects you've queried for, other objects will be pulled in for you automatically. Core Data also gets you features like visual modeling of your entities, automatic generation of property getters & setters, fine-grained control over migration from one schema version to another, and so on.
[ "objective-c", "cocoa", "macos", "sqlite" ]
8
25
2,951
1
0
2008-08-27T20:45:36.620000
2008-08-27T21:03:04.880000
31,249
31,260
How do I set ItemTemplate dynamically in WPF?
Using WPF, I have a TreeView control that I want to set its ItemTemplate dynamically through procedural code. How do I do this? I assume I need to find the resource somewhere. myTreeViewControl.ItemTemplate =??
If the template is defined in your section directly: myTreeViewControl.ItemTemplate = this.Resources["SomeTemplate"] as DataTemplate; If it's somewhere deep within your window, like in a section or something, I think this'll work: myTreeViewControl.ItemTemplate = this.FindResource("SomeTemplate") as DataTemplate; And if it's elsewhere in your application, I think App.FindResource("SomeTemplate") will work.
How do I set ItemTemplate dynamically in WPF? Using WPF, I have a TreeView control that I want to set its ItemTemplate dynamically through procedural code. How do I do this? I assume I need to find the resource somewhere. myTreeViewControl.ItemTemplate =??
TITLE: How do I set ItemTemplate dynamically in WPF? QUESTION: Using WPF, I have a TreeView control that I want to set its ItemTemplate dynamically through procedural code. How do I do this? I assume I need to find the resource somewhere. myTreeViewControl.ItemTemplate =?? ANSWER: If the template is defined in your section directly: myTreeViewControl.ItemTemplate = this.Resources["SomeTemplate"] as DataTemplate; If it's somewhere deep within your window, like in a section or something, I think this'll work: myTreeViewControl.ItemTemplate = this.FindResource("SomeTemplate") as DataTemplate; And if it's elsewhere in your application, I think App.FindResource("SomeTemplate") will work.
[ "wpf", "itemtemplate" ]
9
12
5,480
2
0
2008-08-27T20:48:17.893000
2008-08-27T20:51:01.443000
31,285
68,525
VMWare Tools for Ubuntu Hardy
I am using VMWare tools for Ubuntu Hardy, but for some reason vmware-install.pl finds fault with my LINUX headers. The error message says that the "address space size" doesn't match. To try and remediate, I have resorted to vmware-any-any-update117, and am now getting the following error instead: In file included from include/asm/page.h:3, from /tmp/vmware-config0/vmmon-only/common/hostKernel.h:56, from /tmp/vmware-config0/vmmon-only/common/task.c:30: include/asm/page_32.h: In function ‘pte_t native_make_pte(long unsigned int)’: include/asm/page_32.h:112: error: expected primary-expression before ‘)’ token include/asm/page_32.h:112: error: expected ‘;’ before ‘{’ token include/asm/page_32.h:112: error: expected primary-expression before ‘.’ token include/asm/page_32.h:112: error: expected `;' before ‘}’ token Can anyone help me make some sense of this, please?
Check out this link as it helped me install the tools in one of my vms. http://diamondsw.dyndns.org/Home/Et_Cetera/Entries/2008/4/25_Linux_2.6.24_and_VMWare.html
VMWare Tools for Ubuntu Hardy I am using VMWare tools for Ubuntu Hardy, but for some reason vmware-install.pl finds fault with my LINUX headers. The error message says that the "address space size" doesn't match. To try and remediate, I have resorted to vmware-any-any-update117, and am now getting the following error instead: In file included from include/asm/page.h:3, from /tmp/vmware-config0/vmmon-only/common/hostKernel.h:56, from /tmp/vmware-config0/vmmon-only/common/task.c:30: include/asm/page_32.h: In function ‘pte_t native_make_pte(long unsigned int)’: include/asm/page_32.h:112: error: expected primary-expression before ‘)’ token include/asm/page_32.h:112: error: expected ‘;’ before ‘{’ token include/asm/page_32.h:112: error: expected primary-expression before ‘.’ token include/asm/page_32.h:112: error: expected `;' before ‘}’ token Can anyone help me make some sense of this, please?
TITLE: VMWare Tools for Ubuntu Hardy QUESTION: I am using VMWare tools for Ubuntu Hardy, but for some reason vmware-install.pl finds fault with my LINUX headers. The error message says that the "address space size" doesn't match. To try and remediate, I have resorted to vmware-any-any-update117, and am now getting the following error instead: In file included from include/asm/page.h:3, from /tmp/vmware-config0/vmmon-only/common/hostKernel.h:56, from /tmp/vmware-config0/vmmon-only/common/task.c:30: include/asm/page_32.h: In function ‘pte_t native_make_pte(long unsigned int)’: include/asm/page_32.h:112: error: expected primary-expression before ‘)’ token include/asm/page_32.h:112: error: expected ‘;’ before ‘{’ token include/asm/page_32.h:112: error: expected primary-expression before ‘.’ token include/asm/page_32.h:112: error: expected `;' before ‘}’ token Can anyone help me make some sense of this, please? ANSWER: Check out this link as it helped me install the tools in one of my vms. http://diamondsw.dyndns.org/Home/Et_Cetera/Entries/2008/4/25_Linux_2.6.24_and_VMWare.html
[ "ubuntu", "vmware", "virtualization", "vmware-tools" ]
2
1
952
4
0
2008-08-27T21:01:11.950000
2008-09-16T01:24:39.757000
31,287
31,624
Using Virtual PC for Web Development with Oracle
Is anyone using Virtual PC to maintain multiple large.NET 1.1 and 2.0 websites? Are there any lessons learned? I used Virtual PC recently with a small WinForms app and it worked great, but then everything works great with WinForms. ASP.NET development hogs way more resources, requires IIS to be running, requires a ridiculously long wait after recompilations, etc., so I'm a little concerned. And I'll also be using Oracle, if that makes any difference. Also, is there any real reason to use VM Ware instead of Virtual PC?
I've used VirtualPCs for a few years for development of some fairly hefty web apps without much problem. Lots of RAM is important. I keep my VPCs on an external USB drive and they perform great from there. This gives me the flexibility to take the drive with me if I need to do work somewhere else... just install VPC on a host plug in the USB drive and start coding. For servers, we use VMWare and have had little to no trouble with it. Recently I went back to working on my local machine as you lose the benefit of dual monitors with VPCs, and I don't need to be as mobile as I used to.
Using Virtual PC for Web Development with Oracle Is anyone using Virtual PC to maintain multiple large.NET 1.1 and 2.0 websites? Are there any lessons learned? I used Virtual PC recently with a small WinForms app and it worked great, but then everything works great with WinForms. ASP.NET development hogs way more resources, requires IIS to be running, requires a ridiculously long wait after recompilations, etc., so I'm a little concerned. And I'll also be using Oracle, if that makes any difference. Also, is there any real reason to use VM Ware instead of Virtual PC?
TITLE: Using Virtual PC for Web Development with Oracle QUESTION: Is anyone using Virtual PC to maintain multiple large.NET 1.1 and 2.0 websites? Are there any lessons learned? I used Virtual PC recently with a small WinForms app and it worked great, but then everything works great with WinForms. ASP.NET development hogs way more resources, requires IIS to be running, requires a ridiculously long wait after recompilations, etc., so I'm a little concerned. And I'll also be using Oracle, if that makes any difference. Also, is there any real reason to use VM Ware instead of Virtual PC? ANSWER: I've used VirtualPCs for a few years for development of some fairly hefty web apps without much problem. Lots of RAM is important. I keep my VPCs on an external USB drive and they perform great from there. This gives me the flexibility to take the drive with me if I need to do work somewhere else... just install VPC on a host plug in the USB drive and start coding. For servers, we use VMWare and have had little to no trouble with it. Recently I went back to working on my local machine as you lose the benefit of dual monitors with VPCs, and I don't need to be as mobile as I used to.
[ "performance", "virtual-pc" ]
0
1
476
5
0
2008-08-27T21:02:03.337000
2008-08-28T03:38:45.317000
31,296
31,391
Fast SQL Server 2005 script generation
It seems like the generation of SQL scripts from the SQL Server Management Studio is terribly slow. I think that the old Enterprise Manager could run laps around the newer script generation tool. I've seen a few posts here and there with other folks complaining about the speed, but I haven't seen much offered in the way of alternatives. Is there a low-cost/free tool for scripting an entire SQL Server 2005 database that will perform better that SSMS? It would be hard to do worse.
See the Database Publishing Wizard that is part of the SQL Server Hosting Toolkit. It generates a single SQL file for both schema and data.
Fast SQL Server 2005 script generation It seems like the generation of SQL scripts from the SQL Server Management Studio is terribly slow. I think that the old Enterprise Manager could run laps around the newer script generation tool. I've seen a few posts here and there with other folks complaining about the speed, but I haven't seen much offered in the way of alternatives. Is there a low-cost/free tool for scripting an entire SQL Server 2005 database that will perform better that SSMS? It would be hard to do worse.
TITLE: Fast SQL Server 2005 script generation QUESTION: It seems like the generation of SQL scripts from the SQL Server Management Studio is terribly slow. I think that the old Enterprise Manager could run laps around the newer script generation tool. I've seen a few posts here and there with other folks complaining about the speed, but I haven't seen much offered in the way of alternatives. Is there a low-cost/free tool for scripting an entire SQL Server 2005 database that will perform better that SSMS? It would be hard to do worse. ANSWER: See the Database Publishing Wizard that is part of the SQL Server Hosting Toolkit. It generates a single SQL file for both schema and data.
[ "sql-server", "scripting" ]
2
3
1,033
4
0
2008-08-27T21:08:15.537000
2008-08-28T00:16:14.383000
31,297
31,730
Cannot access a webservice from mobile device
I developed a program in a mobile device (Pocket PC 2003) to access a web service, the web service is installed on a Windows XP SP2 PC with IIS, the PC has the IP 192.168.5.2. The device obtains from the wireless network the IP 192.168.5.118 and the program works OK, it calls the method from the web service and executes the action that is needed. This program is going to be used in various buildings. Now I have this problem, it turns that when I try to test it in another building (distances neraly about 100 mts. or 200 mts.) connected with the network, the program cannot connect to the webservice, at this moment the device gets from an Access Point the IP 192.168.10.25, and it accesses the same XP machine I stated before (192.168.5.2). I made a mobile aspx page to verify that I can reach the web server over the network and it loads it in the device, I even made a winform that access the same webservice in a PC from that building and also works there so I don't understand what is going on. I also tried to ping that 192.168.5.2 PC and it responds alive. After that fail I returned to the original place where I tested the program before and it happens that it works normally. The only thing that I look different here is that the third number in the IP is 10 instead of 5, another observation is that I can't ping to the mobile device. I feel confused I don't know what happens here? What could be the problem? This is how I call the web service; //Connect to webservice svc = new TheWebService(); svc.Credentials = new System.Net.NetworkCredential(Settings.UserName, Settings.Password); svc.AllowAutoRedirect = false; svc.UserAgent = Settings.UserAgent; svc.PreAuthenticate = true; svc.Url = Settings.Url; svc.Timeout = System.Threading.Timeout.Infinite; //Send information to webservice svc.ExecuteMethod(info); the content of the app.config in the mobile device is; Does anyone have an idea what is going on?
This looks like a network issue, unless there's an odd bug in.Net CF that doesn't allow you to traverse subnets in certain situations (I can find no evidence of such a thing from googling). Can you get any support from the network/IT team? Also, have you tried it from a different subnet? I.e. not the same as the XP machine (192.168.5.x) and not the same as the one that's not worked so far (192.168.10.). @Shaun Austin - that wouldn't explain why they can get at a regular web page on the XP machine from the different subnet.
Cannot access a webservice from mobile device I developed a program in a mobile device (Pocket PC 2003) to access a web service, the web service is installed on a Windows XP SP2 PC with IIS, the PC has the IP 192.168.5.2. The device obtains from the wireless network the IP 192.168.5.118 and the program works OK, it calls the method from the web service and executes the action that is needed. This program is going to be used in various buildings. Now I have this problem, it turns that when I try to test it in another building (distances neraly about 100 mts. or 200 mts.) connected with the network, the program cannot connect to the webservice, at this moment the device gets from an Access Point the IP 192.168.10.25, and it accesses the same XP machine I stated before (192.168.5.2). I made a mobile aspx page to verify that I can reach the web server over the network and it loads it in the device, I even made a winform that access the same webservice in a PC from that building and also works there so I don't understand what is going on. I also tried to ping that 192.168.5.2 PC and it responds alive. After that fail I returned to the original place where I tested the program before and it happens that it works normally. The only thing that I look different here is that the third number in the IP is 10 instead of 5, another observation is that I can't ping to the mobile device. I feel confused I don't know what happens here? What could be the problem? This is how I call the web service; //Connect to webservice svc = new TheWebService(); svc.Credentials = new System.Net.NetworkCredential(Settings.UserName, Settings.Password); svc.AllowAutoRedirect = false; svc.UserAgent = Settings.UserAgent; svc.PreAuthenticate = true; svc.Url = Settings.Url; svc.Timeout = System.Threading.Timeout.Infinite; //Send information to webservice svc.ExecuteMethod(info); the content of the app.config in the mobile device is; Does anyone have an idea what is going on?
TITLE: Cannot access a webservice from mobile device QUESTION: I developed a program in a mobile device (Pocket PC 2003) to access a web service, the web service is installed on a Windows XP SP2 PC with IIS, the PC has the IP 192.168.5.2. The device obtains from the wireless network the IP 192.168.5.118 and the program works OK, it calls the method from the web service and executes the action that is needed. This program is going to be used in various buildings. Now I have this problem, it turns that when I try to test it in another building (distances neraly about 100 mts. or 200 mts.) connected with the network, the program cannot connect to the webservice, at this moment the device gets from an Access Point the IP 192.168.10.25, and it accesses the same XP machine I stated before (192.168.5.2). I made a mobile aspx page to verify that I can reach the web server over the network and it loads it in the device, I even made a winform that access the same webservice in a PC from that building and also works there so I don't understand what is going on. I also tried to ping that 192.168.5.2 PC and it responds alive. After that fail I returned to the original place where I tested the program before and it happens that it works normally. The only thing that I look different here is that the third number in the IP is 10 instead of 5, another observation is that I can't ping to the mobile device. I feel confused I don't know what happens here? What could be the problem? This is how I call the web service; //Connect to webservice svc = new TheWebService(); svc.Credentials = new System.Net.NetworkCredential(Settings.UserName, Settings.Password); svc.AllowAutoRedirect = false; svc.UserAgent = Settings.UserAgent; svc.PreAuthenticate = true; svc.Url = Settings.Url; svc.Timeout = System.Threading.Timeout.Infinite; //Send information to webservice svc.ExecuteMethod(info); the content of the app.config in the mobile device is; Does anyone have an idea what is going on? ANSWER: This looks like a network issue, unless there's an odd bug in.Net CF that doesn't allow you to traverse subnets in certain situations (I can find no evidence of such a thing from googling). Can you get any support from the network/IT team? Also, have you tried it from a different subnet? I.e. not the same as the XP machine (192.168.5.x) and not the same as the one that's not worked so far (192.168.10.). @Shaun Austin - that wouldn't explain why they can get at a regular web page on the XP machine from the different subnet.
[ "mobile" ]
1
0
1,502
3
0
2008-08-27T21:08:24.383000
2008-08-28T06:43:41.363000
31,303
31,481
Checklist for Database Schema Upgrades
Having to upgrade a database schema makes installing a new release of software a lot trickier. What are the best practices for doing this? I'm looking for a checklist or timeline of action items, such as 8:30 shut down apps 8:45 modify schema 9:15 install new apps 9:30 restart db etc, showing how to minimize risk and downtime. Issues such as backing out of the upgrade if things go awry minimizing impact to existing apps "hot" updates while the database is running promoting from dev to test to production servers are especially of interest.
I have a lot of experience with this. My application is highly iterative, and schema changes happen frequently. I do a production release roughly every 2 to 3 weeks, with 50-100 items cleared from my FogBugz list for each one. Every release we've done over the last few years has required schema changes to support new features. The key to this is to practice the changes several times in a test environment before actually making them on the live servers. I keep a deployment checklist file that is copied from a template and then heavily edited for each release with anything that is out of the ordinary. I have two scripts that I run on the database, one for schema changes, one for programmability (procedures, views, etc). The changes script is coded by hand, and the one with the procs is scripted via Powershell. The change script is run when everything is turned off (you have to pick a time that annoys the least amount of users for this), and it is run command by command, manually, just in case anything goes weird. The most common problem I have run into is adding a unique constraint that fails due to duplicate rows. When preparing for an integration testing cycle, I go through my checklist on a test server, as if that server was production. Then, in addition to that, I go get an actual copy of the production database (this is a good time to swap out your offsite backups), and I run the scripts on a restored local version (which is also good because it proves my latest backup is sound). I'm killing a lot of birds with one stone here. So that's 4 databases total: Dev: all changes must be made in the change script, never with studio. Test: Integration testing happens here Copy of production: Last minute deployment practice Production You really, really need to get it right when you do it on production. Backing out schema changes is hard. As far as hotfixes, I will only ever hotfix procedures, never schema, unless it's a very isolated change and crucial for the business.
Checklist for Database Schema Upgrades Having to upgrade a database schema makes installing a new release of software a lot trickier. What are the best practices for doing this? I'm looking for a checklist or timeline of action items, such as 8:30 shut down apps 8:45 modify schema 9:15 install new apps 9:30 restart db etc, showing how to minimize risk and downtime. Issues such as backing out of the upgrade if things go awry minimizing impact to existing apps "hot" updates while the database is running promoting from dev to test to production servers are especially of interest.
TITLE: Checklist for Database Schema Upgrades QUESTION: Having to upgrade a database schema makes installing a new release of software a lot trickier. What are the best practices for doing this? I'm looking for a checklist or timeline of action items, such as 8:30 shut down apps 8:45 modify schema 9:15 install new apps 9:30 restart db etc, showing how to minimize risk and downtime. Issues such as backing out of the upgrade if things go awry minimizing impact to existing apps "hot" updates while the database is running promoting from dev to test to production servers are especially of interest. ANSWER: I have a lot of experience with this. My application is highly iterative, and schema changes happen frequently. I do a production release roughly every 2 to 3 weeks, with 50-100 items cleared from my FogBugz list for each one. Every release we've done over the last few years has required schema changes to support new features. The key to this is to practice the changes several times in a test environment before actually making them on the live servers. I keep a deployment checklist file that is copied from a template and then heavily edited for each release with anything that is out of the ordinary. I have two scripts that I run on the database, one for schema changes, one for programmability (procedures, views, etc). The changes script is coded by hand, and the one with the procs is scripted via Powershell. The change script is run when everything is turned off (you have to pick a time that annoys the least amount of users for this), and it is run command by command, manually, just in case anything goes weird. The most common problem I have run into is adding a unique constraint that fails due to duplicate rows. When preparing for an integration testing cycle, I go through my checklist on a test server, as if that server was production. Then, in addition to that, I go get an actual copy of the production database (this is a good time to swap out your offsite backups), and I run the scripts on a restored local version (which is also good because it proves my latest backup is sound). I'm killing a lot of birds with one stone here. So that's 4 databases total: Dev: all changes must be made in the change script, never with studio. Test: Integration testing happens here Copy of production: Last minute deployment practice Production You really, really need to get it right when you do it on production. Backing out schema changes is hard. As far as hotfixes, I will only ever hotfix procedures, never schema, unless it's a very isolated change and crucial for the business.
[ "database", "installation", "version-control" ]
11
5
1,411
5
0
2008-08-27T21:11:20.913000
2008-08-28T01:39:40.673000
31,312
287,822
Problems passing special chars with observe_field
I am working on a rails project. Using the tag observe_field, I am taking text typed into a text area, processing it in a control, and displaying the result in a div (very similar to the preview in stack overflow). Everything works fine until I type certain special chars.? => causes the variable not to be found in the params object (pound) => causes an invalid authenticity error % => stops the div from being updated & => every thing after the & is no longer passed into the variable on the server. Is there a way to solve this? --- code sample --- this is the view. ( 'postbody' is a text area) <%= observe_field 'postbody',:update => 'preview',:url => {:controller => 'blog',:action => 'textile_to_html'},:frequency => 0.5,:with => 'postbody' -%> this is the controller that is called def textile_to_html text = params['postbody'] if text == nil then @textile_to_html = ' never set' else r = RedCloth.new text @textile_to_html = r.to_html end render:layout => false end and this is the javascript that is created: new Form.Element.Observer('postbody', 0.5, function(element, value) {new Ajax.Updater('preview', '/blog/textile_to_html', {asynchronous:true, evalScripts:true, parameters:'postbody=' + value + '&authenticity_token=' + encodeURIComponent('22f7ee12eac9efd418caa0fe76ae9e862025ef97')})})
This is an escaping issue (as stated by others). You'll want to change your observe_field:with statement to something like::with => "'postbody=' + encodeURIComponent(value)" Then in your controller: def textile_to_html text = URI.unescape(params['postbody'])...
Problems passing special chars with observe_field I am working on a rails project. Using the tag observe_field, I am taking text typed into a text area, processing it in a control, and displaying the result in a div (very similar to the preview in stack overflow). Everything works fine until I type certain special chars.? => causes the variable not to be found in the params object (pound) => causes an invalid authenticity error % => stops the div from being updated & => every thing after the & is no longer passed into the variable on the server. Is there a way to solve this? --- code sample --- this is the view. ( 'postbody' is a text area) <%= observe_field 'postbody',:update => 'preview',:url => {:controller => 'blog',:action => 'textile_to_html'},:frequency => 0.5,:with => 'postbody' -%> this is the controller that is called def textile_to_html text = params['postbody'] if text == nil then @textile_to_html = ' never set' else r = RedCloth.new text @textile_to_html = r.to_html end render:layout => false end and this is the javascript that is created: new Form.Element.Observer('postbody', 0.5, function(element, value) {new Ajax.Updater('preview', '/blog/textile_to_html', {asynchronous:true, evalScripts:true, parameters:'postbody=' + value + '&authenticity_token=' + encodeURIComponent('22f7ee12eac9efd418caa0fe76ae9e862025ef97')})})
TITLE: Problems passing special chars with observe_field QUESTION: I am working on a rails project. Using the tag observe_field, I am taking text typed into a text area, processing it in a control, and displaying the result in a div (very similar to the preview in stack overflow). Everything works fine until I type certain special chars.? => causes the variable not to be found in the params object (pound) => causes an invalid authenticity error % => stops the div from being updated & => every thing after the & is no longer passed into the variable on the server. Is there a way to solve this? --- code sample --- this is the view. ( 'postbody' is a text area) <%= observe_field 'postbody',:update => 'preview',:url => {:controller => 'blog',:action => 'textile_to_html'},:frequency => 0.5,:with => 'postbody' -%> this is the controller that is called def textile_to_html text = params['postbody'] if text == nil then @textile_to_html = ' never set' else r = RedCloth.new text @textile_to_html = r.to_html end render:layout => false end and this is the javascript that is created: new Form.Element.Observer('postbody', 0.5, function(element, value) {new Ajax.Updater('preview', '/blog/textile_to_html', {asynchronous:true, evalScripts:true, parameters:'postbody=' + value + '&authenticity_token=' + encodeURIComponent('22f7ee12eac9efd418caa0fe76ae9e862025ef97')})}) ANSWER: This is an escaping issue (as stated by others). You'll want to change your observe_field:with statement to something like::with => "'postbody=' + encodeURIComponent(value)" Then in your controller: def textile_to_html text = URI.unescape(params['postbody'])...
[ "ruby-on-rails", "ajax" ]
1
3
465
3
0
2008-08-27T21:17:17.717000
2008-11-13T18:43:57.747000
31,324
31,418
How do I add a constant column value during data transfer from CSV to SQL?
I am reading in CSV file and translating it to an SQL Table. The kicker is that one of the columns in the table is of data type ID that needs to be set to a constant (in this case 2). I am not sure how to do this.
You can use a Derived Column Transformation in which you'll create a new output column and set its value to 2. You can then use that column when outputting to SQL.
How do I add a constant column value during data transfer from CSV to SQL? I am reading in CSV file and translating it to an SQL Table. The kicker is that one of the columns in the table is of data type ID that needs to be set to a constant (in this case 2). I am not sure how to do this.
TITLE: How do I add a constant column value during data transfer from CSV to SQL? QUESTION: I am reading in CSV file and translating it to an SQL Table. The kicker is that one of the columns in the table is of data type ID that needs to be set to a constant (in this case 2). I am not sure how to do this. ANSWER: You can use a Derived Column Transformation in which you'll create a new output column and set its value to 2. You can then use that column when outputting to SQL.
[ "sql-server", "ssis", "csv" ]
14
26
24,722
1
0
2008-08-27T23:33:35.813000
2008-08-28T00:30:25.550000
31,340
31,398
How do threads work in Python, and what are common Python-threading specific pitfalls?
I've been trying to wrap my head around how threads work in Python, and it's hard to find good information on how they operate. I may just be missing a link or something, but it seems like the official documentation isn't very thorough on the subject, and I haven't been able to find a good write-up. From what I can tell, only one thread can be running at once, and the active thread switches every 10 instructions or so? Where is there a good explanation, or can you provide one? It would also be very nice to be aware of common problems that you run into while using threads with Python.
Yes, because of the Global Interpreter Lock (GIL) there can only run one thread at a time. Here are some links with some insights about this: http://www.artima.com/weblogs/viewpost.jsp?thread=214235 http://smoothspan.wordpress.com/2007/09/14/guido-is-right-to-leave-the-gil-in-python-not-for-multicore-but-for-utility-computing/ From the last link an interesting quote: Let me explain what all that means. Threads run inside the same virtual machine, and hence run on the same physical machine. Processes can run on the same physical machine or in another physical machine. If you architect your application around threads, you’ve done nothing to access multiple machines. So, you can scale to as many cores are on the single machine (which will be quite a few over time), but to really reach web scales, you’ll need to solve the multiple machine problem anyway. If you want to use multi core, pyprocessing defines an process based API to do real parallelization. The PEP also includes some interesting benchmarks.
How do threads work in Python, and what are common Python-threading specific pitfalls? I've been trying to wrap my head around how threads work in Python, and it's hard to find good information on how they operate. I may just be missing a link or something, but it seems like the official documentation isn't very thorough on the subject, and I haven't been able to find a good write-up. From what I can tell, only one thread can be running at once, and the active thread switches every 10 instructions or so? Where is there a good explanation, or can you provide one? It would also be very nice to be aware of common problems that you run into while using threads with Python.
TITLE: How do threads work in Python, and what are common Python-threading specific pitfalls? QUESTION: I've been trying to wrap my head around how threads work in Python, and it's hard to find good information on how they operate. I may just be missing a link or something, but it seems like the official documentation isn't very thorough on the subject, and I haven't been able to find a good write-up. From what I can tell, only one thread can be running at once, and the active thread switches every 10 instructions or so? Where is there a good explanation, or can you provide one? It would also be very nice to be aware of common problems that you run into while using threads with Python. ANSWER: Yes, because of the Global Interpreter Lock (GIL) there can only run one thread at a time. Here are some links with some insights about this: http://www.artima.com/weblogs/viewpost.jsp?thread=214235 http://smoothspan.wordpress.com/2007/09/14/guido-is-right-to-leave-the-gil-in-python-not-for-multicore-but-for-utility-computing/ From the last link an interesting quote: Let me explain what all that means. Threads run inside the same virtual machine, and hence run on the same physical machine. Processes can run on the same physical machine or in another physical machine. If you architect your application around threads, you’ve done nothing to access multiple machines. So, you can scale to as many cores are on the single machine (which will be quite a few over time), but to really reach web scales, you’ll need to solve the multiple machine problem anyway. If you want to use multi core, pyprocessing defines an process based API to do real parallelization. The PEP also includes some interesting benchmarks.
[ "python", "multithreading" ]
95
54
48,986
7
0
2008-08-27T23:44:47.843000
2008-08-28T00:19:50.320000
31,343
31,347
Do you need the .NET 1.0 framework to target the .NET 1.0 framework?
I have a bunch of.NET frameworks installed on my machine. I know that with the Java JDK, I can use the 6.0 version to target 5.0 and earlier. Can I do something similar with the.NET framework - target 1.0 and 2.0 with the 3.0 framework?
Visual Studio 2008 was the first to support targeting older versions of.NET. Unfortunately, it supports only.NET 2 and up. In other words, you'll need.NET framework SDK 1 or 1.1 to do this.
Do you need the .NET 1.0 framework to target the .NET 1.0 framework? I have a bunch of.NET frameworks installed on my machine. I know that with the Java JDK, I can use the 6.0 version to target 5.0 and earlier. Can I do something similar with the.NET framework - target 1.0 and 2.0 with the 3.0 framework?
TITLE: Do you need the .NET 1.0 framework to target the .NET 1.0 framework? QUESTION: I have a bunch of.NET frameworks installed on my machine. I know that with the Java JDK, I can use the 6.0 version to target 5.0 and earlier. Can I do something similar with the.NET framework - target 1.0 and 2.0 with the 3.0 framework? ANSWER: Visual Studio 2008 was the first to support targeting older versions of.NET. Unfortunately, it supports only.NET 2 and up. In other words, you'll need.NET framework SDK 1 or 1.1 to do this.
[ ".net" ]
2
2
630
3
0
2008-08-27T23:46:21.633000
2008-08-27T23:48:44.607000
31,346
31,454
What's the best way to display a video with rounded corners in Silverlight?
The MediaElement doesn't support rounded corners (radiusx, radiusy). Should I use a VideoBrush on a Rectangle with rounded corners?
Yeah - In a way you're both asking and answering the question yourself... But that is one of the two options I can think of. The reasons that might be a problem is that you lose some of the features/control you get from the MediaElement control. Another option is to do this: Add your MediaElement to your page. Draw a Rectangle on top of it and set wanted corner radius Right click the rectangle in Blend and choose "Create Clipping Path" Apply the clipping path to your MediaElement That way you're still using a MediaElement control, but you can "clip" away what ever you want to get the desired rounded effect. This example shows a clipped MediaElement. I know it's not easy to picture the vector path, but if you open it open in Blend you will see a rounded MediaElement.
What's the best way to display a video with rounded corners in Silverlight? The MediaElement doesn't support rounded corners (radiusx, radiusy). Should I use a VideoBrush on a Rectangle with rounded corners?
TITLE: What's the best way to display a video with rounded corners in Silverlight? QUESTION: The MediaElement doesn't support rounded corners (radiusx, radiusy). Should I use a VideoBrush on a Rectangle with rounded corners? ANSWER: Yeah - In a way you're both asking and answering the question yourself... But that is one of the two options I can think of. The reasons that might be a problem is that you lose some of the features/control you get from the MediaElement control. Another option is to do this: Add your MediaElement to your page. Draw a Rectangle on top of it and set wanted corner radius Right click the rectangle in Blend and choose "Create Clipping Path" Apply the clipping path to your MediaElement That way you're still using a MediaElement control, but you can "clip" away what ever you want to get the desired rounded effect. This example shows a clipped MediaElement. I know it's not easy to picture the vector path, but if you open it open in Blend you will see a rounded MediaElement.
[ "silverlight" ]
4
2
1,253
4
0
2008-08-27T23:48:36.837000
2008-08-28T01:09:58.077000
31,366
31,725
Find and Replace with Unique
I am performing a find and replace on the line feed character ( ) and replacing it with the paragraph close and paragraph open tags using the following code: This almost works perfectly, except that I really need it to de-dup the line feeds as the paragraphs tend to be separated by 2 or more resulting in. Is it possible to get it so that it will only ever replace this once per paragraph?
disable-output-escaping isn't evil in itself, but there are only few cases where you should use it and this isn't one of them. In XSLT you work with trees, not markup string. Here's an XSTL 1.0 solution:
Find and Replace with Unique I am performing a find and replace on the line feed character ( ) and replacing it with the paragraph close and paragraph open tags using the following code: This almost works perfectly, except that I really need it to de-dup the line feeds as the paragraphs tend to be separated by 2 or more resulting in. Is it possible to get it so that it will only ever replace this once per paragraph?
TITLE: Find and Replace with Unique QUESTION: I am performing a find and replace on the line feed character ( ) and replacing it with the paragraph close and paragraph open tags using the following code: This almost works perfectly, except that I really need it to de-dup the line feeds as the paragraphs tend to be separated by 2 or more resulting in. Is it possible to get it so that it will only ever replace this once per paragraph? ANSWER: disable-output-escaping isn't evil in itself, but there are only few cases where you should use it and this isn't one of them. In XSLT you work with trees, not markup string. Here's an XSTL 1.0 solution:
[ "xml", "xslt" ]
4
5
12,205
3
0
2008-08-27T23:55:28.600000
2008-08-28T06:38:45.697000
31,380
32,509
Is there a reason to use BufferedReader over InputStreamReader when reading all characters?
I currently use the following function to do a simple HTTP GET. public static String download(String url) throws java.io.IOException { java.io.InputStream s = null; java.io.InputStreamReader r = null; //java.io.BufferedReader b = null; StringBuilder content = new StringBuilder(); try { s = (java.io.InputStream)new URL(url).getContent(); r = new java.io.InputStreamReader(s); //b = new java.io.BufferedReader(r); char[] buffer = new char[4*1024]; int n = 0; while (n >= 0) { n = r.read(buffer, 0, buffer.length); if (n > 0) { content.append(buffer, 0, n); } } } finally { //if (b!= null) b.close(); if (r!= null) r.close(); if (s!= null) s.close(); } return content.toString(); } I see no reason to use the BufferedReader since I am just going to download everything in sequence. Am I right in thinking there is no use for the BufferedReader in this case?
In this case, I would do as you are doing (use a byte array for buffering and not one of the stream buffers). There are exceptions, though. One place you see buffers (output this time) is in the servlet API. Data isn't written to the underlying stream until flush() is called, allowing you to buffer output but then dump the buffer if an error occurs and write an error page instead. You might buffer input if you needed to reset the stream for rereading using mark(int) and reset(). For example, maybe you'd inspect the file header before deciding on which content handler to pass the stream to. Unrelated, but I think you should rewrite your stream handling. This pattern works best to avoid resource leaks: InputStream stream = new FileInputStream("in"); try { //no operations between open stream and try block //work } finally { //do nothing but close this one stream in the finally stream.close(); } If you are opening multiple streams, nest try/finally blocks. Another thing your code is doing is making the assumption that the returned content is encoded in your VM's default character set (though that might be adequate, depending on the use case).
Is there a reason to use BufferedReader over InputStreamReader when reading all characters? I currently use the following function to do a simple HTTP GET. public static String download(String url) throws java.io.IOException { java.io.InputStream s = null; java.io.InputStreamReader r = null; //java.io.BufferedReader b = null; StringBuilder content = new StringBuilder(); try { s = (java.io.InputStream)new URL(url).getContent(); r = new java.io.InputStreamReader(s); //b = new java.io.BufferedReader(r); char[] buffer = new char[4*1024]; int n = 0; while (n >= 0) { n = r.read(buffer, 0, buffer.length); if (n > 0) { content.append(buffer, 0, n); } } } finally { //if (b!= null) b.close(); if (r!= null) r.close(); if (s!= null) s.close(); } return content.toString(); } I see no reason to use the BufferedReader since I am just going to download everything in sequence. Am I right in thinking there is no use for the BufferedReader in this case?
TITLE: Is there a reason to use BufferedReader over InputStreamReader when reading all characters? QUESTION: I currently use the following function to do a simple HTTP GET. public static String download(String url) throws java.io.IOException { java.io.InputStream s = null; java.io.InputStreamReader r = null; //java.io.BufferedReader b = null; StringBuilder content = new StringBuilder(); try { s = (java.io.InputStream)new URL(url).getContent(); r = new java.io.InputStreamReader(s); //b = new java.io.BufferedReader(r); char[] buffer = new char[4*1024]; int n = 0; while (n >= 0) { n = r.read(buffer, 0, buffer.length); if (n > 0) { content.append(buffer, 0, n); } } } finally { //if (b!= null) b.close(); if (r!= null) r.close(); if (s!= null) s.close(); } return content.toString(); } I see no reason to use the BufferedReader since I am just going to download everything in sequence. Am I right in thinking there is no use for the BufferedReader in this case? ANSWER: In this case, I would do as you are doing (use a byte array for buffering and not one of the stream buffers). There are exceptions, though. One place you see buffers (output this time) is in the servlet API. Data isn't written to the underlying stream until flush() is called, allowing you to buffer output but then dump the buffer if an error occurs and write an error page instead. You might buffer input if you needed to reset the stream for rereading using mark(int) and reset(). For example, maybe you'd inspect the file header before deciding on which content handler to pass the stream to. Unrelated, but I think you should rewrite your stream handling. This pattern works best to avoid resource leaks: InputStream stream = new FileInputStream("in"); try { //no operations between open stream and try block //work } finally { //do nothing but close this one stream in the finally stream.close(); } If you are opening multiple streams, nest try/finally blocks. Another thing your code is doing is making the assumption that the returned content is encoded in your VM's default character set (though that might be adequate, depending on the use case).
[ "java", "performance", "http", "io", "buffer" ]
5
4
16,012
4
0
2008-08-28T00:07:06.980000
2008-08-28T15:03:31.053000
31,394
31,401
Java: Programatic Way to Determine Current Windows User
I see many similar questions, however I want to find the Username of the currently logged in user using Java. Its probably something like: System.getProperty(current.user); But, I'm not quite sure.
You're actually really close. This is what you're looking for: System.getProperty("user.name")
Java: Programatic Way to Determine Current Windows User I see many similar questions, however I want to find the Username of the currently logged in user using Java. Its probably something like: System.getProperty(current.user); But, I'm not quite sure.
TITLE: Java: Programatic Way to Determine Current Windows User QUESTION: I see many similar questions, however I want to find the Username of the currently logged in user using Java. Its probably something like: System.getProperty(current.user); But, I'm not quite sure. ANSWER: You're actually really close. This is what you're looking for: System.getProperty("user.name")
[ "java", "windows" ]
11
32
14,900
3
0
2008-08-28T00:17:21.730000
2008-08-28T00:20:44.013000
31,408
31,452
Where can I find a good ASP.NET MVC sample?
I have been using Castle MonoRail for the last two years, but in a new job I am going to be the one to bring in ASP.NET MVC with me. I understand the basics of views, actions and the like. I just need a good sample for someone with MVC experience. Any good links besides Scott's Northwind traders sample?
CodeCampServer - Built with ASP.NET MVC, pretty light and small project. No cruft at all. @lomaxx - Just FYI, most of what Troy Goode wrote is now part of ASP.NET MVC as of Preview 4.
Where can I find a good ASP.NET MVC sample? I have been using Castle MonoRail for the last two years, but in a new job I am going to be the one to bring in ASP.NET MVC with me. I understand the basics of views, actions and the like. I just need a good sample for someone with MVC experience. Any good links besides Scott's Northwind traders sample?
TITLE: Where can I find a good ASP.NET MVC sample? QUESTION: I have been using Castle MonoRail for the last two years, but in a new job I am going to be the one to bring in ASP.NET MVC with me. I understand the basics of views, actions and the like. I just need a good sample for someone with MVC experience. Any good links besides Scott's Northwind traders sample? ANSWER: CodeCampServer - Built with ASP.NET MVC, pretty light and small project. No cruft at all. @lomaxx - Just FYI, most of what Troy Goode wrote is now part of ASP.NET MVC as of Preview 4.
[ "c#", "asp.net", "asp.net-mvc" ]
11
11
3,090
8
0
2008-08-28T00:23:38.937000
2008-08-28T01:07:02.703000
31,410
31,427
Visual Studio 2008 debugging issue
I'm working in VS 2008 and have three projects in one solution. I'm debugging by attaching to a.net process invoked by a third party app (SalesLogix, a CRM app). Once it has attached to the process and I attempt to set a breakpoint in one of the projects, it doesn't set a breakpoint in that file. It actually switches the current tab to another file in another project and sets a breakpoint in that document. If the file isn't open, it even goes so far as to open it for me. I can't explain this. I've got no clue. Anyone seen such odd behavior? I wouldn't believe it if I wasn't seeing it myself. A little more info: if I set a breakpoint before attaching, it shows the "red dot" and says no symbols loaded...no problem...I expect that. When I attach and invoke my.net code from SalesLogix and switch back to VS, my breakpoint is completely gone (not even a warning that the source doesn't match the debug file). When I attempt to manually load the debug file, then I get a message that the symbol file does not match the module. The.pdb and the.dll are timestamped the same, so I'm stumped. Anyone have any ideas? Thx, Jeff
I saw this functionality in older versions of VS.Net (2003 I think). It may still exist in current versions, but I haven't encountered it. Seems that files with the same name, even in different directories confuse VS.Net, and it ends up setting a break point in a file with the same name. May only happen if the classes in the file both have the same name also. So much for namespaces I guess. You also may want to check your build configuration to make sure that all the projects are in fact building in debug mode. I know I've been caught a couple times when the configuration got changed somehow for the solution, and some projects weren't compiling in debug mode.
Visual Studio 2008 debugging issue I'm working in VS 2008 and have three projects in one solution. I'm debugging by attaching to a.net process invoked by a third party app (SalesLogix, a CRM app). Once it has attached to the process and I attempt to set a breakpoint in one of the projects, it doesn't set a breakpoint in that file. It actually switches the current tab to another file in another project and sets a breakpoint in that document. If the file isn't open, it even goes so far as to open it for me. I can't explain this. I've got no clue. Anyone seen such odd behavior? I wouldn't believe it if I wasn't seeing it myself. A little more info: if I set a breakpoint before attaching, it shows the "red dot" and says no symbols loaded...no problem...I expect that. When I attach and invoke my.net code from SalesLogix and switch back to VS, my breakpoint is completely gone (not even a warning that the source doesn't match the debug file). When I attempt to manually load the debug file, then I get a message that the symbol file does not match the module. The.pdb and the.dll are timestamped the same, so I'm stumped. Anyone have any ideas? Thx, Jeff
TITLE: Visual Studio 2008 debugging issue QUESTION: I'm working in VS 2008 and have three projects in one solution. I'm debugging by attaching to a.net process invoked by a third party app (SalesLogix, a CRM app). Once it has attached to the process and I attempt to set a breakpoint in one of the projects, it doesn't set a breakpoint in that file. It actually switches the current tab to another file in another project and sets a breakpoint in that document. If the file isn't open, it even goes so far as to open it for me. I can't explain this. I've got no clue. Anyone seen such odd behavior? I wouldn't believe it if I wasn't seeing it myself. A little more info: if I set a breakpoint before attaching, it shows the "red dot" and says no symbols loaded...no problem...I expect that. When I attach and invoke my.net code from SalesLogix and switch back to VS, my breakpoint is completely gone (not even a warning that the source doesn't match the debug file). When I attempt to manually load the debug file, then I get a message that the symbol file does not match the module. The.pdb and the.dll are timestamped the same, so I'm stumped. Anyone have any ideas? Thx, Jeff ANSWER: I saw this functionality in older versions of VS.Net (2003 I think). It may still exist in current versions, but I haven't encountered it. Seems that files with the same name, even in different directories confuse VS.Net, and it ends up setting a break point in a file with the same name. May only happen if the classes in the file both have the same name also. So much for namespaces I guess. You also may want to check your build configuration to make sure that all the projects are in fact building in debug mode. I know I've been caught a couple times when the configuration got changed somehow for the solution, and some projects weren't compiling in debug mode.
[ "c#", "visual-studio-2008", "debugging" ]
4
4
1,413
2
0
2008-08-28T00:25:47.870000
2008-08-28T00:34:39.363000
31,412
31,421
Proprietary plug-ins for GPL programs: what about interpreted languages?
I am developing a GPL-licensed application in Python and need to know if the GPL allows my program to use proprietary plug-ins. This is what the FSF has to say on the issue: If a program released under the GPL uses plug-ins, what are the requirements for the licenses of a plug-in? It depends on how the program invokes its plug-ins. If the program uses fork and exec to invoke plug-ins, then the plug-ins are separate programs, so the license for the main program makes no requirements for them. If the program dynamically links plug-ins, and they make function calls to each other and share data structures, we believe they form a single program, which must be treated as an extension of both the main program and the plug-ins. This means the plug-ins must be released under the GPL or a GPL-compatible free software license, and that the terms of the GPL must be followed when those plug-ins are distributed. If the program dynamically links plug-ins, but the communication between them is limited to invoking the ‘main’ function of the plug-in with some options and waiting for it to return, that is a borderline case. The distinction between fork/exec and dynamic linking, besides being kind of artificial, doesn't carry over to interpreted languages: what about a Python/Perl/Ruby plugin, which gets loaded via import or execfile? (edit: I understand why the distinction between fork/exec and dynamic linking, but it seems like someone who wanted to comply with the GPL but go against the "spirit" --I don't-- could just use fork/exec and interprocess communication to do pretty much anything). The best solution would be to add an exception to my license to explicitly allow the use of proprietary plugins, but I am unable to do so since I'm using Qt / PyQt which is GPL.
he distinction between fork/exec and dynamic linking, besides being kind of artificial, I don't think its artificial at all. Basically they are just making the division based upon the level of integration. If the program has "plugins" which are essentially fire and forget with no API level integration, then the resulting work is unlikely to be considered a derived work. Generally speaking a plugin which is merely forked/exec'ed would fit this criteria, though there may be cases where it does not. This case especially applies if the "plugin" code would work independently of your code as well. If, on the other hand, the code is deeply dependent upon the GPL'ed work, such as extensively calling APIs, or tight data structure integration, then things are more likely to be considered a derived work. Ie, the "plugin" cannot exist on its own without the GPL product, and a product with this plugin installed is essentially a derived work of the GPLed product. So to make it a little more clear, the same principles could apply to your interpreted code. If the interpreted code relies heavily upon your APIs (or vice-versa) then it would be considered a derived work. If it is just a script that executes on its own with extremely little integration, then it may not. Does that make more sense?
Proprietary plug-ins for GPL programs: what about interpreted languages? I am developing a GPL-licensed application in Python and need to know if the GPL allows my program to use proprietary plug-ins. This is what the FSF has to say on the issue: If a program released under the GPL uses plug-ins, what are the requirements for the licenses of a plug-in? It depends on how the program invokes its plug-ins. If the program uses fork and exec to invoke plug-ins, then the plug-ins are separate programs, so the license for the main program makes no requirements for them. If the program dynamically links plug-ins, and they make function calls to each other and share data structures, we believe they form a single program, which must be treated as an extension of both the main program and the plug-ins. This means the plug-ins must be released under the GPL or a GPL-compatible free software license, and that the terms of the GPL must be followed when those plug-ins are distributed. If the program dynamically links plug-ins, but the communication between them is limited to invoking the ‘main’ function of the plug-in with some options and waiting for it to return, that is a borderline case. The distinction between fork/exec and dynamic linking, besides being kind of artificial, doesn't carry over to interpreted languages: what about a Python/Perl/Ruby plugin, which gets loaded via import or execfile? (edit: I understand why the distinction between fork/exec and dynamic linking, but it seems like someone who wanted to comply with the GPL but go against the "spirit" --I don't-- could just use fork/exec and interprocess communication to do pretty much anything). The best solution would be to add an exception to my license to explicitly allow the use of proprietary plugins, but I am unable to do so since I'm using Qt / PyQt which is GPL.
TITLE: Proprietary plug-ins for GPL programs: what about interpreted languages? QUESTION: I am developing a GPL-licensed application in Python and need to know if the GPL allows my program to use proprietary plug-ins. This is what the FSF has to say on the issue: If a program released under the GPL uses plug-ins, what are the requirements for the licenses of a plug-in? It depends on how the program invokes its plug-ins. If the program uses fork and exec to invoke plug-ins, then the plug-ins are separate programs, so the license for the main program makes no requirements for them. If the program dynamically links plug-ins, and they make function calls to each other and share data structures, we believe they form a single program, which must be treated as an extension of both the main program and the plug-ins. This means the plug-ins must be released under the GPL or a GPL-compatible free software license, and that the terms of the GPL must be followed when those plug-ins are distributed. If the program dynamically links plug-ins, but the communication between them is limited to invoking the ‘main’ function of the plug-in with some options and waiting for it to return, that is a borderline case. The distinction between fork/exec and dynamic linking, besides being kind of artificial, doesn't carry over to interpreted languages: what about a Python/Perl/Ruby plugin, which gets loaded via import or execfile? (edit: I understand why the distinction between fork/exec and dynamic linking, but it seems like someone who wanted to comply with the GPL but go against the "spirit" --I don't-- could just use fork/exec and interprocess communication to do pretty much anything). The best solution would be to add an exception to my license to explicitly allow the use of proprietary plugins, but I am unable to do so since I'm using Qt / PyQt which is GPL. ANSWER: he distinction between fork/exec and dynamic linking, besides being kind of artificial, I don't think its artificial at all. Basically they are just making the division based upon the level of integration. If the program has "plugins" which are essentially fire and forget with no API level integration, then the resulting work is unlikely to be considered a derived work. Generally speaking a plugin which is merely forked/exec'ed would fit this criteria, though there may be cases where it does not. This case especially applies if the "plugin" code would work independently of your code as well. If, on the other hand, the code is deeply dependent upon the GPL'ed work, such as extensively calling APIs, or tight data structure integration, then things are more likely to be considered a derived work. Ie, the "plugin" cannot exist on its own without the GPL product, and a product with this plugin installed is essentially a derived work of the GPLed product. So to make it a little more clear, the same principles could apply to your interpreted code. If the interpreted code relies heavily upon your APIs (or vice-versa) then it would be considered a derived work. If it is just a script that executes on its own with extremely little integration, then it may not. Does that make more sense?
[ "python", "plugins", "open-source", "licensing", "interpreted-language" ]
9
7
2,538
3
0
2008-08-28T00:26:35.390000
2008-08-28T00:33:04.157000
31,415
31,432
Quick way to find a value in HTML (Java)
Using regular expressions, what is the simplest way to fetch a websites HTML and find the value inside this tag (or any attribute's value for that matter): [snip] [snip]
Depends on how sophisticated of an Http request you need to build (authentication, etc). Here's one simple way I've seen used in the past. StringBuilder html = new StringBuilder(); java.net.URL url = new URL("http://www.google.com/"); BufferedReader input = null; try { input new BufferedReader( new InputStreamReader(url.openStream())); String htmlLine; while ((htmlLine=input.readLine())!=null) { html.appendLine(htmlLine); } } finally { input.close(); } Pattern exp = Pattern.compile( " "); Matcher matcher = exp.matcher(html.toString()); if(matcher.find()) { System.out.println("Generator: "+matcher.group(1)); } Probably plenty of typos here to be found when compiled. (hope this wasn't homework)
Quick way to find a value in HTML (Java) Using regular expressions, what is the simplest way to fetch a websites HTML and find the value inside this tag (or any attribute's value for that matter): [snip] [snip]
TITLE: Quick way to find a value in HTML (Java) QUESTION: Using regular expressions, what is the simplest way to fetch a websites HTML and find the value inside this tag (or any attribute's value for that matter): [snip] [snip] ANSWER: Depends on how sophisticated of an Http request you need to build (authentication, etc). Here's one simple way I've seen used in the past. StringBuilder html = new StringBuilder(); java.net.URL url = new URL("http://www.google.com/"); BufferedReader input = null; try { input new BufferedReader( new InputStreamReader(url.openStream())); String htmlLine; while ((htmlLine=input.readLine())!=null) { html.appendLine(htmlLine); } } finally { input.close(); } Pattern exp = Pattern.compile( " "); Matcher matcher = exp.matcher(html.toString()); if(matcher.find()) { System.out.println("Generator: "+matcher.group(1)); } Probably plenty of typos here to be found when compiled. (hope this wasn't homework)
[ "java", "html", "regex" ]
0
10
12,154
7
0
2008-08-28T00:28:36.553000
2008-08-28T00:38:16.360000
31,424
87,823
NHIbernate: Difference between Restriction.In and Restriction.InG
When creating a criteria in NHibernate I can use Restriction.In() or Restriction.InG() What is the difference between them?
InG is the generic equivalent of In (for collections) The signatures of the methods are as follows (only the ICollection In overload is shown): In(string propertyName, ICollection values) vs. InG (string propertyName, ICollection values) Looking at NHibernate's source code (trunk) it seems that they both copy the collection to an object array and use that going forward, so I don't think there is a performance difference between them. I personally just use the In one most of the time - its easier to read.
NHIbernate: Difference between Restriction.In and Restriction.InG When creating a criteria in NHibernate I can use Restriction.In() or Restriction.InG() What is the difference between them?
TITLE: NHIbernate: Difference between Restriction.In and Restriction.InG QUESTION: When creating a criteria in NHibernate I can use Restriction.In() or Restriction.InG() What is the difference between them? ANSWER: InG is the generic equivalent of In (for collections) The signatures of the methods are as follows (only the ICollection In overload is shown): In(string propertyName, ICollection values) vs. InG (string propertyName, ICollection values) Looking at NHibernate's source code (trunk) it seems that they both copy the collection to an object array and use that going forward, so I don't think there is a performance difference between them. I personally just use the In one most of the time - its easier to read.
[ "c#", "nhibernate", "orm" ]
4
11
6,309
2
0
2008-08-28T00:33:45.840000
2008-09-17T21:24:53.310000
31,446
33,041
Detach an entity from JPA/EJB3 persistence context
What would be the easiest way to detach a specific JPA Entity Bean that was acquired through an EntityManager. Alternatively, could I have a query return detached objects in the first place so they would essentially act as 'read only'? The reason why I want to do this is becuase I want to modify the data within the bean - with in my application only, but not ever have it persisted to the database. In my program, I eventually have to call flush() on the EntityManager, which would persist all changes from attached entities to the underyling database, but I want to exclude specific objects.
Unfortunately, there's no way to disconnect one object from the entity manager in the current JPA implementation, AFAIR. EntityManager.clear() will disconnect all the JPA objects, so that might not be an appropriate solution in all the cases, if you have other objects you do plan to keep connected. So your best bet would be to clone the objects and pass the clones to the code that changes the objects. Since primitive and immutable object fields are taken care of by the default cloning mechanism in a proper way, you won't have to write a lot of plumbing code (apart from deep cloning any aggregated structures you might have).
Detach an entity from JPA/EJB3 persistence context What would be the easiest way to detach a specific JPA Entity Bean that was acquired through an EntityManager. Alternatively, could I have a query return detached objects in the first place so they would essentially act as 'read only'? The reason why I want to do this is becuase I want to modify the data within the bean - with in my application only, but not ever have it persisted to the database. In my program, I eventually have to call flush() on the EntityManager, which would persist all changes from attached entities to the underyling database, but I want to exclude specific objects.
TITLE: Detach an entity from JPA/EJB3 persistence context QUESTION: What would be the easiest way to detach a specific JPA Entity Bean that was acquired through an EntityManager. Alternatively, could I have a query return detached objects in the first place so they would essentially act as 'read only'? The reason why I want to do this is becuase I want to modify the data within the bean - with in my application only, but not ever have it persisted to the database. In my program, I eventually have to call flush() on the EntityManager, which would persist all changes from attached entities to the underyling database, but I want to exclude specific objects. ANSWER: Unfortunately, there's no way to disconnect one object from the entity manager in the current JPA implementation, AFAIR. EntityManager.clear() will disconnect all the JPA objects, so that might not be an appropriate solution in all the cases, if you have other objects you do plan to keep connected. So your best bet would be to clone the objects and pass the clones to the code that changes the objects. Since primitive and immutable object fields are taken care of by the default cloning mechanism in a proper way, you won't have to write a lot of plumbing code (apart from deep cloning any aggregated structures you might have).
[ "java", "orm", "jpa" ]
60
17
80,160
15
0
2008-08-28T00:53:21.860000
2008-08-28T18:39:55.213000
31,462
31,463
How to fetch HTML in Java
Without the use of any external library, what is the simplest way to fetch a website's HTML content into a String?
I'm currently using this: String content = null; URLConnection connection = null; try { connection = new URL("http://www.google.com").openConnection(); Scanner scanner = new Scanner(connection.getInputStream()); scanner.useDelimiter("\\Z"); content = scanner.next(); scanner.close(); }catch ( Exception ex ) { ex.printStackTrace(); } System.out.println(content); But not sure if there's a better way.
How to fetch HTML in Java Without the use of any external library, what is the simplest way to fetch a website's HTML content into a String?
TITLE: How to fetch HTML in Java QUESTION: Without the use of any external library, what is the simplest way to fetch a website's HTML content into a String? ANSWER: I'm currently using this: String content = null; URLConnection connection = null; try { connection = new URL("http://www.google.com").openConnection(); Scanner scanner = new Scanner(connection.getInputStream()); scanner.useDelimiter("\\Z"); content = scanner.next(); scanner.close(); }catch ( Exception ex ) { ex.printStackTrace(); } System.out.println(content); But not sure if there's a better way.
[ "java", "html", "screen-scraping" ]
35
47
76,710
6
0
2008-08-28T01:20:18.100000
2008-08-28T01:21:00.797000
31,465
31,486
Stackoverflow Style Notifications in asp.net Ajax
When you get a badge or aren't logged in to stack overflow there's a groovy little notification bar at the top of the page that lets you know there's something going on. I know the SOflow team use JQuery, but I was wondering if anyone knew of an implementation of the same style of notification system in asp.net AJAX. On a side note, what's the "official" name for this style of notification bar?
I like it to. div tag with a fade. http://www.asp.net/AJAX/AjaxControlToolkit/Samples/Walkthrough/UsingAnimations.aspx
Stackoverflow Style Notifications in asp.net Ajax When you get a badge or aren't logged in to stack overflow there's a groovy little notification bar at the top of the page that lets you know there's something going on. I know the SOflow team use JQuery, but I was wondering if anyone knew of an implementation of the same style of notification system in asp.net AJAX. On a side note, what's the "official" name for this style of notification bar?
TITLE: Stackoverflow Style Notifications in asp.net Ajax QUESTION: When you get a badge or aren't logged in to stack overflow there's a groovy little notification bar at the top of the page that lets you know there's something going on. I know the SOflow team use JQuery, but I was wondering if anyone knew of an implementation of the same style of notification system in asp.net AJAX. On a side note, what's the "official" name for this style of notification bar? ANSWER: I like it to. div tag with a fade. http://www.asp.net/AJAX/AjaxControlToolkit/Samples/Walkthrough/UsingAnimations.aspx
[ "asp.net", "asp.net-ajax", "notification-bar" ]
11
8
4,331
2
0
2008-08-28T01:24:10.697000
2008-08-28T01:42:26.813000
31,466
31,470
Does Amazon S3 download fail sometimes?
We just added an autoupdater in our software and got some bug report saying that the autoupdate wouldn't complete properly because the downloaded file's sha1 checksum wasn't matching. We're hosted on Amazon S3... That's either something wrong with my code or something wrong with S3. I reread my code for suspicious stuff and wrote a simple script downloading and checking the checksum of the downloaded file, and indeed got a few errors once in while (1 out of 40 yesterday). Today it seems okay. Did you experience that kind of problem? Is there some kind of workaround? extra info: test were ran in Japan.
Other than the downtime a few weeks ago. None that I heard of. They did a good job considering the one time it was down was because of an obscure server error that cascaded throughout the cloud. They was very open about it and resolve it as soon as they found out.(it happened during a weekend, iirc) So they are pretty reliable. My advice is double check your code. And bring it up to amazon support if it is still a problem.
Does Amazon S3 download fail sometimes? We just added an autoupdater in our software and got some bug report saying that the autoupdate wouldn't complete properly because the downloaded file's sha1 checksum wasn't matching. We're hosted on Amazon S3... That's either something wrong with my code or something wrong with S3. I reread my code for suspicious stuff and wrote a simple script downloading and checking the checksum of the downloaded file, and indeed got a few errors once in while (1 out of 40 yesterday). Today it seems okay. Did you experience that kind of problem? Is there some kind of workaround? extra info: test were ran in Japan.
TITLE: Does Amazon S3 download fail sometimes? QUESTION: We just added an autoupdater in our software and got some bug report saying that the autoupdate wouldn't complete properly because the downloaded file's sha1 checksum wasn't matching. We're hosted on Amazon S3... That's either something wrong with my code or something wrong with S3. I reread my code for suspicious stuff and wrote a simple script downloading and checking the checksum of the downloaded file, and indeed got a few errors once in while (1 out of 40 yesterday). Today it seems okay. Did you experience that kind of problem? Is there some kind of workaround? extra info: test were ran in Japan. ANSWER: Other than the downtime a few weeks ago. None that I heard of. They did a good job considering the one time it was down was because of an obscure server error that cascaded throughout the cloud. They was very open about it and resolve it as soon as they found out.(it happened during a weekend, iirc) So they are pretty reliable. My advice is double check your code. And bring it up to amazon support if it is still a problem.
[ "download", "amazon-s3" ]
6
4
10,822
7
0
2008-08-28T01:25:52.313000
2008-08-28T01:29:30.650000
31,480
31,485
How stable is WPF?
How stable is WPF not in terms of stability of a WPF program, but in terms of the 'stability' of the API itself. Let me explain: Microsoft is notorious for changing its whole methodology around with new technology. Like with the move from silverlight 1 to silverlight 2. With WPF, I know that MS changed a bunch of stuff with the release of the.NET service pack. I don't know how much they changed things around. So the bottom line is, in your opinion are they going to revamp the system again with the next release or do you think that it is stable enough now that they won't change the bulk of the system. I hate to have to unlearn stuff with every release. I hope that the question wasn't too long winded.
MS do have a history of "fire and movement" with regards to introducing new technology into their development stack, but they also have a strong history of maintaining support for the older stuff, and backwards-compatibility. WPF seems to be getting stuff added to it with each new release of the framework but the things you learn aren't being superceded or invalidated. The only breaking change I've seen in my own WPF applications with a new release of the framework was one recently in 3.5 SP1, and that was because we were unknowingly relying on a bug to get a certain behaviour from our code. We adjusted the XAML to be more correct and it started working fine. So yeah, I think WPF is pretty "stable" as a client-side development technology.
How stable is WPF? How stable is WPF not in terms of stability of a WPF program, but in terms of the 'stability' of the API itself. Let me explain: Microsoft is notorious for changing its whole methodology around with new technology. Like with the move from silverlight 1 to silverlight 2. With WPF, I know that MS changed a bunch of stuff with the release of the.NET service pack. I don't know how much they changed things around. So the bottom line is, in your opinion are they going to revamp the system again with the next release or do you think that it is stable enough now that they won't change the bulk of the system. I hate to have to unlearn stuff with every release. I hope that the question wasn't too long winded.
TITLE: How stable is WPF? QUESTION: How stable is WPF not in terms of stability of a WPF program, but in terms of the 'stability' of the API itself. Let me explain: Microsoft is notorious for changing its whole methodology around with new technology. Like with the move from silverlight 1 to silverlight 2. With WPF, I know that MS changed a bunch of stuff with the release of the.NET service pack. I don't know how much they changed things around. So the bottom line is, in your opinion are they going to revamp the system again with the next release or do you think that it is stable enough now that they won't change the bulk of the system. I hate to have to unlearn stuff with every release. I hope that the question wasn't too long winded. ANSWER: MS do have a history of "fire and movement" with regards to introducing new technology into their development stack, but they also have a strong history of maintaining support for the older stuff, and backwards-compatibility. WPF seems to be getting stuff added to it with each new release of the framework but the things you learn aren't being superceded or invalidated. The only breaking change I've seen in my own WPF applications with a new release of the framework was one recently in 3.5 SP1, and that was because we were unknowingly relying on a bug to get a certain behaviour from our code. We adjusted the XAML to be more correct and it started working fine. So yeah, I think WPF is pretty "stable" as a client-side development technology.
[ ".net", "wpf" ]
6
12
599
3
0
2008-08-28T01:38:47.073000
2008-08-28T01:42:15.457000
31,496
31,505
How do I check the active solution configuration Visual Studio built with at runtime?
I would like to enable/disable some code based on a custom solution configuration I added in Visual Studio. How do I check this value at runtime?
You can use precompiler directives within Visual Studio. The #if directive will allow you to determine if you are going to include code or not based on your custom solution configuration.
How do I check the active solution configuration Visual Studio built with at runtime? I would like to enable/disable some code based on a custom solution configuration I added in Visual Studio. How do I check this value at runtime?
TITLE: How do I check the active solution configuration Visual Studio built with at runtime? QUESTION: I would like to enable/disable some code based on a custom solution configuration I added in Visual Studio. How do I check this value at runtime? ANSWER: You can use precompiler directives within Visual Studio. The #if directive will allow you to determine if you are going to include code or not based on your custom solution configuration.
[ "visual-studio" ]
12
9
11,536
4
0
2008-08-28T01:56:34.377000
2008-08-28T02:02:07.717000
31,497
31,522
Where do I use delegates?
What are some real world places that call for delegates? I'm curious what situations or patterns are present where this method is the best solution. No code required.
A delegate is a named type that defines a particular kind of method. Just as a class definition lays out all the members for the given kind of object it defines, the delegate lays out the method signature for the kind of method it defines. Based on this statement, a delegate is a function pointer and it defines what that function looks like. A great example for a real world application of a delegate is the Predicate. In the example from the link, you will notice that Array.Find takes the array to search and then a predicate to handle the criteria of what to find. In this case it passes a method ProductGT10 which matches the Predicate signature.
Where do I use delegates? What are some real world places that call for delegates? I'm curious what situations or patterns are present where this method is the best solution. No code required.
TITLE: Where do I use delegates? QUESTION: What are some real world places that call for delegates? I'm curious what situations or patterns are present where this method is the best solution. No code required. ANSWER: A delegate is a named type that defines a particular kind of method. Just as a class definition lays out all the members for the given kind of object it defines, the delegate lays out the method signature for the kind of method it defines. Based on this statement, a delegate is a function pointer and it defines what that function looks like. A great example for a real world application of a delegate is the Predicate. In the example from the link, you will notice that Array.Find takes the array to search and then a predicate to handle the criteria of what to find. In this case it passes a method ProductGT10 which matches the Predicate signature.
[ "oop", "design-patterns", "delegates" ]
112
36
49,856
8
0
2008-08-28T01:58:53.810000
2008-08-28T02:12:21.983000
31,498
31,513
Best way to test if a generic type is a string? (C#)
I have a generic class that should allow any type, primitive or otherwise. The only problem with this is using default(T). When you call default on a value type or a string, it initializes it to a reasonable value (such as empty string). When you call default(T) on an object, it returns null. For various reasons we need to ensure that if it is not a primitive type, then we will have a default instance of the type, not null. Here is attempt 1: T createDefault() { if(typeof(T).IsValueType) { return default(T); } else { return Activator.CreateInstance (); } } Problem - string is not a value type, but it does not have a parameterless constructor. So, the current solution is: T createDefault() { if(typeof(T).IsValueType || typeof(T).FullName == "System.String") { return default(T); } else { return Activator.CreateInstance (); } } But this feels like a kludge. Is there a nicer way to handle the string case?
Keep in mind that default(string) is null, not string.Empty. You may want a special case in your code: if (typeof(T) == typeof(String)) return (T)(object)String.Empty;
Best way to test if a generic type is a string? (C#) I have a generic class that should allow any type, primitive or otherwise. The only problem with this is using default(T). When you call default on a value type or a string, it initializes it to a reasonable value (such as empty string). When you call default(T) on an object, it returns null. For various reasons we need to ensure that if it is not a primitive type, then we will have a default instance of the type, not null. Here is attempt 1: T createDefault() { if(typeof(T).IsValueType) { return default(T); } else { return Activator.CreateInstance (); } } Problem - string is not a value type, but it does not have a parameterless constructor. So, the current solution is: T createDefault() { if(typeof(T).IsValueType || typeof(T).FullName == "System.String") { return default(T); } else { return Activator.CreateInstance (); } } But this feels like a kludge. Is there a nicer way to handle the string case?
TITLE: Best way to test if a generic type is a string? (C#) QUESTION: I have a generic class that should allow any type, primitive or otherwise. The only problem with this is using default(T). When you call default on a value type or a string, it initializes it to a reasonable value (such as empty string). When you call default(T) on an object, it returns null. For various reasons we need to ensure that if it is not a primitive type, then we will have a default instance of the type, not null. Here is attempt 1: T createDefault() { if(typeof(T).IsValueType) { return default(T); } else { return Activator.CreateInstance (); } } Problem - string is not a value type, but it does not have a parameterless constructor. So, the current solution is: T createDefault() { if(typeof(T).IsValueType || typeof(T).FullName == "System.String") { return default(T); } else { return Activator.CreateInstance (); } } But this feels like a kludge. Is there a nicer way to handle the string case? ANSWER: Keep in mind that default(string) is null, not string.Empty. You may want a special case in your code: if (typeof(T) == typeof(String)) return (T)(object)String.Empty;
[ "c#", "generics" ]
109
199
105,624
5
0
2008-08-28T02:00:00.920000
2008-08-28T02:08:18.670000
31,500
31,520
Do indexes work with "IN" clause
If I have a query like: Select EmployeeId From Employee Where EmployeeTypeId IN (1,2,3) and I have an index on the EmployeeTypeId field, does SQL server still use that index?
Yeah, that's right. If your Employee table has 10,000 records, and only 5 records have EmployeeTypeId in (1,2,3), then it will most likely use the index to fetch the records. However, if it finds that 9,000 records have the EmployeeTypeId in (1,2,3), then it would most likely just do a table scan to get the corresponding EmployeeId s, as it's faster just to run through the whole table than to go to each branch of the index tree and look at the records individually. SQL Server does a lot of stuff to try and optimize how the queries run. However, sometimes it doesn't get the right answer. If you know that SQL Server isn't using the index, by looking at the execution plan in query analyzer, you can tell the query engine to use a specific index with the following change to your query. SELECT EmployeeId FROM Employee WITH (Index(Index_EmployeeTypeId )) WHERE EmployeeTypeId IN (1,2,3) Assuming the index you have on the EmployeeTypeId field is named Index_EmployeeTypeId.
Do indexes work with "IN" clause If I have a query like: Select EmployeeId From Employee Where EmployeeTypeId IN (1,2,3) and I have an index on the EmployeeTypeId field, does SQL server still use that index?
TITLE: Do indexes work with "IN" clause QUESTION: If I have a query like: Select EmployeeId From Employee Where EmployeeTypeId IN (1,2,3) and I have an index on the EmployeeTypeId field, does SQL server still use that index? ANSWER: Yeah, that's right. If your Employee table has 10,000 records, and only 5 records have EmployeeTypeId in (1,2,3), then it will most likely use the index to fetch the records. However, if it finds that 9,000 records have the EmployeeTypeId in (1,2,3), then it would most likely just do a table scan to get the corresponding EmployeeId s, as it's faster just to run through the whole table than to go to each branch of the index tree and look at the records individually. SQL Server does a lot of stuff to try and optimize how the queries run. However, sometimes it doesn't get the right answer. If you know that SQL Server isn't using the index, by looking at the execution plan in query analyzer, you can tell the query engine to use a specific index with the following change to your query. SELECT EmployeeId FROM Employee WITH (Index(Index_EmployeeTypeId )) WHERE EmployeeTypeId IN (1,2,3) Assuming the index you have on the EmployeeTypeId field is named Index_EmployeeTypeId.
[ "sql", "indexing" ]
69
37
40,589
6
0
2008-08-28T02:00:09.970000
2008-08-28T02:11:32.827000
31,535
31,546
Best way to fetch a varying HTML tag
I'm trying to fetch some HTML from various blogs and have noticed that different providers use the same tag in different ways. For example, here are two major providers that use the meta name generator tag differently: Blogger: (content first, name later and, yes, single quotes!) WordPress: (name first, content later) Is there a way to extract the value of content for all cases (single/double quotes, first/last in the row)? P.S. Although I'm using Java, the answer would probably help more people if it where for regular expressions generally.
The answer is: don't use regular expressions. Seriously. Use a SGML parser, or an XML parser if you happen to know it's valid XML (probably almost never true). You will absolutely screw up and waste tons of time trying to get it right. Just use what's already available.
Best way to fetch a varying HTML tag I'm trying to fetch some HTML from various blogs and have noticed that different providers use the same tag in different ways. For example, here are two major providers that use the meta name generator tag differently: Blogger: (content first, name later and, yes, single quotes!) WordPress: (name first, content later) Is there a way to extract the value of content for all cases (single/double quotes, first/last in the row)? P.S. Although I'm using Java, the answer would probably help more people if it where for regular expressions generally.
TITLE: Best way to fetch a varying HTML tag QUESTION: I'm trying to fetch some HTML from various blogs and have noticed that different providers use the same tag in different ways. For example, here are two major providers that use the meta name generator tag differently: Blogger: (content first, name later and, yes, single quotes!) WordPress: (name first, content later) Is there a way to extract the value of content for all cases (single/double quotes, first/last in the row)? P.S. Although I'm using Java, the answer would probably help more people if it where for regular expressions generally. ANSWER: The answer is: don't use regular expressions. Seriously. Use a SGML parser, or an XML parser if you happen to know it's valid XML (probably almost never true). You will absolutely screw up and waste tons of time trying to get it right. Just use what's already available.
[ "html", "regex", "language-agnostic" ]
5
14
542
8
0
2008-08-28T02:23:12.770000
2008-08-28T02:31:40.643000
31,561
31,603
Keeping CL and Scheme straight in your head
Depending on my mood I seem to waffle back and forth between wanting a Lisp-1 and a Lisp-2. Unfortunately beyond the obvious name space differences, this leaves all kinds of amusing function name/etc problems you run into. Case in point, trying to write some code tonight I tried to do (map #'function listvar) which, of course, doesn't work in CL, at all. Took me a bit to remember I wanted mapcar, not map. Of course it doesn't help when slime/emacs shows map IS defined as something, though obviously not the same function at all. So, pointers on how to minimize this short of picking one or the other and sticking with it?
Map is more general than mapcar, for example you could do the following rather than using mapcar: (map 'list #'function listvar) How do I keep scheme and CL separate in my head? I guess when you know both languages well enough you just know what works in one and not the other. Despite the syntactic similarities they are quite different languages in terms of style.
Keeping CL and Scheme straight in your head Depending on my mood I seem to waffle back and forth between wanting a Lisp-1 and a Lisp-2. Unfortunately beyond the obvious name space differences, this leaves all kinds of amusing function name/etc problems you run into. Case in point, trying to write some code tonight I tried to do (map #'function listvar) which, of course, doesn't work in CL, at all. Took me a bit to remember I wanted mapcar, not map. Of course it doesn't help when slime/emacs shows map IS defined as something, though obviously not the same function at all. So, pointers on how to minimize this short of picking one or the other and sticking with it?
TITLE: Keeping CL and Scheme straight in your head QUESTION: Depending on my mood I seem to waffle back and forth between wanting a Lisp-1 and a Lisp-2. Unfortunately beyond the obvious name space differences, this leaves all kinds of amusing function name/etc problems you run into. Case in point, trying to write some code tonight I tried to do (map #'function listvar) which, of course, doesn't work in CL, at all. Took me a bit to remember I wanted mapcar, not map. Of course it doesn't help when slime/emacs shows map IS defined as something, though obviously not the same function at all. So, pointers on how to minimize this short of picking one or the other and sticking with it? ANSWER: Map is more general than mapcar, for example you could do the following rather than using mapcar: (map 'list #'function listvar) How do I keep scheme and CL separate in my head? I guess when you know both languages well enough you just know what works in one and not the other. Despite the syntactic similarities they are quite different languages in terms of style.
[ "lisp", "scheme", "clisp" ]
2
5
536
4
0
2008-08-28T02:41:53.987000
2008-08-28T03:24:20.437000
31,566
31,573
Query to list all tables that contain a specific column with SQL Server 2005
Question as stated in the title.
http://blog.sqlauthority.com/2008/08/06/sql-server-query-to-find-column-from-all-tables-of-database/ USE AdventureWorks GO SELECT t.name AS table_name,SCHEMA_NAME(schema_id) AS schema_name,c.name AS column_name FROM sys.tables AS t INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID WHERE c.name LIKE '%EmployeeID%' ORDER BY schema_name,table_name;
Query to list all tables that contain a specific column with SQL Server 2005 Question as stated in the title.
TITLE: Query to list all tables that contain a specific column with SQL Server 2005 QUESTION: Question as stated in the title. ANSWER: http://blog.sqlauthority.com/2008/08/06/sql-server-query-to-find-column-from-all-tables-of-database/ USE AdventureWorks GO SELECT t.name AS table_name,SCHEMA_NAME(schema_id) AS schema_name,c.name AS column_name FROM sys.tables AS t INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID WHERE c.name LIKE '%EmployeeID%' ORDER BY schema_name,table_name;
[ "sql-server-2005" ]
4
2
2,663
1
0
2008-08-28T02:50:38.147000
2008-08-28T02:55:57.323000
31,567
31,638
How to properly cast objects created through reflection
I'm trying to wrap my head around reflection, so I decided to add plugin capability to a program that I'm writing. The only way to understand a concept is to get your fingers dirty and write the code, so I went the route of creating a simple interface library consisting of the IPlugin and IHost interfaces, a plugin implementation library of classes that implement IPlugin, and a simple console project that instantiates the IHost implementation class that does simple work with the plugin objects. Using reflection, I wanted to iterate through the types contained inside my plugin implementation dll and create instances of types. I was able to sucessfully instantiate classes with this code, but I could not cast the created object to the interface. I tried this code but I couldn't cast object o as I expected. I stepped through the process with the debugger and the proper constructor was called. Quickwatching object o showed me that it had the fields and properties that I expected to see in the implementation class. loop through assemblies loop through types in assembly // Filter out unwanted types if (!type.IsClass || type.IsNotPublic || type.IsAbstract ) continue; // This successfully created the right object object o = Activator.CreateInstance(type); // This threw an Invalid Cast Exception or returned null for an "as" cast // even though the object implemented IPlugin IPlugin i = (IPlugin) o; I made the code work with this. using System.Runtime.Remoting; ObjectHandle oh = Activator.CreateInstance(assembly.FullName, type.FullName); // This worked as I intended IPlugin i = (IPlugin) oh.Unwrap(); i.DoStuff(); Here are my questions: Activator.CreateInstance(Type t) returns an object, but I couldn't cast the object to an interface that the object implemented. Why? Should I have been using a different overload of CreateInstance()? What are the reflection related tips and tricks? Is there some crucial part of reflection that I'm just not getting?
I'm just guessing here because from your code it's not obvious where do you have definition of IPlugin interface but if you can't cast in your host application then you are probably having IPlugin interface in your host assembly and then at the same time in your plugin assembly. This won't work. The easiest thing is to make this work is to have IPlugin interface marked as public in your host assembly and then have your Plugin assembly reference host application assembly, so both assemblies have access to the very same interface.
How to properly cast objects created through reflection I'm trying to wrap my head around reflection, so I decided to add plugin capability to a program that I'm writing. The only way to understand a concept is to get your fingers dirty and write the code, so I went the route of creating a simple interface library consisting of the IPlugin and IHost interfaces, a plugin implementation library of classes that implement IPlugin, and a simple console project that instantiates the IHost implementation class that does simple work with the plugin objects. Using reflection, I wanted to iterate through the types contained inside my plugin implementation dll and create instances of types. I was able to sucessfully instantiate classes with this code, but I could not cast the created object to the interface. I tried this code but I couldn't cast object o as I expected. I stepped through the process with the debugger and the proper constructor was called. Quickwatching object o showed me that it had the fields and properties that I expected to see in the implementation class. loop through assemblies loop through types in assembly // Filter out unwanted types if (!type.IsClass || type.IsNotPublic || type.IsAbstract ) continue; // This successfully created the right object object o = Activator.CreateInstance(type); // This threw an Invalid Cast Exception or returned null for an "as" cast // even though the object implemented IPlugin IPlugin i = (IPlugin) o; I made the code work with this. using System.Runtime.Remoting; ObjectHandle oh = Activator.CreateInstance(assembly.FullName, type.FullName); // This worked as I intended IPlugin i = (IPlugin) oh.Unwrap(); i.DoStuff(); Here are my questions: Activator.CreateInstance(Type t) returns an object, but I couldn't cast the object to an interface that the object implemented. Why? Should I have been using a different overload of CreateInstance()? What are the reflection related tips and tricks? Is there some crucial part of reflection that I'm just not getting?
TITLE: How to properly cast objects created through reflection QUESTION: I'm trying to wrap my head around reflection, so I decided to add plugin capability to a program that I'm writing. The only way to understand a concept is to get your fingers dirty and write the code, so I went the route of creating a simple interface library consisting of the IPlugin and IHost interfaces, a plugin implementation library of classes that implement IPlugin, and a simple console project that instantiates the IHost implementation class that does simple work with the plugin objects. Using reflection, I wanted to iterate through the types contained inside my plugin implementation dll and create instances of types. I was able to sucessfully instantiate classes with this code, but I could not cast the created object to the interface. I tried this code but I couldn't cast object o as I expected. I stepped through the process with the debugger and the proper constructor was called. Quickwatching object o showed me that it had the fields and properties that I expected to see in the implementation class. loop through assemblies loop through types in assembly // Filter out unwanted types if (!type.IsClass || type.IsNotPublic || type.IsAbstract ) continue; // This successfully created the right object object o = Activator.CreateInstance(type); // This threw an Invalid Cast Exception or returned null for an "as" cast // even though the object implemented IPlugin IPlugin i = (IPlugin) o; I made the code work with this. using System.Runtime.Remoting; ObjectHandle oh = Activator.CreateInstance(assembly.FullName, type.FullName); // This worked as I intended IPlugin i = (IPlugin) oh.Unwrap(); i.DoStuff(); Here are my questions: Activator.CreateInstance(Type t) returns an object, but I couldn't cast the object to an interface that the object implemented. Why? Should I have been using a different overload of CreateInstance()? What are the reflection related tips and tricks? Is there some crucial part of reflection that I'm just not getting? ANSWER: I'm just guessing here because from your code it's not obvious where do you have definition of IPlugin interface but if you can't cast in your host application then you are probably having IPlugin interface in your host assembly and then at the same time in your plugin assembly. This won't work. The easiest thing is to make this work is to have IPlugin interface marked as public in your host assembly and then have your Plugin assembly reference host application assembly, so both assemblies have access to the very same interface.
[ "c#", ".net", "reflection" ]
10
4
12,621
7
0
2008-08-28T02:50:55.510000
2008-08-28T03:46:33.257000
31,572
31,768
Broadcast like UDP with the reliability of TCP
I'm working on a.net solution that is run completely inside a single network. When users make a change to the system, I want to launch an announcement and have everyone else hear it and act accordingly. Is there a way that we can broadcast out messages like this (like UDP will let you do) while keeping guaranteed delivery (like TCP)? This is on a small network (30ish clients), if that would make a difference.
Almost all games have a need for the fast-reacting properties (and to a lesser extent, the connectionless properties) of UDP and the reliability of TCP. What they do is they build their own reliable protocol on top of UDP. This gives them the ability to just burst packets to whereever and optionally make them reliable, as well. The reliable packet system is usually a simple retry-until-acknowledged system simpler than TCP but there are protocols which go way beyond what TCP can offer. Your situation sounds very simple. You'll probably be able to make the cleanest solution yourself - just make every client send back an "I heard you" response and have the server keep trying until it gets it (or gives up). If you want something more, most custom protocol libraries are in C++, so I am not sure how much use they'll be to you. However, my knowledge here is a few years old - perhaps some protocols have been ported over by now. Hmm... RakNet and enet are two C/C++ libraries that come to mind.
Broadcast like UDP with the reliability of TCP I'm working on a.net solution that is run completely inside a single network. When users make a change to the system, I want to launch an announcement and have everyone else hear it and act accordingly. Is there a way that we can broadcast out messages like this (like UDP will let you do) while keeping guaranteed delivery (like TCP)? This is on a small network (30ish clients), if that would make a difference.
TITLE: Broadcast like UDP with the reliability of TCP QUESTION: I'm working on a.net solution that is run completely inside a single network. When users make a change to the system, I want to launch an announcement and have everyone else hear it and act accordingly. Is there a way that we can broadcast out messages like this (like UDP will let you do) while keeping guaranteed delivery (like TCP)? This is on a small network (30ish clients), if that would make a difference. ANSWER: Almost all games have a need for the fast-reacting properties (and to a lesser extent, the connectionless properties) of UDP and the reliability of TCP. What they do is they build their own reliable protocol on top of UDP. This gives them the ability to just burst packets to whereever and optionally make them reliable, as well. The reliable packet system is usually a simple retry-until-acknowledged system simpler than TCP but there are protocols which go way beyond what TCP can offer. Your situation sounds very simple. You'll probably be able to make the cleanest solution yourself - just make every client send back an "I heard you" response and have the server keep trying until it gets it (or gives up). If you want something more, most custom protocol libraries are in C++, so I am not sure how much use they'll be to you. However, my knowledge here is a few years old - perhaps some protocols have been ported over by now. Hmm... RakNet and enet are two C/C++ libraries that come to mind.
[ ".net", "networking", "tcp", "udp" ]
19
15
12,114
16
0
2008-08-28T02:55:23.347000
2008-08-28T07:16:35.153000
31,581
31,833
How scalable is System.Threading.Timer?
I'm writing an app that will need to make use of Timer s, but potentially very many of them. How scalable is the System.Threading.Timer class? The documentation merely say it's "lightweight", but doesn't explain further. Do these timers get sucked into a single thread (or very small threadpool) that processes all the callbacks on behalf of a Timer, or does each Timer have its own thread? I guess another way to rephrase the question is: How is System.Threading.Timer implemented?
I say this in response to a lot of questions: Don't forget that the (managed) source code to the framework is available. You can use this tool to get it all: http://www.codeplex.com/NetMassDownloader Unfortunately, in this specific case, a lot of the implementation is in native code, so you don't get to look at it... They definitely use pool threads rather than a thread-per-timer, though. The standard way to implement a big collection of timers (which is how the kernel does it internally, and I would suspect is indirectly how your big collection of Timers ends up) is to maintain the list sorted by time-until-expiry - so the system only ever has to worry about checking the next timer which is going to expire, not the whole list. Roughly, this gives O(log n) for starting a timer and O(1) for processing running timers. Edit: Just been looking in Jeff Richter's book. He says (of Threading.Timer) that it uses a single thread for all Timer objects, this thread knows when the next timer (i.e. as above) is due and calls ThreadPool.QueueUserWorkItem for the callbacks as appropriate. This has the effect that if you don't finish servicing one callback on a timer before the next is due, that your callback will reenter on another pool thread. So in summary I doubt you'll see a big problem with having lots of timers, but you might suffer thread pool exhaustion if large numbers of them are firing at the same timer and/or their callbacks are slow-running.
How scalable is System.Threading.Timer? I'm writing an app that will need to make use of Timer s, but potentially very many of them. How scalable is the System.Threading.Timer class? The documentation merely say it's "lightweight", but doesn't explain further. Do these timers get sucked into a single thread (or very small threadpool) that processes all the callbacks on behalf of a Timer, or does each Timer have its own thread? I guess another way to rephrase the question is: How is System.Threading.Timer implemented?
TITLE: How scalable is System.Threading.Timer? QUESTION: I'm writing an app that will need to make use of Timer s, but potentially very many of them. How scalable is the System.Threading.Timer class? The documentation merely say it's "lightweight", but doesn't explain further. Do these timers get sucked into a single thread (or very small threadpool) that processes all the callbacks on behalf of a Timer, or does each Timer have its own thread? I guess another way to rephrase the question is: How is System.Threading.Timer implemented? ANSWER: I say this in response to a lot of questions: Don't forget that the (managed) source code to the framework is available. You can use this tool to get it all: http://www.codeplex.com/NetMassDownloader Unfortunately, in this specific case, a lot of the implementation is in native code, so you don't get to look at it... They definitely use pool threads rather than a thread-per-timer, though. The standard way to implement a big collection of timers (which is how the kernel does it internally, and I would suspect is indirectly how your big collection of Timers ends up) is to maintain the list sorted by time-until-expiry - so the system only ever has to worry about checking the next timer which is going to expire, not the whole list. Roughly, this gives O(log n) for starting a timer and O(1) for processing running timers. Edit: Just been looking in Jeff Richter's book. He says (of Threading.Timer) that it uses a single thread for all Timer objects, this thread knows when the next timer (i.e. as above) is due and calls ThreadPool.QueueUserWorkItem for the callbacks as appropriate. This has the effect that if you don't finish servicing one callback on a timer before the next is due, that your callback will reenter on another pool thread. So in summary I doubt you'll see a big problem with having lots of timers, but you might suffer thread pool exhaustion if large numbers of them are firing at the same timer and/or their callbacks are slow-running.
[ "c#", ".net", "multithreading", "timer" ]
26
29
10,327
4
0
2008-08-28T03:01:10.773000
2008-08-28T08:12:24.270000
31,584
37,005
Design: Java and returning self-reference in setter methods
For classes that have a long list of setters that are used frequently, I found this way very useful (although I have recently read about the Builder pattern in Effective Java that is kinda the same). Basically, all setter methods return the object itself so then you can use code like this: myClass.setInt(1).setString("test").setBoolean(true); Setters simply return this in the end: public MyClass setInt(int anInt) { // [snip] return this; } What is your opinion? What are the pros and cons? Does this have any impact on performance? Also referred to as the named parameter idiom in c++.
@pek Chained invocation is one of proposals for Java 7. It says that if a method return type is void, it should implicitly return this. If you're interested in this topic, there is a bunch of links and a simple example on Alex Miller's Java 7 page.
Design: Java and returning self-reference in setter methods For classes that have a long list of setters that are used frequently, I found this way very useful (although I have recently read about the Builder pattern in Effective Java that is kinda the same). Basically, all setter methods return the object itself so then you can use code like this: myClass.setInt(1).setString("test").setBoolean(true); Setters simply return this in the end: public MyClass setInt(int anInt) { // [snip] return this; } What is your opinion? What are the pros and cons? Does this have any impact on performance? Also referred to as the named parameter idiom in c++.
TITLE: Design: Java and returning self-reference in setter methods QUESTION: For classes that have a long list of setters that are used frequently, I found this way very useful (although I have recently read about the Builder pattern in Effective Java that is kinda the same). Basically, all setter methods return the object itself so then you can use code like this: myClass.setInt(1).setString("test").setBoolean(true); Setters simply return this in the end: public MyClass setInt(int anInt) { // [snip] return this; } What is your opinion? What are the pros and cons? Does this have any impact on performance? Also referred to as the named parameter idiom in c++. ANSWER: @pek Chained invocation is one of proposals for Java 7. It says that if a method return type is void, it should implicitly return this. If you're interested in this topic, there is a bunch of links and a simple example on Alex Miller's Java 7 page.
[ "java" ]
22
15
20,520
11
0
2008-08-28T03:03:53.467000
2008-08-31T18:14:27.953000
31,592
31,609
How to get the libraries you need into the bin folder when using IoC/DI
I'm using Castle Windsor to do some dependency injection, specifically I've abstracted the DAL layer to interfaces that are now being loaded by DI. Once the project is developed & deployed all the.bin files will be in the same location, but for while I'm developing in Visual Studio, the only ways I can see of getting the dependency injected project's.bin file into the startup project's bin folder is to either have a post-build event that copies it in, or to put in a manual reference to the DAL project to pull the file in. I'm not totally thrilled with either solution, so I was wondering if there was a 'standard' way of solving this problem?
Could you set the build output path of the concrete DAL project to be the bin folder of the dependent project?
How to get the libraries you need into the bin folder when using IoC/DI I'm using Castle Windsor to do some dependency injection, specifically I've abstracted the DAL layer to interfaces that are now being loaded by DI. Once the project is developed & deployed all the.bin files will be in the same location, but for while I'm developing in Visual Studio, the only ways I can see of getting the dependency injected project's.bin file into the startup project's bin folder is to either have a post-build event that copies it in, or to put in a manual reference to the DAL project to pull the file in. I'm not totally thrilled with either solution, so I was wondering if there was a 'standard' way of solving this problem?
TITLE: How to get the libraries you need into the bin folder when using IoC/DI QUESTION: I'm using Castle Windsor to do some dependency injection, specifically I've abstracted the DAL layer to interfaces that are now being loaded by DI. Once the project is developed & deployed all the.bin files will be in the same location, but for while I'm developing in Visual Studio, the only ways I can see of getting the dependency injected project's.bin file into the startup project's bin folder is to either have a post-build event that copies it in, or to put in a manual reference to the DAL project to pull the file in. I'm not totally thrilled with either solution, so I was wondering if there was a 'standard' way of solving this problem? ANSWER: Could you set the build output path of the concrete DAL project to be the bin folder of the dependent project?
[ "visual-studio", "dependency-injection", "inversion-of-control", "castle-windsor" ]
1
1
222
2
0
2008-08-28T03:09:28.790000
2008-08-28T03:31:14.523000
31,627
31,631
Alternative to VSS for a one man show (army of one?)
I've been programming for 10+ years now for the same employer and only source code control we've ever used is VSS. (Sorry - That's what they had when I started). There's only ever been a few of us; two right now and we usually work alone, so VSS has worked ok for us. So, I have two questions: 1) Should we switch to something else like subversion, git, TFS, etc what exactly and why (please)? 2) Am I beyond all hope and destined to eternal damnation because VSS has corrupted me (as Jeff says)? Wow - thanks for all the great responses! It sounds like I should clearify a few things. We are a MS shop (Gold parntner) and we mostly do VB, ASP.NET, SQL Server, sharepoint & Biztalk work. I have CS degree so I've done x86 assembly C, C++ on DEC Unix and Slackware Linux in a "time out of mind"... My concern with VSS is that now I'm working over a VPN a lot more and VSS's performance sux and I'm afraid that our 10+ y/o version 5 VSS database is going to get hoosed... There's the LAN service that's supposed to speed things up, but Ive never used it and I'm not sure it helps with corruption - has anyone used the VSS LAN service? (new with VSS 2005)
I'd probably go with Subversion, if I were you. I'm a total Git fanatic at this point, but Subversion certainly has some advantages: simplicity abundance of interoperable tools active and supportive community portable Has really nice Windows shell integration integrates with visual studio (I think - but surely through a third party) Git has many, many other advantages, but the above tend to be the ones people care about when asking general questions like the above. Edit: the company I now work for is using VisualSVN server, which is free. It makes setting up a Subversion repository on a Windows server stupid simple, and on the client we're using TortoiseSVN (for shell integration) and AnkhSVN for Visual Studio support. It's quite good, and should be fairly easy for even VSS users to pick up. Latter-day Edit: So....nearly eight years later, I would never recommend Subversion to anyone for any reason. I don't really recant, per se, because I think my advice was valid at the time. However, in 2016, Subversion retains almost none of the advantages it used to have over Git. The tooling for Git is superior to (and much more diverse) what it once was, and in particular, there's GitHub and other good Git hosting providers (BitBucket, Beanstalk, Visual Studio Online, just off the top of my head). Visual Studio now has Git support out-of-the-box, and it's actually pretty good. There are even PowerShell modules to give a more native Windows experience to denizens of the console. Git is even easier to set up and use than Subversion and doesn't require a server component. Git has become as ubiquitous as any single tool can be, and you really would only be cheating yourself to not use it (unless you just really want to use something not-Git). Don't misunderstand - this isn't me hating on Subversion, but rather me recognizing that it's a tool from another time, rather like a straight razor for shaving.
Alternative to VSS for a one man show (army of one?) I've been programming for 10+ years now for the same employer and only source code control we've ever used is VSS. (Sorry - That's what they had when I started). There's only ever been a few of us; two right now and we usually work alone, so VSS has worked ok for us. So, I have two questions: 1) Should we switch to something else like subversion, git, TFS, etc what exactly and why (please)? 2) Am I beyond all hope and destined to eternal damnation because VSS has corrupted me (as Jeff says)? Wow - thanks for all the great responses! It sounds like I should clearify a few things. We are a MS shop (Gold parntner) and we mostly do VB, ASP.NET, SQL Server, sharepoint & Biztalk work. I have CS degree so I've done x86 assembly C, C++ on DEC Unix and Slackware Linux in a "time out of mind"... My concern with VSS is that now I'm working over a VPN a lot more and VSS's performance sux and I'm afraid that our 10+ y/o version 5 VSS database is going to get hoosed... There's the LAN service that's supposed to speed things up, but Ive never used it and I'm not sure it helps with corruption - has anyone used the VSS LAN service? (new with VSS 2005)
TITLE: Alternative to VSS for a one man show (army of one?) QUESTION: I've been programming for 10+ years now for the same employer and only source code control we've ever used is VSS. (Sorry - That's what they had when I started). There's only ever been a few of us; two right now and we usually work alone, so VSS has worked ok for us. So, I have two questions: 1) Should we switch to something else like subversion, git, TFS, etc what exactly and why (please)? 2) Am I beyond all hope and destined to eternal damnation because VSS has corrupted me (as Jeff says)? Wow - thanks for all the great responses! It sounds like I should clearify a few things. We are a MS shop (Gold parntner) and we mostly do VB, ASP.NET, SQL Server, sharepoint & Biztalk work. I have CS degree so I've done x86 assembly C, C++ on DEC Unix and Slackware Linux in a "time out of mind"... My concern with VSS is that now I'm working over a VPN a lot more and VSS's performance sux and I'm afraid that our 10+ y/o version 5 VSS database is going to get hoosed... There's the LAN service that's supposed to speed things up, but Ive never used it and I'm not sure it helps with corruption - has anyone used the VSS LAN service? (new with VSS 2005) ANSWER: I'd probably go with Subversion, if I were you. I'm a total Git fanatic at this point, but Subversion certainly has some advantages: simplicity abundance of interoperable tools active and supportive community portable Has really nice Windows shell integration integrates with visual studio (I think - but surely through a third party) Git has many, many other advantages, but the above tend to be the ones people care about when asking general questions like the above. Edit: the company I now work for is using VisualSVN server, which is free. It makes setting up a Subversion repository on a Windows server stupid simple, and on the client we're using TortoiseSVN (for shell integration) and AnkhSVN for Visual Studio support. It's quite good, and should be fairly easy for even VSS users to pick up. Latter-day Edit: So....nearly eight years later, I would never recommend Subversion to anyone for any reason. I don't really recant, per se, because I think my advice was valid at the time. However, in 2016, Subversion retains almost none of the advantages it used to have over Git. The tooling for Git is superior to (and much more diverse) what it once was, and in particular, there's GitHub and other good Git hosting providers (BitBucket, Beanstalk, Visual Studio Online, just off the top of my head). Visual Studio now has Git support out-of-the-box, and it's actually pretty good. There are even PowerShell modules to give a more native Windows experience to denizens of the console. Git is even easier to set up and use than Subversion and doesn't require a server component. Git has become as ubiquitous as any single tool can be, and you really would only be cheating yourself to not use it (unless you just really want to use something not-Git). Don't misunderstand - this isn't me hating on Subversion, but rather me recognizing that it's a tool from another time, rather like a straight razor for shaving.
[ "version-control", "visual-sourcesafe" ]
12
28
2,555
16
0
2008-08-28T03:40:16.250000
2008-08-28T03:44:07.753000
31,672
67,624
Learning FORTRAN In the Modern Era
I've recently come to maintain a large amount of scientific calculation-intensive FORTRAN code. I'm having difficulties getting a handle on all of the, say, nuances, of a forty year old language, despite google & two introductory level books. The code is rife with "performance enhancing improvements". Does anyone have any guides or practical advice for de -optimizing FORTRAN into CS 101 levels? Does anyone have knowledge of how FORTRAN code optimization operated? Are there any typical FORTRAN 'gotchas' that might not occur to a Java/C++/.NET raised developer taking over a FORTRAN 77/90 codebase?
You kind of have to get a "feel" for what programmers had to do back in the day. The vast majority of the code I work with is older than I am and ran on machines that were "new" when my parents were in high school. Common FORTRAN-isms I deal with, that hurt readability are: Common blocks Implicit variables Two or three DO loops with shared CONTINUE statements GOTO's in place of DO loops Arithmetic IF statements Computed GOTO's Equivalence REAL/INTEGER/other in some common block Strategies for solving these involve: Get Spag / plusFORT, worth the money, it solves a lot of them automatically and Bug Free(tm) Move to Fortran 90 if at all possible, if not move to free-format Fortran 77 Add IMPLICIT NONE to each subroutine and then fix every compile error, time consuming but ultimately necessary, some programs can do this for you automatically (or you can script it) Moving all COMMON blocks to MODULEs, low hanging fruit, worth it Convert arithmetic IF statements to IF..ELSEIF..ELSE blocks Convert computed GOTOs to SELECT CASE blocks Convert all DO loops to the newer F90 syntax myloop: do ii = 1, nloops! do something enddo myloop Convert equivalenced common block members to either ALLOCATABLE memory allocated in a module, or to their true character routines if it is Hollerith being stored in a REAL If you had more specific questions as to how to accomplish some readability tasks, I can give advice. I have a code base of a few hundred thousand lines of Fortran which was written over the span of 40 years that I am in some way responsible for, so I've probably run across any "problems" you may have found.
Learning FORTRAN In the Modern Era I've recently come to maintain a large amount of scientific calculation-intensive FORTRAN code. I'm having difficulties getting a handle on all of the, say, nuances, of a forty year old language, despite google & two introductory level books. The code is rife with "performance enhancing improvements". Does anyone have any guides or practical advice for de -optimizing FORTRAN into CS 101 levels? Does anyone have knowledge of how FORTRAN code optimization operated? Are there any typical FORTRAN 'gotchas' that might not occur to a Java/C++/.NET raised developer taking over a FORTRAN 77/90 codebase?
TITLE: Learning FORTRAN In the Modern Era QUESTION: I've recently come to maintain a large amount of scientific calculation-intensive FORTRAN code. I'm having difficulties getting a handle on all of the, say, nuances, of a forty year old language, despite google & two introductory level books. The code is rife with "performance enhancing improvements". Does anyone have any guides or practical advice for de -optimizing FORTRAN into CS 101 levels? Does anyone have knowledge of how FORTRAN code optimization operated? Are there any typical FORTRAN 'gotchas' that might not occur to a Java/C++/.NET raised developer taking over a FORTRAN 77/90 codebase? ANSWER: You kind of have to get a "feel" for what programmers had to do back in the day. The vast majority of the code I work with is older than I am and ran on machines that were "new" when my parents were in high school. Common FORTRAN-isms I deal with, that hurt readability are: Common blocks Implicit variables Two or three DO loops with shared CONTINUE statements GOTO's in place of DO loops Arithmetic IF statements Computed GOTO's Equivalence REAL/INTEGER/other in some common block Strategies for solving these involve: Get Spag / plusFORT, worth the money, it solves a lot of them automatically and Bug Free(tm) Move to Fortran 90 if at all possible, if not move to free-format Fortran 77 Add IMPLICIT NONE to each subroutine and then fix every compile error, time consuming but ultimately necessary, some programs can do this for you automatically (or you can script it) Moving all COMMON blocks to MODULEs, low hanging fruit, worth it Convert arithmetic IF statements to IF..ELSEIF..ELSE blocks Convert computed GOTOs to SELECT CASE blocks Convert all DO loops to the newer F90 syntax myloop: do ii = 1, nloops! do something enddo myloop Convert equivalenced common block members to either ALLOCATABLE memory allocated in a module, or to their true character routines if it is Hollerith being stored in a REAL If you had more specific questions as to how to accomplish some readability tasks, I can give advice. I have a code base of a few hundred thousand lines of Fortran which was written over the span of 40 years that I am in some way responsible for, so I've probably run across any "problems" you may have found.
[ "fortran" ]
80
88
15,766
10
0
2008-08-28T04:36:25.570000
2008-09-15T22:29:44.433000
31,693
31,929
What are the differences between Generics in C# and Java... and Templates in C++?
I mostly use Java and generics are relatively new. I keep reading that Java made the wrong decision or that.NET has better implementations etc. etc. So, what are the main differences between C++, C#, Java in generics? Pros/cons of each?
I'll add my voice to the noise and take a stab at making things clear: C# Generics allow you to declare something like this. List foo = new List (); and then the compiler will prevent you from putting things that aren't Person into the list. Behind the scenes the C# compiler is just putting List into the.NET dll file, but at runtime the JIT compiler goes and builds a new set of code, as if you had written a special list class just for containing people - something like ListOfPerson. The benefit of this is that it makes it really fast. There's no casting or any other stuff, and because the dll contains the information that this is a List of Person, other code that looks at it later on using reflection can tell that it contains Person objects (so you get intellisense and so on). The downside of this is that old C# 1.0 and 1.1 code (before they added generics) doesn't understand these new List, so you have to manually convert things back to plain old List to interoperate with them. This is not that big of a problem, because C# 2.0 binary code is not backwards compatible. The only time this will ever happen is if you're upgrading some old C# 1.0/1.1 code to C# 2.0 Java Generics allow you to declare something like this. ArrayList foo = new ArrayList (); On the surface it looks the same, and it sort-of is. The compiler will also prevent you from putting things that aren't Person into the list. The difference is what happens behind the scenes. Unlike C#, Java does not go and build a special ListOfPerson - it just uses the plain old ArrayList which has always been in Java. When you get things out of the array, the usual Person p = (Person)foo.get(1); casting-dance still has to be done. The compiler is saving you the key-presses, but the speed hit/casting is still incurred just like it always was. When people mention "Type Erasure" this is what they're talking about. The compiler inserts the casts for you, and then 'erases' the fact that it's meant to be a list of Person not just Object The benefit of this approach is that old code which doesn't understand generics doesn't have to care. It's still dealing with the same old ArrayList as it always has. This is more important in the java world because they wanted to support compiling code using Java 5 with generics, and having it run on old 1.4 or previous JVM's, which microsoft deliberately decided not to bother with. The downside is the speed hit I mentioned previously, and also because there is no ListOfPerson pseudo-class or anything like that going into the.class files, code that looks at it later on (with reflection, or if you pull it out of another collection where it's been converted into Object or so on) can't tell in any way that it's meant to be a list containing only Person and not just any other array list. C++ Templates allow you to declare something like this std::list * foo = new std::list (); It looks like C# and Java generics, and it will do what you think it should do, but behind the scenes different things are happening. It has the most in common with C# generics in that it builds special pseudo-classes rather than just throwing the type information away like java does, but it's a whole different kettle of fish. Both C# and Java produce output which is designed for virtual machines. If you write some code which has a Person class in it, in both cases some information about a Person class will go into the.dll or.class file, and the JVM/CLR will do stuff with this. C++ produces raw x86 binary code. Everything is not an object, and there's no underlying virtual machine which needs to know about a Person class. There's no boxing or unboxing, and functions don't have to belong to classes, or indeed anything. Because of this, the C++ compiler places no restrictions on what you can do with templates - basically any code you could write manually, you can get templates to write for you. The most obvious example is adding things: In C# and Java, the generics system needs to know what methods are available for a class, and it needs to pass this down to the virtual machine. The only way to tell it this is by either hard-coding the actual class in, or using interfaces. For example: string addNames ( T first, T second ) { return first.Name() + second.Name(); } That code won't compile in C# or Java, because it doesn't know that the type T actually provides a method called Name(). You have to tell it - in C# like this: interface IHasName{ string Name(); }; string addNames ( T first, T second ) where T: IHasName {.... } And then you have to make sure the things you pass to addNames implement the IHasName interface and so on. The java syntax is different ( ), but it suffers from the same problems. The 'classic' case for this problem is trying to write a function which does this string addNames ( T first, T second ) { return first + second; } You can't actually write this code because there are no ways to declare an interface with the + method in it. You fail. C++ suffers from none of these problems. The compiler doesn't care about passing types down to any VM's - if both your objects have a.Name() function, it will compile. If they don't, it won't. Simple. So, there you have it:-)
What are the differences between Generics in C# and Java... and Templates in C++? I mostly use Java and generics are relatively new. I keep reading that Java made the wrong decision or that.NET has better implementations etc. etc. So, what are the main differences between C++, C#, Java in generics? Pros/cons of each?
TITLE: What are the differences between Generics in C# and Java... and Templates in C++? QUESTION: I mostly use Java and generics are relatively new. I keep reading that Java made the wrong decision or that.NET has better implementations etc. etc. So, what are the main differences between C++, C#, Java in generics? Pros/cons of each? ANSWER: I'll add my voice to the noise and take a stab at making things clear: C# Generics allow you to declare something like this. List foo = new List (); and then the compiler will prevent you from putting things that aren't Person into the list. Behind the scenes the C# compiler is just putting List into the.NET dll file, but at runtime the JIT compiler goes and builds a new set of code, as if you had written a special list class just for containing people - something like ListOfPerson. The benefit of this is that it makes it really fast. There's no casting or any other stuff, and because the dll contains the information that this is a List of Person, other code that looks at it later on using reflection can tell that it contains Person objects (so you get intellisense and so on). The downside of this is that old C# 1.0 and 1.1 code (before they added generics) doesn't understand these new List, so you have to manually convert things back to plain old List to interoperate with them. This is not that big of a problem, because C# 2.0 binary code is not backwards compatible. The only time this will ever happen is if you're upgrading some old C# 1.0/1.1 code to C# 2.0 Java Generics allow you to declare something like this. ArrayList foo = new ArrayList (); On the surface it looks the same, and it sort-of is. The compiler will also prevent you from putting things that aren't Person into the list. The difference is what happens behind the scenes. Unlike C#, Java does not go and build a special ListOfPerson - it just uses the plain old ArrayList which has always been in Java. When you get things out of the array, the usual Person p = (Person)foo.get(1); casting-dance still has to be done. The compiler is saving you the key-presses, but the speed hit/casting is still incurred just like it always was. When people mention "Type Erasure" this is what they're talking about. The compiler inserts the casts for you, and then 'erases' the fact that it's meant to be a list of Person not just Object The benefit of this approach is that old code which doesn't understand generics doesn't have to care. It's still dealing with the same old ArrayList as it always has. This is more important in the java world because they wanted to support compiling code using Java 5 with generics, and having it run on old 1.4 or previous JVM's, which microsoft deliberately decided not to bother with. The downside is the speed hit I mentioned previously, and also because there is no ListOfPerson pseudo-class or anything like that going into the.class files, code that looks at it later on (with reflection, or if you pull it out of another collection where it's been converted into Object or so on) can't tell in any way that it's meant to be a list containing only Person and not just any other array list. C++ Templates allow you to declare something like this std::list * foo = new std::list (); It looks like C# and Java generics, and it will do what you think it should do, but behind the scenes different things are happening. It has the most in common with C# generics in that it builds special pseudo-classes rather than just throwing the type information away like java does, but it's a whole different kettle of fish. Both C# and Java produce output which is designed for virtual machines. If you write some code which has a Person class in it, in both cases some information about a Person class will go into the.dll or.class file, and the JVM/CLR will do stuff with this. C++ produces raw x86 binary code. Everything is not an object, and there's no underlying virtual machine which needs to know about a Person class. There's no boxing or unboxing, and functions don't have to belong to classes, or indeed anything. Because of this, the C++ compiler places no restrictions on what you can do with templates - basically any code you could write manually, you can get templates to write for you. The most obvious example is adding things: In C# and Java, the generics system needs to know what methods are available for a class, and it needs to pass this down to the virtual machine. The only way to tell it this is by either hard-coding the actual class in, or using interfaces. For example: string addNames ( T first, T second ) { return first.Name() + second.Name(); } That code won't compile in C# or Java, because it doesn't know that the type T actually provides a method called Name(). You have to tell it - in C# like this: interface IHasName{ string Name(); }; string addNames ( T first, T second ) where T: IHasName {.... } And then you have to make sure the things you pass to addNames implement the IHasName interface and so on. The java syntax is different ( ), but it suffers from the same problems. The 'classic' case for this problem is trying to write a function which does this string addNames ( T first, T second ) { return first + second; } You can't actually write this code because there are no ways to declare an interface with the + method in it. You fail. C++ suffers from none of these problems. The compiler doesn't care about passing types down to any VM's - if both your objects have a.Name() function, it will compile. If they don't, it won't. Simple. So, there you have it:-)
[ "c#", "java", "c++", "generics", "templates" ]
203
362
60,668
13
0
2008-08-28T05:08:06.663000
2008-08-28T09:50:26.127000
31,701
34,140
How to control layer ordering in Virtual Earth
I have a mapping application that needs to draw a path, and then display icons on top of the path. I can't find a way to control the order of virtual earth layers, other than the order in which they are added. Does anyone know how to change the z index of Virtual Earth shape layers, or force a layer to the front?
I think the easiest way is to iterate through the shapes in your VEShapeLayer and use the VEShape.SetZIndex method.
How to control layer ordering in Virtual Earth I have a mapping application that needs to draw a path, and then display icons on top of the path. I can't find a way to control the order of virtual earth layers, other than the order in which they are added. Does anyone know how to change the z index of Virtual Earth shape layers, or force a layer to the front?
TITLE: How to control layer ordering in Virtual Earth QUESTION: I have a mapping application that needs to draw a path, and then display icons on top of the path. I can't find a way to control the order of virtual earth layers, other than the order in which they are added. Does anyone know how to change the z index of Virtual Earth shape layers, or force a layer to the front? ANSWER: I think the easiest way is to iterate through the shapes in your VEShapeLayer and use the VEShape.SetZIndex method.
[ "javascript", "virtual-earth" ]
4
2
603
2
0
2008-08-28T05:17:19.730000
2008-08-29T07:49:01.260000
31,708
31,710
How can I convert IEnumerable<T> to List<T> in C#?
I am using LINQ to query a generic dictionary and then use the result as the datasource for my ListView (WebForms). Simplified code: Dictionary dict = GetAllRecords(); myListView.DataSource = dict.Values.Where(rec => rec.Name == "foo"); myListView.DataBind(); I thought that would work but in fact it throws a System.InvalidOperationException: ListView with id 'myListView' must have a data source that either implements ICollection or can perform data source paging if AllowPaging is true. In order to get it working I have had to resort to the following: Dictionary dict = GetAllRecords(); List searchResults = new List (); var matches = dict.Values.Where(rec => rec.Name == "foo"); foreach (Record rec in matches) searchResults.Add(rec); myListView.DataSource = searchResults; myListView.DataBind(); Is there a small gotcha in the first example to make it work? (Wasn't sure what to use as the question title for this one, feel free to edit to something more appropriate)
Try this: var matches = dict.Values.Where(rec => rec.Name == "foo").ToList(); Be aware that that will essentially be creating a new list from the original Values collection, and so any changes to your dictionary won't automatically be reflected in your bound control.
How can I convert IEnumerable<T> to List<T> in C#? I am using LINQ to query a generic dictionary and then use the result as the datasource for my ListView (WebForms). Simplified code: Dictionary dict = GetAllRecords(); myListView.DataSource = dict.Values.Where(rec => rec.Name == "foo"); myListView.DataBind(); I thought that would work but in fact it throws a System.InvalidOperationException: ListView with id 'myListView' must have a data source that either implements ICollection or can perform data source paging if AllowPaging is true. In order to get it working I have had to resort to the following: Dictionary dict = GetAllRecords(); List searchResults = new List (); var matches = dict.Values.Where(rec => rec.Name == "foo"); foreach (Record rec in matches) searchResults.Add(rec); myListView.DataSource = searchResults; myListView.DataBind(); Is there a small gotcha in the first example to make it work? (Wasn't sure what to use as the question title for this one, feel free to edit to something more appropriate)
TITLE: How can I convert IEnumerable<T> to List<T> in C#? QUESTION: I am using LINQ to query a generic dictionary and then use the result as the datasource for my ListView (WebForms). Simplified code: Dictionary dict = GetAllRecords(); myListView.DataSource = dict.Values.Where(rec => rec.Name == "foo"); myListView.DataBind(); I thought that would work but in fact it throws a System.InvalidOperationException: ListView with id 'myListView' must have a data source that either implements ICollection or can perform data source paging if AllowPaging is true. In order to get it working I have had to resort to the following: Dictionary dict = GetAllRecords(); List searchResults = new List (); var matches = dict.Values.Where(rec => rec.Name == "foo"); foreach (Record rec in matches) searchResults.Add(rec); myListView.DataSource = searchResults; myListView.DataBind(); Is there a small gotcha in the first example to make it work? (Wasn't sure what to use as the question title for this one, feel free to edit to something more appropriate) ANSWER: Try this: var matches = dict.Values.Where(rec => rec.Name == "foo").ToList(); Be aware that that will essentially be creating a new list from the original Values collection, and so any changes to your dictionary won't automatically be reflected in your bound control.
[ "c#", "linq", "generics", "listview" ]
17
29
54,449
5
0
2008-08-28T05:21:26.943000
2008-08-28T05:23:15.067000
31,711
31,788
How to plot a long path with Virtual Earth
The obvious way to plot a path with virtual earth (VEMap.GetDirections) is limited to 25 points. When trying to plot a vehicle's journey this is extremely limiting. How can I plot a by-road journey of more than 25 points on a virtual earth map?
According to this you need to call VEMap.GetDirections every 25 points until you reach the end of the route and then plot a custom shape of the complete route.
How to plot a long path with Virtual Earth The obvious way to plot a path with virtual earth (VEMap.GetDirections) is limited to 25 points. When trying to plot a vehicle's journey this is extremely limiting. How can I plot a by-road journey of more than 25 points on a virtual earth map?
TITLE: How to plot a long path with Virtual Earth QUESTION: The obvious way to plot a path with virtual earth (VEMap.GetDirections) is limited to 25 points. When trying to plot a vehicle's journey this is extremely limiting. How can I plot a by-road journey of more than 25 points on a virtual earth map? ANSWER: According to this you need to call VEMap.GetDirections every 25 points until you reach the end of the route and then plot a custom shape of the complete route.
[ "javascript", "virtual-earth" ]
3
1
414
1
0
2008-08-28T05:23:30.120000
2008-08-28T07:28:09.430000
31,722
33,500
Anyone have a diff algorithm for rendered HTML?
I'm interested in seeing a good diff algorithm, possibly in Javascript, for rendering a side-by-side diff of two HTML pages. The idea would be that the diff would show the differences of the rendered HTML. To clarify, I want to be able to see the side-by-side diffs as rendered output. So if I delete a paragraph, the side by side view would know to space things correctly. @Josh exactly. Though maybe it would show the deleted text in red or something. The idea is that if I use a WYSIWYG editor for my HTML content, I don't want to have to switch to HTML to do diffs. I want to do it with two WYSIWYG editors side by side maybe. Or at least display diffs side-by-side in an end-user friendly matter.
There's another nice trick you can use to significantly improve the look of a rendered HTML diff. Although this doesn't fully solve the initial problem, it will make a significant difference in the appearance of your rendered HTML diffs. Side-by-side rendered HTML will make it very difficult for your diff to line up vertically. Vertical alignment is crucial for comparing side-by-side diffs. In order to improve the vertical alignment of a side-by-side diff, you can insert invisible HTML elements in each version of the diff at "checkpoints" where the diff should be vertically aligned. Then you can use a bit of client-side JavaScript to add vertical spacing around checkpoint until the sides line up vertically. Explained in a little more detail: If you want to use this technique, run your diff algorithm and insert a bunch of visibility:hidden s or tiny s wherever your side-by-side versions should match up, according to the diff. Then run JavaScript that finds each checkpoint (and its side-by-side neighbor) and adds vertical spacing to the checkpoint that is higher-up (shallower) on the page. Now your rendered HTML diff will be vertically aligned up to that checkpoint, and you can continue repairing vertical alignment down the rest of your side-by-side page.
Anyone have a diff algorithm for rendered HTML? I'm interested in seeing a good diff algorithm, possibly in Javascript, for rendering a side-by-side diff of two HTML pages. The idea would be that the diff would show the differences of the rendered HTML. To clarify, I want to be able to see the side-by-side diffs as rendered output. So if I delete a paragraph, the side by side view would know to space things correctly. @Josh exactly. Though maybe it would show the deleted text in red or something. The idea is that if I use a WYSIWYG editor for my HTML content, I don't want to have to switch to HTML to do diffs. I want to do it with two WYSIWYG editors side by side maybe. Or at least display diffs side-by-side in an end-user friendly matter.
TITLE: Anyone have a diff algorithm for rendered HTML? QUESTION: I'm interested in seeing a good diff algorithm, possibly in Javascript, for rendering a side-by-side diff of two HTML pages. The idea would be that the diff would show the differences of the rendered HTML. To clarify, I want to be able to see the side-by-side diffs as rendered output. So if I delete a paragraph, the side by side view would know to space things correctly. @Josh exactly. Though maybe it would show the deleted text in red or something. The idea is that if I use a WYSIWYG editor for my HTML content, I don't want to have to switch to HTML to do diffs. I want to do it with two WYSIWYG editors side by side maybe. Or at least display diffs side-by-side in an end-user friendly matter. ANSWER: There's another nice trick you can use to significantly improve the look of a rendered HTML diff. Although this doesn't fully solve the initial problem, it will make a significant difference in the appearance of your rendered HTML diffs. Side-by-side rendered HTML will make it very difficult for your diff to line up vertically. Vertical alignment is crucial for comparing side-by-side diffs. In order to improve the vertical alignment of a side-by-side diff, you can insert invisible HTML elements in each version of the diff at "checkpoints" where the diff should be vertically aligned. Then you can use a bit of client-side JavaScript to add vertical spacing around checkpoint until the sides line up vertically. Explained in a little more detail: If you want to use this technique, run your diff algorithm and insert a bunch of visibility:hidden s or tiny s wherever your side-by-side versions should match up, according to the diff. Then run JavaScript that finds each checkpoint (and its side-by-side neighbor) and adds vertical spacing to the checkpoint that is higher-up (shallower) on the page. Now your rendered HTML diff will be vertically aligned up to that checkpoint, and you can continue repairing vertical alignment down the rest of your side-by-side page.
[ "javascript", "html", "diff" ]
91
17
39,236
12
0
2008-08-28T06:33:37.863000
2008-08-28T22:00:34.093000
31,790
31,798
How many ServiceContracts can a WCF service have?
How many ServiceContracts can a WCF service have? Specifically, since a ServiceContract is an attribute to an interface, how many interfaces can I code into one WCF web service? Is it a one-to-one? Does it make sense to separate the contracts across multiple web services?
You can have a service implement all the service contracts you want. I mean, I don't know if there is a limit, but I don't think there is. That's a neat way to separate operations that will be implemented by the same service in several conceptually different service contract interfaces.
How many ServiceContracts can a WCF service have? How many ServiceContracts can a WCF service have? Specifically, since a ServiceContract is an attribute to an interface, how many interfaces can I code into one WCF web service? Is it a one-to-one? Does it make sense to separate the contracts across multiple web services?
TITLE: How many ServiceContracts can a WCF service have? QUESTION: How many ServiceContracts can a WCF service have? Specifically, since a ServiceContract is an attribute to an interface, how many interfaces can I code into one WCF web service? Is it a one-to-one? Does it make sense to separate the contracts across multiple web services? ANSWER: You can have a service implement all the service contracts you want. I mean, I don't know if there is a limit, but I don't think there is. That's a neat way to separate operations that will be implemented by the same service in several conceptually different service contract interfaces.
[ "wcf", "web-services" ]
10
1
16,714
4
0
2008-08-28T07:28:17.857000
2008-08-28T07:36:29.363000
31,794
31,796
Help accessing application settings using ConfigurationManager
In.net frameworks 1.1, I use System.Configuration.ConfigurationSettings.AppSettings["name"]; for application settings. But in.Net 2.0, it says ConfigurationSettings is obsolete and to use ConfigurationManager instead. So I swapped it out with this: System.Configuration.ConfigurationManager.AppSettings["name"]; The problem is, ConfigurationManager was not found in the System.Configuration namespace. I've been banging my head against the wall trying to figure out what I'm doing wrong. Anybody got any ideas?
You have to reference the System.configuration assembly (note the lowercase) I don't know why this assembly is not added by default to new projects on Visual Studio, but I find myself having the same problem every time I start a new project. I always forget to add the reference.
Help accessing application settings using ConfigurationManager In.net frameworks 1.1, I use System.Configuration.ConfigurationSettings.AppSettings["name"]; for application settings. But in.Net 2.0, it says ConfigurationSettings is obsolete and to use ConfigurationManager instead. So I swapped it out with this: System.Configuration.ConfigurationManager.AppSettings["name"]; The problem is, ConfigurationManager was not found in the System.Configuration namespace. I've been banging my head against the wall trying to figure out what I'm doing wrong. Anybody got any ideas?
TITLE: Help accessing application settings using ConfigurationManager QUESTION: In.net frameworks 1.1, I use System.Configuration.ConfigurationSettings.AppSettings["name"]; for application settings. But in.Net 2.0, it says ConfigurationSettings is obsolete and to use ConfigurationManager instead. So I swapped it out with this: System.Configuration.ConfigurationManager.AppSettings["name"]; The problem is, ConfigurationManager was not found in the System.Configuration namespace. I've been banging my head against the wall trying to figure out what I'm doing wrong. Anybody got any ideas? ANSWER: You have to reference the System.configuration assembly (note the lowercase) I don't know why this assembly is not added by default to new projects on Visual Studio, but I find myself having the same problem every time I start a new project. I always forget to add the reference.
[ "c#", ".net", ".net-2.0" ]
6
9
2,659
5
0
2008-08-28T07:31:48.580000
2008-08-28T07:33:35.317000
31,799
31,810
Preventing XML Serialization of IEnumerable and ICollection<T> & Inherited Types
NOTE: XMLIgnore is NOT the answer! OK, so following on from my question on XML Serialization and Inherited Types, I began integrating that code into my application I am working on, stupidly thinking all will go well.. I ran into problems with a couple of classes I have that implement IEnumerable and ICollection The problem with these is that when the XMLSerializer comes to serialize these, it views them as an external property, and instead of using the property we would like it to (i.e. the one with our AbstractXmlSerializer ) it comes here and falls over (due to the type mismatch), pretty much putting us back to square one. You cannot decorate these methods with the XmlIgnore attribute either, so we cannot stop it that way. My current solution is to remove the interface implementation (in this current application, its no real big deal, just made the code prettier). Do I need to swallow my pride on this one and accept it cant be done? I know I have kinda pushed and got more out of the XmlSerializer than what was expected of it:) Edit I should also add, I am currently working in framework 2. Update I have accepted lomaxx's answer. In my scenario I cannot actually do this, but I do know it will work. Since their have been no other suggestions, I ended up removing the interface implementation from the code.
you can get around this problem by getting hold of the System.RunTime.Serialization dll (it's a.net 3.x assembly) and referencing it from your.net 2.0 application. This works because the.net 3.0 binaries are compiled to run on the.net 2.0 CLR. By doing this, you get access to the DataContractSerliazer which I've used to get around a similar problem where I wanted to pass in a ICollection as a parameter to a webservice and the xmlserializer didn't know how to deal with it properly. If you're cool with using the.net 3.x dll in your 2.x application you should be able to use the DataContractSerializer to solve this problem
Preventing XML Serialization of IEnumerable and ICollection<T> & Inherited Types NOTE: XMLIgnore is NOT the answer! OK, so following on from my question on XML Serialization and Inherited Types, I began integrating that code into my application I am working on, stupidly thinking all will go well.. I ran into problems with a couple of classes I have that implement IEnumerable and ICollection The problem with these is that when the XMLSerializer comes to serialize these, it views them as an external property, and instead of using the property we would like it to (i.e. the one with our AbstractXmlSerializer ) it comes here and falls over (due to the type mismatch), pretty much putting us back to square one. You cannot decorate these methods with the XmlIgnore attribute either, so we cannot stop it that way. My current solution is to remove the interface implementation (in this current application, its no real big deal, just made the code prettier). Do I need to swallow my pride on this one and accept it cant be done? I know I have kinda pushed and got more out of the XmlSerializer than what was expected of it:) Edit I should also add, I am currently working in framework 2. Update I have accepted lomaxx's answer. In my scenario I cannot actually do this, but I do know it will work. Since their have been no other suggestions, I ended up removing the interface implementation from the code.
TITLE: Preventing XML Serialization of IEnumerable and ICollection<T> & Inherited Types QUESTION: NOTE: XMLIgnore is NOT the answer! OK, so following on from my question on XML Serialization and Inherited Types, I began integrating that code into my application I am working on, stupidly thinking all will go well.. I ran into problems with a couple of classes I have that implement IEnumerable and ICollection The problem with these is that when the XMLSerializer comes to serialize these, it views them as an external property, and instead of using the property we would like it to (i.e. the one with our AbstractXmlSerializer ) it comes here and falls over (due to the type mismatch), pretty much putting us back to square one. You cannot decorate these methods with the XmlIgnore attribute either, so we cannot stop it that way. My current solution is to remove the interface implementation (in this current application, its no real big deal, just made the code prettier). Do I need to swallow my pride on this one and accept it cant be done? I know I have kinda pushed and got more out of the XmlSerializer than what was expected of it:) Edit I should also add, I am currently working in framework 2. Update I have accepted lomaxx's answer. In my scenario I cannot actually do this, but I do know it will work. Since their have been no other suggestions, I ended up removing the interface implementation from the code. ANSWER: you can get around this problem by getting hold of the System.RunTime.Serialization dll (it's a.net 3.x assembly) and referencing it from your.net 2.0 application. This works because the.net 3.0 binaries are compiled to run on the.net 2.0 CLR. By doing this, you get access to the DataContractSerliazer which I've used to get around a similar problem where I wanted to pass in a ICollection as a parameter to a webservice and the xmlserializer didn't know how to deal with it properly. If you're cool with using the.net 3.x dll in your 2.x application you should be able to use the DataContractSerializer to solve this problem
[ "xml", "inheritance", "serialization", ".net-2.0" ]
4
4
3,347
3
0
2008-08-28T07:36:40.020000
2008-08-28T07:45:11.467000
31,800
31,825
How to respond to an alternate URI in a RESTful web service
I'm building a RESTful web service which has multiple URIs for one of its resources, because there is more than one unique identifier. Should the server respond to a GET request for an alternate URI by returning the resource, or should I send an HTTP 3xx redirect to the canonical URI? Is HTTP 303 (see also) the most appropriate redirect? Clarification: the HTTP specification makes it clear that the choice of redirect depends on which URI future requests should use. In my application, the 'canonical' URI is the most stable of the alternatives; an alternative URI will always direct to same canonical URI, or become invalid.
I'd personally plump for returning the resource rather than faffing with a redirect, although I suspect that's only because my subcoscious is telling me redirects are slower. However, if you were to decide to use a redirect I'd think a 302 or 307 might be more appropiate than a 303, although the w3.org has details of the different redirect codes you could use.
How to respond to an alternate URI in a RESTful web service I'm building a RESTful web service which has multiple URIs for one of its resources, because there is more than one unique identifier. Should the server respond to a GET request for an alternate URI by returning the resource, or should I send an HTTP 3xx redirect to the canonical URI? Is HTTP 303 (see also) the most appropriate redirect? Clarification: the HTTP specification makes it clear that the choice of redirect depends on which URI future requests should use. In my application, the 'canonical' URI is the most stable of the alternatives; an alternative URI will always direct to same canonical URI, or become invalid.
TITLE: How to respond to an alternate URI in a RESTful web service QUESTION: I'm building a RESTful web service which has multiple URIs for one of its resources, because there is more than one unique identifier. Should the server respond to a GET request for an alternate URI by returning the resource, or should I send an HTTP 3xx redirect to the canonical URI? Is HTTP 303 (see also) the most appropriate redirect? Clarification: the HTTP specification makes it clear that the choice of redirect depends on which URI future requests should use. In my application, the 'canonical' URI is the most stable of the alternatives; an alternative URI will always direct to same canonical URI, or become invalid. ANSWER: I'd personally plump for returning the resource rather than faffing with a redirect, although I suspect that's only because my subcoscious is telling me redirects are slower. However, if you were to decide to use a redirect I'd think a 302 or 307 might be more appropiate than a 303, although the w3.org has details of the different redirect codes you could use.
[ "language-agnostic", "http", "rest" ]
4
4
485
3
0
2008-08-28T07:36:46.383000
2008-08-28T07:59:53.457000
31,818
31,820
How to find out which Service Pack is installed on SQL Server?
How can I find out which Service Pack is installed on my copy of SQL Server?
From TechNet: Determining which version and edition of SQL Server Database Engine is running -- SQL Server 2000/2005 SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition') -- SQL Server 6.5/7.0 SELECT @@VERSION
How to find out which Service Pack is installed on SQL Server? How can I find out which Service Pack is installed on my copy of SQL Server?
TITLE: How to find out which Service Pack is installed on SQL Server? QUESTION: How can I find out which Service Pack is installed on my copy of SQL Server? ANSWER: From TechNet: Determining which version and edition of SQL Server Database Engine is running -- SQL Server 2000/2005 SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition') -- SQL Server 6.5/7.0 SELECT @@VERSION
[ "sql-server" ]
13
21
45,837
2
0
2008-08-28T07:54:27.467000
2008-08-28T07:56:15.760000
31,826
31,841
Algorithmic complexity of XML parsers/validators
I need to know how the performance of different XML tools (parsers, validators, XPath expression evaluators, etc) is affected by the size and complexity of the input document. Are there resources out there that document how CPU time and memory usage are affected by... well, what? Document size in bytes? Number of nodes? And is the relationship linear, polynomial, or worse? Update In an article in IEEE Computer Magazine, vol 41 nr 9, sept 2008, the authors survey four popular XML parsing models (DOM, SAX, StAX and VTD). They run some very basic performance tests which show that a DOM-parser will have its throughput halved when the input file's size is increased from 1-15 KB to 1-15 MB, or about 1000x larger. The throughput of the other models is not significantly affected. Unfortunately they did not perform more detailed studies, such as of throughput/memory usage as a function of number of nodes/size. The article is here. Update I was unable to find any formal treatment of this problem. For what it's worth, I have done some experiments measuring the number of nodes in an XML document as a function of the document's size in bytes. I'm working on a warehouse management system and the XML documents are typical warehouse documents, e.g. advanced shipping notice etc. The graph below shows the relationship between the size in bytes and the number of nodes (which should be proportional to the document's memory footprint under a DOM model). The different colors correspond to different kinds of documents. The scale is log/log. The black line is the best fit to the blue points. It's interesting to note that for all kinds of documents, the relationship between byte size and node size is linear, but that the coefficient of proportionality can be very different. (source: flickr.com )
If I was faced with that problem and couldn't find anything on google I would probably try to do it my self. Some "back-of-an-evelope" stuff to get a feel for where it is going. But it would kinda need me to have an idea of how to do a xml parser. For non algorithmical benchmarks take a look here: http://www.xml.com/pub/a/Benchmark/exec.html http://www.devx.com/xml/Article/16922 http://xerces.apache.org/xerces2-j/faq-performance.html
Algorithmic complexity of XML parsers/validators I need to know how the performance of different XML tools (parsers, validators, XPath expression evaluators, etc) is affected by the size and complexity of the input document. Are there resources out there that document how CPU time and memory usage are affected by... well, what? Document size in bytes? Number of nodes? And is the relationship linear, polynomial, or worse? Update In an article in IEEE Computer Magazine, vol 41 nr 9, sept 2008, the authors survey four popular XML parsing models (DOM, SAX, StAX and VTD). They run some very basic performance tests which show that a DOM-parser will have its throughput halved when the input file's size is increased from 1-15 KB to 1-15 MB, or about 1000x larger. The throughput of the other models is not significantly affected. Unfortunately they did not perform more detailed studies, such as of throughput/memory usage as a function of number of nodes/size. The article is here. Update I was unable to find any formal treatment of this problem. For what it's worth, I have done some experiments measuring the number of nodes in an XML document as a function of the document's size in bytes. I'm working on a warehouse management system and the XML documents are typical warehouse documents, e.g. advanced shipping notice etc. The graph below shows the relationship between the size in bytes and the number of nodes (which should be proportional to the document's memory footprint under a DOM model). The different colors correspond to different kinds of documents. The scale is log/log. The black line is the best fit to the blue points. It's interesting to note that for all kinds of documents, the relationship between byte size and node size is linear, but that the coefficient of proportionality can be very different. (source: flickr.com )
TITLE: Algorithmic complexity of XML parsers/validators QUESTION: I need to know how the performance of different XML tools (parsers, validators, XPath expression evaluators, etc) is affected by the size and complexity of the input document. Are there resources out there that document how CPU time and memory usage are affected by... well, what? Document size in bytes? Number of nodes? And is the relationship linear, polynomial, or worse? Update In an article in IEEE Computer Magazine, vol 41 nr 9, sept 2008, the authors survey four popular XML parsing models (DOM, SAX, StAX and VTD). They run some very basic performance tests which show that a DOM-parser will have its throughput halved when the input file's size is increased from 1-15 KB to 1-15 MB, or about 1000x larger. The throughput of the other models is not significantly affected. Unfortunately they did not perform more detailed studies, such as of throughput/memory usage as a function of number of nodes/size. The article is here. Update I was unable to find any formal treatment of this problem. For what it's worth, I have done some experiments measuring the number of nodes in an XML document as a function of the document's size in bytes. I'm working on a warehouse management system and the XML documents are typical warehouse documents, e.g. advanced shipping notice etc. The graph below shows the relationship between the size in bytes and the number of nodes (which should be proportional to the document's memory footprint under a DOM model). The different colors correspond to different kinds of documents. The scale is log/log. The black line is the best fit to the blue points. It's interesting to note that for all kinds of documents, the relationship between byte size and node size is linear, but that the coefficient of proportionality can be very different. (source: flickr.com ) ANSWER: If I was faced with that problem and couldn't find anything on google I would probably try to do it my self. Some "back-of-an-evelope" stuff to get a feel for where it is going. But it would kinda need me to have an idea of how to do a xml parser. For non algorithmical benchmarks take a look here: http://www.xml.com/pub/a/Benchmark/exec.html http://www.devx.com/xml/Article/16922 http://xerces.apache.org/xerces2-j/faq-performance.html
[ "xml", "algorithm", "performance" ]
15
3
1,972
4
0
2008-08-28T08:01:12.690000
2008-08-28T08:21:00.880000
31,849
32,086
Capturing Cmd-C (or Ctrl-C) keyboard event from modular Flex application in browser or AIR
It seems that it is impossible to capture the keyboard event normally used for copy when running a Flex application in the browser or as an AIR app, presumably because the browser or OS is intercepting it first. Is there a way to tell the browser or OS to let the event through? For example, on an AdvancedDataGrid I have set the keyUp event to handleCaseListKeyUp(event), which calls the following function: private function handleCaseListKeyUp(event:KeyboardEvent):void { var char:String = String.fromCharCode(event.charCode).toUpperCase(); if (event.ctrlKey && char == "C") { trace("Ctrl-C"); copyCasesToClipboard(); return; } if (!event.ctrlKey && char == "C") { trace("C"); copyCasesToClipboard(); return; } // Didn't match event to capture, just drop out. trace("charCode: " + event.charCode); trace("char: " + char); trace("keyCode: " + event.keyCode); trace("ctrlKey: " + event.ctrlKey); trace("altKey: " + event.altKey); trace("shiftKey: " + event.shiftKey); } When run, I can never get the release of the "C" key while also pressing the command key (which shows up as KeyboardEvent.ctrlKey). I get the following trace results: charCode: 0 char: keyCode: 17 ctrlKey: false altKey: false shiftKey: false As you can see, the only event I can capture is the release of the command key, the release of the "C" key while holding the command key isn't even sent. Has anyone successfully implemented standard copy and paste keyboard handling? Am I destined to just use the "C" key on it's own (as shown in the code example) or make a copy button available? Or do I need to create the listener manually at a higher level and pass the event down into my modular application's guts?
I did a test where I listened for key up events on the stage and noticed that (on my Mac) I could capture control-c, control-v, etc. just fine, but anything involving command (the  key) wasn't captured until I released the command key, and then ctrlKey was false (even though the docs says that ctrlKey should be true for the command key on the Mac), and the charCode was 0. Pretty useless, in short.
Capturing Cmd-C (or Ctrl-C) keyboard event from modular Flex application in browser or AIR It seems that it is impossible to capture the keyboard event normally used for copy when running a Flex application in the browser or as an AIR app, presumably because the browser or OS is intercepting it first. Is there a way to tell the browser or OS to let the event through? For example, on an AdvancedDataGrid I have set the keyUp event to handleCaseListKeyUp(event), which calls the following function: private function handleCaseListKeyUp(event:KeyboardEvent):void { var char:String = String.fromCharCode(event.charCode).toUpperCase(); if (event.ctrlKey && char == "C") { trace("Ctrl-C"); copyCasesToClipboard(); return; } if (!event.ctrlKey && char == "C") { trace("C"); copyCasesToClipboard(); return; } // Didn't match event to capture, just drop out. trace("charCode: " + event.charCode); trace("char: " + char); trace("keyCode: " + event.keyCode); trace("ctrlKey: " + event.ctrlKey); trace("altKey: " + event.altKey); trace("shiftKey: " + event.shiftKey); } When run, I can never get the release of the "C" key while also pressing the command key (which shows up as KeyboardEvent.ctrlKey). I get the following trace results: charCode: 0 char: keyCode: 17 ctrlKey: false altKey: false shiftKey: false As you can see, the only event I can capture is the release of the command key, the release of the "C" key while holding the command key isn't even sent. Has anyone successfully implemented standard copy and paste keyboard handling? Am I destined to just use the "C" key on it's own (as shown in the code example) or make a copy button available? Or do I need to create the listener manually at a higher level and pass the event down into my modular application's guts?
TITLE: Capturing Cmd-C (or Ctrl-C) keyboard event from modular Flex application in browser or AIR QUESTION: It seems that it is impossible to capture the keyboard event normally used for copy when running a Flex application in the browser or as an AIR app, presumably because the browser or OS is intercepting it first. Is there a way to tell the browser or OS to let the event through? For example, on an AdvancedDataGrid I have set the keyUp event to handleCaseListKeyUp(event), which calls the following function: private function handleCaseListKeyUp(event:KeyboardEvent):void { var char:String = String.fromCharCode(event.charCode).toUpperCase(); if (event.ctrlKey && char == "C") { trace("Ctrl-C"); copyCasesToClipboard(); return; } if (!event.ctrlKey && char == "C") { trace("C"); copyCasesToClipboard(); return; } // Didn't match event to capture, just drop out. trace("charCode: " + event.charCode); trace("char: " + char); trace("keyCode: " + event.keyCode); trace("ctrlKey: " + event.ctrlKey); trace("altKey: " + event.altKey); trace("shiftKey: " + event.shiftKey); } When run, I can never get the release of the "C" key while also pressing the command key (which shows up as KeyboardEvent.ctrlKey). I get the following trace results: charCode: 0 char: keyCode: 17 ctrlKey: false altKey: false shiftKey: false As you can see, the only event I can capture is the release of the command key, the release of the "C" key while holding the command key isn't even sent. Has anyone successfully implemented standard copy and paste keyboard handling? Am I destined to just use the "C" key on it's own (as shown in the code example) or make a copy button available? Or do I need to create the listener manually at a higher level and pass the event down into my modular application's guts? ANSWER: I did a test where I listened for key up events on the stage and noticed that (on my Mac) I could capture control-c, control-v, etc. just fine, but anything involving command (the  key) wasn't captured until I released the command key, and then ctrlKey was false (even though the docs says that ctrlKey should be true for the command key on the Mac), and the charCode was 0. Pretty useless, in short.
[ "apache-flex", "air" ]
3
2
10,553
4
0
2008-08-28T08:34:09.087000
2008-08-28T12:32:06.563000
31,865
31,896
Good reasons for not letting the browser launch local applications
I know this might be a no-brainer, but please read on. I also know it's generally not considered a good idea, maybe the worst, to let a browser run and interact with local apps, even in an intranet context. We use Citrix for home-office, and people really like it. Now, they would like the same kind of environment at work, a nice page where every important application/document/folder is nicely arranged and classified in an orderly fashion. These folks are not particularly tech savvy; I don't even consider thinking that they could understand the difference between remote delivered applications and local ones. So, I've been asked if it's possible. Of course, it is, with IE's good ol' ActiveX controls. And I even made a working prototype (that's where it hurts). But now, I doubt. Isn't it madness to allow such 'dangerous' ActiveX controls, even in the ' local intranet ' zone? People will use the same browser to surf the web, can I fully trust IE? Isn't there a risk that Microsoft would just disable those controls in future updates/versions? What if a website, or any kind of malware, just put another site on the trust list? With that extent of control, you could as well uninstall every protection and just run amok 'till you got hanged by the IT dept. I'm about to confront my superiors with the fact that, even if they saw it is doable, it would be a very bad thing. So I'm desperately in need of good and strong arguments, because " let's don't " won't do it. Of course, if there is nothing to be scared of, that'll be nice too. But I strongly doubt that.
We use Citrix for home-office, and people really like it. Now, they would like the same kind of environment at work, a nice page where every important application/document/folder is nicely arranged and classified in an orderly fashion I haven't used Citrix very many times, but what's it got to do with executing local applications? I don't see how "People like Citrix" and "browser executing local applications" relate at all? If the people are accessing your Citrix server from home, and want the same experience in the office, then buy a cheap PC, and run the exact same Citrix software they run on their home computers. Put this computer in the corner and tell them to go use it. They'll be overjoyed. Isn't it madness to allow such 'dangerous' ActiveX controls, even in the 'local intranet' zone? People will use the same browser to surf the web, can I fully trust IE? Put it this way. IE has built-in support for AX controls. It uses it's security mechanisms to prevent them from running unless in a trusted site. By default, no sites are trusted at all. If you use IE at all then you're putting yourself at the mercy of these security mechanisms. Whether or not you tell it to trust the local intranet is beside the point, and isn't going to affect the operation of any other zones. The good old security holes that require you to reboot your computer every few weeks when MS issues a patch will continue to exist and cause problems, regardless of whether you allow ActiveX in your local intranet. Isn't there a risk that Microsoft would just disable those controls in future updates / versions? Since XP-SP2, Microsoft has been making it increasingly difficult to use ActiveX controls. I don't know how many scary looking warning messages and "This might destroy your computer" dialogs you have to click through these days to get them to run, but it's quite a few. This will only get worse over time.
Good reasons for not letting the browser launch local applications I know this might be a no-brainer, but please read on. I also know it's generally not considered a good idea, maybe the worst, to let a browser run and interact with local apps, even in an intranet context. We use Citrix for home-office, and people really like it. Now, they would like the same kind of environment at work, a nice page where every important application/document/folder is nicely arranged and classified in an orderly fashion. These folks are not particularly tech savvy; I don't even consider thinking that they could understand the difference between remote delivered applications and local ones. So, I've been asked if it's possible. Of course, it is, with IE's good ol' ActiveX controls. And I even made a working prototype (that's where it hurts). But now, I doubt. Isn't it madness to allow such 'dangerous' ActiveX controls, even in the ' local intranet ' zone? People will use the same browser to surf the web, can I fully trust IE? Isn't there a risk that Microsoft would just disable those controls in future updates/versions? What if a website, or any kind of malware, just put another site on the trust list? With that extent of control, you could as well uninstall every protection and just run amok 'till you got hanged by the IT dept. I'm about to confront my superiors with the fact that, even if they saw it is doable, it would be a very bad thing. So I'm desperately in need of good and strong arguments, because " let's don't " won't do it. Of course, if there is nothing to be scared of, that'll be nice too. But I strongly doubt that.
TITLE: Good reasons for not letting the browser launch local applications QUESTION: I know this might be a no-brainer, but please read on. I also know it's generally not considered a good idea, maybe the worst, to let a browser run and interact with local apps, even in an intranet context. We use Citrix for home-office, and people really like it. Now, they would like the same kind of environment at work, a nice page where every important application/document/folder is nicely arranged and classified in an orderly fashion. These folks are not particularly tech savvy; I don't even consider thinking that they could understand the difference between remote delivered applications and local ones. So, I've been asked if it's possible. Of course, it is, with IE's good ol' ActiveX controls. And I even made a working prototype (that's where it hurts). But now, I doubt. Isn't it madness to allow such 'dangerous' ActiveX controls, even in the ' local intranet ' zone? People will use the same browser to surf the web, can I fully trust IE? Isn't there a risk that Microsoft would just disable those controls in future updates/versions? What if a website, or any kind of malware, just put another site on the trust list? With that extent of control, you could as well uninstall every protection and just run amok 'till you got hanged by the IT dept. I'm about to confront my superiors with the fact that, even if they saw it is doable, it would be a very bad thing. So I'm desperately in need of good and strong arguments, because " let's don't " won't do it. Of course, if there is nothing to be scared of, that'll be nice too. But I strongly doubt that. ANSWER: We use Citrix for home-office, and people really like it. Now, they would like the same kind of environment at work, a nice page where every important application/document/folder is nicely arranged and classified in an orderly fashion I haven't used Citrix very many times, but what's it got to do with executing local applications? I don't see how "People like Citrix" and "browser executing local applications" relate at all? If the people are accessing your Citrix server from home, and want the same experience in the office, then buy a cheap PC, and run the exact same Citrix software they run on their home computers. Put this computer in the corner and tell them to go use it. They'll be overjoyed. Isn't it madness to allow such 'dangerous' ActiveX controls, even in the 'local intranet' zone? People will use the same browser to surf the web, can I fully trust IE? Put it this way. IE has built-in support for AX controls. It uses it's security mechanisms to prevent them from running unless in a trusted site. By default, no sites are trusted at all. If you use IE at all then you're putting yourself at the mercy of these security mechanisms. Whether or not you tell it to trust the local intranet is beside the point, and isn't going to affect the operation of any other zones. The good old security holes that require you to reboot your computer every few weeks when MS issues a patch will continue to exist and cause problems, regardless of whether you allow ActiveX in your local intranet. Isn't there a risk that Microsoft would just disable those controls in future updates / versions? Since XP-SP2, Microsoft has been making it increasingly difficult to use ActiveX controls. I don't know how many scary looking warning messages and "This might destroy your computer" dialogs you have to click through these days to get them to run, but it's quite a few. This will only get worse over time.
[ "security", "internet-explorer", "activex", "intranet" ]
1
4
3,265
3
0
2008-08-28T08:50:20.933000
2008-08-28T09:14:14.247000
31,867
32,062
Are there any examples where we *need* protected inheritance in C++?
While I've seen rare cases where private inheritance was needed, I've never encountered a case where protected inheritance is needed. Does someone have an example?
People here seem to mistake Protected class inheritance and Protected methods. FWIW, I've never seen anyone use protected class inheritance, and if I remember correctly I think Stroustrup even considered the "protected" level to be a mistake in c++. There's precious little you cannot do if you remove that protection level and only rely on public and private.
Are there any examples where we *need* protected inheritance in C++? While I've seen rare cases where private inheritance was needed, I've never encountered a case where protected inheritance is needed. Does someone have an example?
TITLE: Are there any examples where we *need* protected inheritance in C++? QUESTION: While I've seen rare cases where private inheritance was needed, I've never encountered a case where protected inheritance is needed. Does someone have an example? ANSWER: People here seem to mistake Protected class inheritance and Protected methods. FWIW, I've never seen anyone use protected class inheritance, and if I remember correctly I think Stroustrup even considered the "protected" level to be a mistake in c++. There's precious little you cannot do if you remove that protection level and only rely on public and private.
[ "c++", "oop", "inheritance" ]
14
13
1,970
3
0
2008-08-28T08:52:55.843000
2008-08-28T11:57:18.053000
31,868
34,274
Upload a file to SharePoint through the built-in web services
What is the best way to upload a file to a Document Library on a SharePoint server through the built-in web services that version WSS 3.0 exposes? Following the two initial answers... We definitely need to use the Web Service layer as we will be making these calls from remote client applications. The WebDAV method would work for us, but we would prefer to be consistent with the web service integration method. There is additionally a web service to upload files, painful but works all the time. Are you referring to the “Copy” service? We have been successful with this service’s CopyIntoItems method. Would this be the recommended way to upload a file to Document Libraries using only the WSS web service API? I have posted our code as a suggested answer.
Example of using the WSS "Copy" Web service to upload a document to a library... public static void UploadFile2007(string destinationUrl, byte[] fileData) { // List of desination Urls, Just one in this example. string[] destinationUrls = { Uri.EscapeUriString(destinationUrl) }; // Empty Field Information. This can be populated but not for this example. SharePoint2007CopyService.FieldInformation information = new SharePoint2007CopyService.FieldInformation(); SharePoint2007CopyService.FieldInformation[] info = { information }; // To receive the result Xml. SharePoint2007CopyService.CopyResult[] result; // Create the Copy web service instance configured from the web.config file. SharePoint2007CopyService.CopySoapClient CopyService2007 = new CopySoapClient("CopySoap"); CopyService2007.ClientCredentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials; CopyService2007.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Delegation; CopyService2007.CopyIntoItems(destinationUrl, destinationUrls, info, fileData, out result); if (result[0].ErrorCode!= SharePoint2007CopyService.CopyErrorCode.Success) { //... } }
Upload a file to SharePoint through the built-in web services What is the best way to upload a file to a Document Library on a SharePoint server through the built-in web services that version WSS 3.0 exposes? Following the two initial answers... We definitely need to use the Web Service layer as we will be making these calls from remote client applications. The WebDAV method would work for us, but we would prefer to be consistent with the web service integration method. There is additionally a web service to upload files, painful but works all the time. Are you referring to the “Copy” service? We have been successful with this service’s CopyIntoItems method. Would this be the recommended way to upload a file to Document Libraries using only the WSS web service API? I have posted our code as a suggested answer.
TITLE: Upload a file to SharePoint through the built-in web services QUESTION: What is the best way to upload a file to a Document Library on a SharePoint server through the built-in web services that version WSS 3.0 exposes? Following the two initial answers... We definitely need to use the Web Service layer as we will be making these calls from remote client applications. The WebDAV method would work for us, but we would prefer to be consistent with the web service integration method. There is additionally a web service to upload files, painful but works all the time. Are you referring to the “Copy” service? We have been successful with this service’s CopyIntoItems method. Would this be the recommended way to upload a file to Document Libraries using only the WSS web service API? I have posted our code as a suggested answer. ANSWER: Example of using the WSS "Copy" Web service to upload a document to a library... public static void UploadFile2007(string destinationUrl, byte[] fileData) { // List of desination Urls, Just one in this example. string[] destinationUrls = { Uri.EscapeUriString(destinationUrl) }; // Empty Field Information. This can be populated but not for this example. SharePoint2007CopyService.FieldInformation information = new SharePoint2007CopyService.FieldInformation(); SharePoint2007CopyService.FieldInformation[] info = { information }; // To receive the result Xml. SharePoint2007CopyService.CopyResult[] result; // Create the Copy web service instance configured from the web.config file. SharePoint2007CopyService.CopySoapClient CopyService2007 = new CopySoapClient("CopySoap"); CopyService2007.ClientCredentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials; CopyService2007.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Delegation; CopyService2007.CopyIntoItems(destinationUrl, destinationUrls, info, fileData, out result); if (result[0].ErrorCode!= SharePoint2007CopyService.CopyErrorCode.Success) { //... } }
[ "sharepoint", "wss" ]
31
17
65,878
7
0
2008-08-28T08:53:00.507000
2008-08-29T09:44:37.397000
31,870
31,873
Using an HTML entity in XSLT (e.g. &nbsp;)
What is the best way to include an html entity in XSLT? this one returns a XsltParseError
You can use CDATA section &nbsp; or you can describe in local DTD: ]> or just use instead of
Using an HTML entity in XSLT (e.g. &nbsp;) What is the best way to include an html entity in XSLT? this one returns a XsltParseError
TITLE: Using an HTML entity in XSLT (e.g. &nbsp;) QUESTION: What is the best way to include an html entity in XSLT? this one returns a XsltParseError ANSWER: You can use CDATA section &nbsp; or you can describe in local DTD: ]> or just use instead of
[ "xslt" ]
68
128
65,148
11
0
2008-08-28T08:55:34.697000
2008-08-28T09:02:13.060000
31,871
34,373
WSACancelBlockingCall exception
Ok, I have a strange exception thrown from my code that's been bothering me for ages. System.Net.Sockets.SocketException: A blocking operation was interrupted by a call to WSACancelBlockingCall at System.Net.Sockets.Socket.Accept() at System.Net.Sockets.TcpListener.AcceptTcpClient() MSDN isn't terribly helpful on this: http://msdn.microsoft.com/en-us/library/ms741547(VS.85).aspx and I don't even know how to begin troubleshooting this one. It's only thrown 4 or 5 times a day, and never in our test environment. Only in production sites, and on ALL production sites. I've found plenty of posts asking about this exception, but no actual definitive answers on what is causing it, and how to handle or prevent it. The code runs in a separate background thread, the method starts: public virtual void Startup() { TcpListener serverSocket= new TcpListener(new IPEndPoint(bindAddress, port)); serverSocket.Start(); then I run a loop putting all new connections as jobs in a separate thread pool. It gets more complicated because of the app architecture, but basically: while (( socket = serverSocket.AcceptTcpClient())!=null) //Funny exception here { connectionHandler = new ConnectionHandler(socket, mappingStrategy); pool.AddJob(connectionHandler); } } From there, the pool has it's own threads that take care of each job in it's own thread, separately. My understanding is that AcceptTcpClient() is a blocking call, and that somehow winsock is telling the thread to stop blocking and continue execution.. but why? And what am I supposed to do? Just catch the exception and ignore it? Well, I do think some other thread is closing the socket, but it's certainly not from my code. What I would like to know is: is this socket closed by the connecting client (on the other side of the socket) or is it closed by my server. Because as it is at this moment, whenever this exception occurs, it shutsdown my listening port, effectively closing my service. If this is done from a remote location, then it's a major problem. Alternatively, could this be simply the IIS server shutting down my application, and thus cancelling all my background threads and blocking methods?
Is it possible that the serverSocket is being closed from another thread? That will cause this exception.
WSACancelBlockingCall exception Ok, I have a strange exception thrown from my code that's been bothering me for ages. System.Net.Sockets.SocketException: A blocking operation was interrupted by a call to WSACancelBlockingCall at System.Net.Sockets.Socket.Accept() at System.Net.Sockets.TcpListener.AcceptTcpClient() MSDN isn't terribly helpful on this: http://msdn.microsoft.com/en-us/library/ms741547(VS.85).aspx and I don't even know how to begin troubleshooting this one. It's only thrown 4 or 5 times a day, and never in our test environment. Only in production sites, and on ALL production sites. I've found plenty of posts asking about this exception, but no actual definitive answers on what is causing it, and how to handle or prevent it. The code runs in a separate background thread, the method starts: public virtual void Startup() { TcpListener serverSocket= new TcpListener(new IPEndPoint(bindAddress, port)); serverSocket.Start(); then I run a loop putting all new connections as jobs in a separate thread pool. It gets more complicated because of the app architecture, but basically: while (( socket = serverSocket.AcceptTcpClient())!=null) //Funny exception here { connectionHandler = new ConnectionHandler(socket, mappingStrategy); pool.AddJob(connectionHandler); } } From there, the pool has it's own threads that take care of each job in it's own thread, separately. My understanding is that AcceptTcpClient() is a blocking call, and that somehow winsock is telling the thread to stop blocking and continue execution.. but why? And what am I supposed to do? Just catch the exception and ignore it? Well, I do think some other thread is closing the socket, but it's certainly not from my code. What I would like to know is: is this socket closed by the connecting client (on the other side of the socket) or is it closed by my server. Because as it is at this moment, whenever this exception occurs, it shutsdown my listening port, effectively closing my service. If this is done from a remote location, then it's a major problem. Alternatively, could this be simply the IIS server shutting down my application, and thus cancelling all my background threads and blocking methods?
TITLE: WSACancelBlockingCall exception QUESTION: Ok, I have a strange exception thrown from my code that's been bothering me for ages. System.Net.Sockets.SocketException: A blocking operation was interrupted by a call to WSACancelBlockingCall at System.Net.Sockets.Socket.Accept() at System.Net.Sockets.TcpListener.AcceptTcpClient() MSDN isn't terribly helpful on this: http://msdn.microsoft.com/en-us/library/ms741547(VS.85).aspx and I don't even know how to begin troubleshooting this one. It's only thrown 4 or 5 times a day, and never in our test environment. Only in production sites, and on ALL production sites. I've found plenty of posts asking about this exception, but no actual definitive answers on what is causing it, and how to handle or prevent it. The code runs in a separate background thread, the method starts: public virtual void Startup() { TcpListener serverSocket= new TcpListener(new IPEndPoint(bindAddress, port)); serverSocket.Start(); then I run a loop putting all new connections as jobs in a separate thread pool. It gets more complicated because of the app architecture, but basically: while (( socket = serverSocket.AcceptTcpClient())!=null) //Funny exception here { connectionHandler = new ConnectionHandler(socket, mappingStrategy); pool.AddJob(connectionHandler); } } From there, the pool has it's own threads that take care of each job in it's own thread, separately. My understanding is that AcceptTcpClient() is a blocking call, and that somehow winsock is telling the thread to stop blocking and continue execution.. but why? And what am I supposed to do? Just catch the exception and ignore it? Well, I do think some other thread is closing the socket, but it's certainly not from my code. What I would like to know is: is this socket closed by the connecting client (on the other side of the socket) or is it closed by my server. Because as it is at this moment, whenever this exception occurs, it shutsdown my listening port, effectively closing my service. If this is done from a remote location, then it's a major problem. Alternatively, could this be simply the IIS server shutting down my application, and thus cancelling all my background threads and blocking methods? ANSWER: Is it possible that the serverSocket is being closed from another thread? That will cause this exception.
[ "c#", "multithreading", "sockets", "socketexception" ]
54
55
110,779
6
0
2008-08-28T08:59:07.527000
2008-08-29T11:14:51.233000
31,875
31,887
Is there a simple, elegant way to define singletons?
There seem to be many ways to define singletons in Python. Is there a consensus opinion on Stack Overflow?
I don't really see the need, as a module with functions (and not a class) would serve well as a singleton. All its variables would be bound to the module, which could not be instantiated repeatedly anyway. If you do wish to use a class, there is no way of creating private classes or private constructors in Python, so you can't protect against multiple instantiations, other than just via convention in use of your API. I would still just put methods in a module, and consider the module as the singleton.
Is there a simple, elegant way to define singletons? There seem to be many ways to define singletons in Python. Is there a consensus opinion on Stack Overflow?
TITLE: Is there a simple, elegant way to define singletons? QUESTION: There seem to be many ways to define singletons in Python. Is there a consensus opinion on Stack Overflow? ANSWER: I don't really see the need, as a module with functions (and not a class) would serve well as a singleton. All its variables would be bound to the module, which could not be instantiated repeatedly anyway. If you do wish to use a class, there is no way of creating private classes or private constructors in Python, so you can't protect against multiple instantiations, other than just via convention in use of your API. I would still just put methods in a module, and consider the module as the singleton.
[ "python", "design-patterns", "singleton" ]
536
435
465,960
21
0
2008-08-28T09:03:09.827000
2008-08-28T09:10:12.743000
31,882
31,983
(Why) should I use obfuscation?
It seems to me obfuscation is an idea that falls somewhere in the "security by obscurity" or "false sense of protection" camp. To protect intellectual property, there's copyright; to prevent security issues from being found, there's fixing those issues. In short, I regard it as a technical solution to a social problem. Those almost never work. However, I seem to be the only one in our dev team to feel that way, so I'm either wrong, or just need convincing arguments. Our product uses.NET, and one dev suggested.NET Reactor (which, incidentally, was suggested in this SO thread as well )..NET Reactor completely stops any decompiling by mixing any pure.NET assembly (written in C#, VB.NET, Delphi.NET, J#, MSIL...) with native machine code. So, basically, you throw all advantages of bytecode away in one go? Are there good engineering benefits to obfuscation?
I posted a question which might help you as it discusses some of the issues: should-i-be-worried-about-obfuscating-my-net-code
(Why) should I use obfuscation? It seems to me obfuscation is an idea that falls somewhere in the "security by obscurity" or "false sense of protection" camp. To protect intellectual property, there's copyright; to prevent security issues from being found, there's fixing those issues. In short, I regard it as a technical solution to a social problem. Those almost never work. However, I seem to be the only one in our dev team to feel that way, so I'm either wrong, or just need convincing arguments. Our product uses.NET, and one dev suggested.NET Reactor (which, incidentally, was suggested in this SO thread as well )..NET Reactor completely stops any decompiling by mixing any pure.NET assembly (written in C#, VB.NET, Delphi.NET, J#, MSIL...) with native machine code. So, basically, you throw all advantages of bytecode away in one go? Are there good engineering benefits to obfuscation?
TITLE: (Why) should I use obfuscation? QUESTION: It seems to me obfuscation is an idea that falls somewhere in the "security by obscurity" or "false sense of protection" camp. To protect intellectual property, there's copyright; to prevent security issues from being found, there's fixing those issues. In short, I regard it as a technical solution to a social problem. Those almost never work. However, I seem to be the only one in our dev team to feel that way, so I'm either wrong, or just need convincing arguments. Our product uses.NET, and one dev suggested.NET Reactor (which, incidentally, was suggested in this SO thread as well )..NET Reactor completely stops any decompiling by mixing any pure.NET assembly (written in C#, VB.NET, Delphi.NET, J#, MSIL...) with native machine code. So, basically, you throw all advantages of bytecode away in one go? Are there good engineering benefits to obfuscation? ANSWER: I posted a question which might help you as it discusses some of the issues: should-i-be-worried-about-obfuscating-my-net-code
[ ".net", "security", "obfuscation" ]
7
2
3,323
8
0
2008-08-28T09:08:43.730000
2008-08-28T10:26:47.693000
31,885
31,949
Does Visual Studio Server Explorer support custom database providers?
I had used Server Explorer and related tools for graphical database development with Microsoft SQL Server in some of my learning projects - and it was a great experience. However, in my work I deal with Oracle DB and SQLite and my hobby projects use MySQL (because they are hosted on Linux). Is there a way to leverage the database-related tools in Visual Studio with other database providers?
Here is instructions on how to connect to your MySQL database from Visual Studio: To make the connection in server explorer you need to do the following: first of all you need to install the MyODBC connector 3.51 (or latest) on the development machine (NB. you can find this at http://www.mysql.com/products/connector/odbc/ ) Create a datasource in Control Panel/Administrative Tools with a connection to your database. This data source is going to be used purely for Server Manager and you dont need to worry about creating the same data source on your clients PC when you have made your VS.NET application (Unless you want to) - I dont want to cover this in this answer, too long. For the purpose of this explanation I will pretend that you created a MyODBC data source called 'AADSN' to database 'noddy' on mysqlserver 'SERVER01' and have a root password of 'fred'. The server can be either the Computer Name (found in Control Panel/System/Computer Name), or alternatively it can be the IP Address. NB. Make sure that you test this connection before continuing with this explanation. open your VS.NET project go to server explorer right-click on 'Data Connections' select 'Add Connection' In DataLink Properties, go to the provider tab and select "Microsoft OLE DB Provider For ODBC drivers" Click Next If you previously created an ODBC data source then you could just select that. The disadvantage of this is that when you install your project application on the client machine, the same data source needs to be there. I prefer to use a connection string. This should look something like: DSN=AADSN;DESC=MySQL ODBC 3.51 Driver DSN;DATABASE=noddy;SERVER=SERVER01;UID=root;PASSWORD=fred;PORT=3306;SOCKET=;OPTION=11;STMT=; If you omit the password from the connection string then you must make sure that the datasource you created (AADSN) contains a password. I am not going to describe what these mean, you can look in the documentation for myodbc for that, just ensure that you get a "Connection Succeeded" message when you test the datasource.
Does Visual Studio Server Explorer support custom database providers? I had used Server Explorer and related tools for graphical database development with Microsoft SQL Server in some of my learning projects - and it was a great experience. However, in my work I deal with Oracle DB and SQLite and my hobby projects use MySQL (because they are hosted on Linux). Is there a way to leverage the database-related tools in Visual Studio with other database providers?
TITLE: Does Visual Studio Server Explorer support custom database providers? QUESTION: I had used Server Explorer and related tools for graphical database development with Microsoft SQL Server in some of my learning projects - and it was a great experience. However, in my work I deal with Oracle DB and SQLite and my hobby projects use MySQL (because they are hosted on Linux). Is there a way to leverage the database-related tools in Visual Studio with other database providers? ANSWER: Here is instructions on how to connect to your MySQL database from Visual Studio: To make the connection in server explorer you need to do the following: first of all you need to install the MyODBC connector 3.51 (or latest) on the development machine (NB. you can find this at http://www.mysql.com/products/connector/odbc/ ) Create a datasource in Control Panel/Administrative Tools with a connection to your database. This data source is going to be used purely for Server Manager and you dont need to worry about creating the same data source on your clients PC when you have made your VS.NET application (Unless you want to) - I dont want to cover this in this answer, too long. For the purpose of this explanation I will pretend that you created a MyODBC data source called 'AADSN' to database 'noddy' on mysqlserver 'SERVER01' and have a root password of 'fred'. The server can be either the Computer Name (found in Control Panel/System/Computer Name), or alternatively it can be the IP Address. NB. Make sure that you test this connection before continuing with this explanation. open your VS.NET project go to server explorer right-click on 'Data Connections' select 'Add Connection' In DataLink Properties, go to the provider tab and select "Microsoft OLE DB Provider For ODBC drivers" Click Next If you previously created an ODBC data source then you could just select that. The disadvantage of this is that when you install your project application on the client machine, the same data source needs to be there. I prefer to use a connection string. This should look something like: DSN=AADSN;DESC=MySQL ODBC 3.51 Driver DSN;DATABASE=noddy;SERVER=SERVER01;UID=root;PASSWORD=fred;PORT=3306;SOCKET=;OPTION=11;STMT=; If you omit the password from the connection string then you must make sure that the datasource you created (AADSN) contains a password. I am not going to describe what these mean, you can look in the documentation for myodbc for that, just ensure that you get a "Connection Succeeded" message when you test the datasource.
[ "c#", "mysql", "visual-studio", "oracle", "sqlite" ]
13
9
13,255
4
0
2008-08-28T09:09:58.983000
2008-08-28T10:03:04.630000
31,924
31,960
What are the best practices for JSF?
I have done Java and JSP programming in the past, but I am new to Java Server Faces and want to know if there's a set of best practices for JSF development.
Some tips: Understand the JSF request lifecycle and where your various pieces of code fit in it. Especially find out why your model values will not be updated if there are validation errors. Choose a tag library and then stick with it. Take your time to determine your needs and prototype different libraries. Mixing different taglibs may cause severe harm to your mental health.
What are the best practices for JSF? I have done Java and JSP programming in the past, but I am new to Java Server Faces and want to know if there's a set of best practices for JSF development.
TITLE: What are the best practices for JSF? QUESTION: I have done Java and JSP programming in the past, but I am new to Java Server Faces and want to know if there's a set of best practices for JSF development. ANSWER: Some tips: Understand the JSF request lifecycle and where your various pieces of code fit in it. Especially find out why your model values will not be updated if there are validation errors. Choose a tag library and then stick with it. Take your time to determine your needs and prototype different libraries. Mixing different taglibs may cause severe harm to your mental health.
[ "java", "jsf" ]
11
11
11,292
8
0
2008-08-28T09:47:18.270000
2008-08-28T10:10:08.560000
31,930
32,063
Sending e-mail from a Custom SQL Server Reporting Services Delivery Extension
I've developed my own delivery extension for Reporting Services 2005, to integrate this with our SaaS marketing solution. It takes the subscription, and takes a snapshot of the report with a custom set of parameters. It then renders the report, sends an e-mail with a link and the report attached as XLS. Everything works fine, until mail delivery... Here's my code for sending e-mail: public static List SendMail(SubscriptionData data, Stream reportStream, string reportName, string smptServerHostname, int smtpServerPort) { List failedRecipients = new List (); MailMessage emailMessage = new MailMessage(data.ReplyTo, data.To); emailMessage.Priority = data.Priority; emailMessage.Subject = data.Subject; emailMessage.IsBodyHtml = false; emailMessage.Body = data.Comment; if (reportStream!= null) { Attachment reportAttachment = new Attachment(reportStream, reportName); emailMessage.Attachments.Add(reportAttachment); reportStream.Dispose(); } try { SmtpClient smtp = new SmtpClient(smptServerHostname, smtpServerPort); // Send the MailMessage smtp.Send(emailMessage); } catch (SmtpFailedRecipientsException ex) { // Delivery failed for the recipient. Add the e-mail address to the failedRecipients List failedRecipients.Add(ex.FailedRecipient); } catch (SmtpFailedRecipientException ex) { // Delivery failed for the recipient. Add the e-mail address to the failedRecipients List failedRecipients.Add(ex.FailedRecipient); } catch (SmtpException ex) { throw ex; } catch (Exception ex) { throw ex; } // Return the List of failed recipient e-mail addresses, so the client can maintain its list. return failedRecipients; } Values for SmtpServerHostname is localhost, and port is 25. I veryfied that I can actually send mail, by using Telnet. And it works. Here's the error message I get from SSRS: ReportingServicesService!notification!4!08/28/2008-11:26:17:: Notification 6ab32b8d-296e-47a2-8d96-09e81222985c completed. Success: False, Status: Exception Message: Failure sending mail. Stacktrace: at MyDeliveryExtension.MailDelivery.SendMail(SubscriptionData data, Stream reportStream, String reportName, String smptServerHostname, Int32 smtpServerPort) in C:\inetpub\wwwroot\CustomReporting\MyDeliveryExtension\MailDelivery.cs:line 48 at MyDeliveryExtension.MyDelivery.Deliver(Notification notification) in C:\inetpub\wwwroot\CustomReporting\MyDeliveryExtension\MyDelivery.cs:line 153, DeliveryExtension: My Delivery, Report: Clicks Development, Attempt 1 ReportingServicesService!dbpolling!4!08/28/2008-11:26:17:: NotificationPolling finished processing item 6ab32b8d-296e-47a2-8d96-09e81222985c Could this have something to do with Trust/Code Access Security? My delivery extension is granted full trust in rssrvpolicy.config: Could trust be an issue here? Another theory: SQL Server and SSRS was installed in the security context of Local System. Am I right, or is this service account restricted access to any network resource? Even its own SMTP Server? I tried changing all SQL Server Services logons to Administrator - but still without any success. I also tried logging onto the SMTP server in my code, by proviiding: NetworkCredential("Administrator", "password") and also NetworkCredential("Administrator", "password", "MyRepServer") Can anyone help here, please?
What's at: at MyDeliveryExtension.MailDelivery.SendMail(SubscriptionData data, Stream reportStream, String reportName, String smptServerHostname, Int32 smtpServerPort) in C:\inetpub\wwwroot\CustomReporting\MyDeliveryExtension\MailDelivery.cs:line 48 at MyDeliveryExtension.MyDelivery.Deliver(Notification notification) in C:\inetpub\wwwroot\CustomReporting\MyDeliveryExtension\MyDelivery.cs:line 153 Also you seem to be disposing the report stream, but that should be done by whatever opened that stream, not your method (it won't be obvious that attaching a stream disposes it). You're losing part of your stack trace due to how you re-throw exceptions. Don't throw the ex variable, just throw is enough. Try this tweak: public static List SendMail(SubscriptionData data, Stream reportStream, string reportName, string smptServerHostname, int smtpServerPort) { List failedRecipients = new List (); MailMessage emailMessage = new MailMessage(data.ReplyTo, data.To) { Priority = data.Priority, Subject = data.Subject, IsBodyHtml = false, Body = data.Comment }; if (reportStream!= null) emailMessage.Attachments.Add(new Attachment(reportStream, reportName)); try { SmtpClient smtp = new SmtpClient(smptServerHostname, smtpServerPort); // Send the MailMessage smtp.Send(emailMessage); } catch (SmtpFailedRecipientsException ex) { // Delivery failed for the recipient. Add the e-mail address to the failedRecipients List failedRecipients.Add(ex.FailedRecipient); //are you missing a loop here? only one failed address will ever be returned } catch (SmtpFailedRecipientException ex) { // Delivery failed for the recipient. Add the e-mail address to the failedRecipients List failedRecipients.Add(ex.FailedRecipient); } // Return the List of failed recipient e-mail addresses, so the client can maintain its list. return failedRecipients; }
Sending e-mail from a Custom SQL Server Reporting Services Delivery Extension I've developed my own delivery extension for Reporting Services 2005, to integrate this with our SaaS marketing solution. It takes the subscription, and takes a snapshot of the report with a custom set of parameters. It then renders the report, sends an e-mail with a link and the report attached as XLS. Everything works fine, until mail delivery... Here's my code for sending e-mail: public static List SendMail(SubscriptionData data, Stream reportStream, string reportName, string smptServerHostname, int smtpServerPort) { List failedRecipients = new List (); MailMessage emailMessage = new MailMessage(data.ReplyTo, data.To); emailMessage.Priority = data.Priority; emailMessage.Subject = data.Subject; emailMessage.IsBodyHtml = false; emailMessage.Body = data.Comment; if (reportStream!= null) { Attachment reportAttachment = new Attachment(reportStream, reportName); emailMessage.Attachments.Add(reportAttachment); reportStream.Dispose(); } try { SmtpClient smtp = new SmtpClient(smptServerHostname, smtpServerPort); // Send the MailMessage smtp.Send(emailMessage); } catch (SmtpFailedRecipientsException ex) { // Delivery failed for the recipient. Add the e-mail address to the failedRecipients List failedRecipients.Add(ex.FailedRecipient); } catch (SmtpFailedRecipientException ex) { // Delivery failed for the recipient. Add the e-mail address to the failedRecipients List failedRecipients.Add(ex.FailedRecipient); } catch (SmtpException ex) { throw ex; } catch (Exception ex) { throw ex; } // Return the List of failed recipient e-mail addresses, so the client can maintain its list. return failedRecipients; } Values for SmtpServerHostname is localhost, and port is 25. I veryfied that I can actually send mail, by using Telnet. And it works. Here's the error message I get from SSRS: ReportingServicesService!notification!4!08/28/2008-11:26:17:: Notification 6ab32b8d-296e-47a2-8d96-09e81222985c completed. Success: False, Status: Exception Message: Failure sending mail. Stacktrace: at MyDeliveryExtension.MailDelivery.SendMail(SubscriptionData data, Stream reportStream, String reportName, String smptServerHostname, Int32 smtpServerPort) in C:\inetpub\wwwroot\CustomReporting\MyDeliveryExtension\MailDelivery.cs:line 48 at MyDeliveryExtension.MyDelivery.Deliver(Notification notification) in C:\inetpub\wwwroot\CustomReporting\MyDeliveryExtension\MyDelivery.cs:line 153, DeliveryExtension: My Delivery, Report: Clicks Development, Attempt 1 ReportingServicesService!dbpolling!4!08/28/2008-11:26:17:: NotificationPolling finished processing item 6ab32b8d-296e-47a2-8d96-09e81222985c Could this have something to do with Trust/Code Access Security? My delivery extension is granted full trust in rssrvpolicy.config: Could trust be an issue here? Another theory: SQL Server and SSRS was installed in the security context of Local System. Am I right, or is this service account restricted access to any network resource? Even its own SMTP Server? I tried changing all SQL Server Services logons to Administrator - but still without any success. I also tried logging onto the SMTP server in my code, by proviiding: NetworkCredential("Administrator", "password") and also NetworkCredential("Administrator", "password", "MyRepServer") Can anyone help here, please?
TITLE: Sending e-mail from a Custom SQL Server Reporting Services Delivery Extension QUESTION: I've developed my own delivery extension for Reporting Services 2005, to integrate this with our SaaS marketing solution. It takes the subscription, and takes a snapshot of the report with a custom set of parameters. It then renders the report, sends an e-mail with a link and the report attached as XLS. Everything works fine, until mail delivery... Here's my code for sending e-mail: public static List SendMail(SubscriptionData data, Stream reportStream, string reportName, string smptServerHostname, int smtpServerPort) { List failedRecipients = new List (); MailMessage emailMessage = new MailMessage(data.ReplyTo, data.To); emailMessage.Priority = data.Priority; emailMessage.Subject = data.Subject; emailMessage.IsBodyHtml = false; emailMessage.Body = data.Comment; if (reportStream!= null) { Attachment reportAttachment = new Attachment(reportStream, reportName); emailMessage.Attachments.Add(reportAttachment); reportStream.Dispose(); } try { SmtpClient smtp = new SmtpClient(smptServerHostname, smtpServerPort); // Send the MailMessage smtp.Send(emailMessage); } catch (SmtpFailedRecipientsException ex) { // Delivery failed for the recipient. Add the e-mail address to the failedRecipients List failedRecipients.Add(ex.FailedRecipient); } catch (SmtpFailedRecipientException ex) { // Delivery failed for the recipient. Add the e-mail address to the failedRecipients List failedRecipients.Add(ex.FailedRecipient); } catch (SmtpException ex) { throw ex; } catch (Exception ex) { throw ex; } // Return the List of failed recipient e-mail addresses, so the client can maintain its list. return failedRecipients; } Values for SmtpServerHostname is localhost, and port is 25. I veryfied that I can actually send mail, by using Telnet. And it works. Here's the error message I get from SSRS: ReportingServicesService!notification!4!08/28/2008-11:26:17:: Notification 6ab32b8d-296e-47a2-8d96-09e81222985c completed. Success: False, Status: Exception Message: Failure sending mail. Stacktrace: at MyDeliveryExtension.MailDelivery.SendMail(SubscriptionData data, Stream reportStream, String reportName, String smptServerHostname, Int32 smtpServerPort) in C:\inetpub\wwwroot\CustomReporting\MyDeliveryExtension\MailDelivery.cs:line 48 at MyDeliveryExtension.MyDelivery.Deliver(Notification notification) in C:\inetpub\wwwroot\CustomReporting\MyDeliveryExtension\MyDelivery.cs:line 153, DeliveryExtension: My Delivery, Report: Clicks Development, Attempt 1 ReportingServicesService!dbpolling!4!08/28/2008-11:26:17:: NotificationPolling finished processing item 6ab32b8d-296e-47a2-8d96-09e81222985c Could this have something to do with Trust/Code Access Security? My delivery extension is granted full trust in rssrvpolicy.config: Could trust be an issue here? Another theory: SQL Server and SSRS was installed in the security context of Local System. Am I right, or is this service account restricted access to any network resource? Even its own SMTP Server? I tried changing all SQL Server Services logons to Administrator - but still without any success. I also tried logging onto the SMTP server in my code, by proviiding: NetworkCredential("Administrator", "password") and also NetworkCredential("Administrator", "password", "MyRepServer") Can anyone help here, please? ANSWER: What's at: at MyDeliveryExtension.MailDelivery.SendMail(SubscriptionData data, Stream reportStream, String reportName, String smptServerHostname, Int32 smtpServerPort) in C:\inetpub\wwwroot\CustomReporting\MyDeliveryExtension\MailDelivery.cs:line 48 at MyDeliveryExtension.MyDelivery.Deliver(Notification notification) in C:\inetpub\wwwroot\CustomReporting\MyDeliveryExtension\MyDelivery.cs:line 153 Also you seem to be disposing the report stream, but that should be done by whatever opened that stream, not your method (it won't be obvious that attaching a stream disposes it). You're losing part of your stack trace due to how you re-throw exceptions. Don't throw the ex variable, just throw is enough. Try this tweak: public static List SendMail(SubscriptionData data, Stream reportStream, string reportName, string smptServerHostname, int smtpServerPort) { List failedRecipients = new List (); MailMessage emailMessage = new MailMessage(data.ReplyTo, data.To) { Priority = data.Priority, Subject = data.Subject, IsBodyHtml = false, Body = data.Comment }; if (reportStream!= null) emailMessage.Attachments.Add(new Attachment(reportStream, reportName)); try { SmtpClient smtp = new SmtpClient(smptServerHostname, smtpServerPort); // Send the MailMessage smtp.Send(emailMessage); } catch (SmtpFailedRecipientsException ex) { // Delivery failed for the recipient. Add the e-mail address to the failedRecipients List failedRecipients.Add(ex.FailedRecipient); //are you missing a loop here? only one failed address will ever be returned } catch (SmtpFailedRecipientException ex) { // Delivery failed for the recipient. Add the e-mail address to the failedRecipients List failedRecipients.Add(ex.FailedRecipient); } // Return the List of failed recipient e-mail addresses, so the client can maintain its list. return failedRecipients; }
[ "c#", "reporting-services" ]
2
0
7,050
5
0
2008-08-28T09:50:48.183000
2008-08-28T11:57:23.917000
31,931
31,939
What's the simplest way to decrement a date in Javascript by 1 day?
I need to decrement a Javascript date by 1 day, so that it rolls back across months/years correctly. That is, if I have a date of 'Today', I want to get the date for 'Yesterday'. It always seems to take more code than necessary when I do this, so I'm wondering if there's any simpler way. What's the simplest way of doing this? [Edit: Just to avoid confusion in an answer below, this is a JavaScript question, not a Java one.]
var d = new Date(); d.setDate(d.getDate() - 1); console.log(d);
What's the simplest way to decrement a date in Javascript by 1 day? I need to decrement a Javascript date by 1 day, so that it rolls back across months/years correctly. That is, if I have a date of 'Today', I want to get the date for 'Yesterday'. It always seems to take more code than necessary when I do this, so I'm wondering if there's any simpler way. What's the simplest way of doing this? [Edit: Just to avoid confusion in an answer below, this is a JavaScript question, not a Java one.]
TITLE: What's the simplest way to decrement a date in Javascript by 1 day? QUESTION: I need to decrement a Javascript date by 1 day, so that it rolls back across months/years correctly. That is, if I have a date of 'Today', I want to get the date for 'Yesterday'. It always seems to take more code than necessary when I do this, so I'm wondering if there's any simpler way. What's the simplest way of doing this? [Edit: Just to avoid confusion in an answer below, this is a JavaScript question, not a Java one.] ANSWER: var d = new Date(); d.setDate(d.getDate() - 1); console.log(d);
[ "javascript", "browser", "date" ]
24
36
15,085
7
0
2008-08-28T09:50:48.370000
2008-08-28T09:56:01.370000
31,935
32,784
ASP.NET AJAX: Firing an UpdatePanel after the page load is complete
I'm sure this is easy but I can't figure it out: I have an ASP.NET page with some UpdatePanels on it. I want the page to completely load with some 'Please wait' text in the UpdatePanels. Then once the page is completely loaded I want to call a code-behind function to update the UpdatePanel. Any ideas as to what combination of Javascript and code-behind I need to implement this idea? SAL PS: I've tried putting my function call in the Page_Load but then code is run before the page is delivered and, as the function I want to run takes some time, the page simply takes too long to load up.
Use a timer control that will be fired after a certain number of milliseconds (for page to load). In the timer tick event refresh the update panel.
ASP.NET AJAX: Firing an UpdatePanel after the page load is complete I'm sure this is easy but I can't figure it out: I have an ASP.NET page with some UpdatePanels on it. I want the page to completely load with some 'Please wait' text in the UpdatePanels. Then once the page is completely loaded I want to call a code-behind function to update the UpdatePanel. Any ideas as to what combination of Javascript and code-behind I need to implement this idea? SAL PS: I've tried putting my function call in the Page_Load but then code is run before the page is delivered and, as the function I want to run takes some time, the page simply takes too long to load up.
TITLE: ASP.NET AJAX: Firing an UpdatePanel after the page load is complete QUESTION: I'm sure this is easy but I can't figure it out: I have an ASP.NET page with some UpdatePanels on it. I want the page to completely load with some 'Please wait' text in the UpdatePanels. Then once the page is completely loaded I want to call a code-behind function to update the UpdatePanel. Any ideas as to what combination of Javascript and code-behind I need to implement this idea? SAL PS: I've tried putting my function call in the Page_Load but then code is run before the page is delivered and, as the function I want to run takes some time, the page simply takes too long to load up. ANSWER: Use a timer control that will be fired after a certain number of milliseconds (for page to load). In the timer tick event refresh the update panel.
[ "asp.net", "javascript", "asp.net-ajax" ]
9
1
25,655
8
0
2008-08-28T09:53:22.140000
2008-08-28T16:49:36.197000
32,000
32,005
C# - SQLClient - Simplest INSERT
I'm basically trying to figure out the simplest way to perform your basic insert operation in C#.NET using the SqlClient namespace. I'm using SqlConnection for my db link, I've already had success executing some reads, and I want to know the simplest way to insert data. I'm finding what seem to be pretty verbose methods when I google.
using (var conn = new SqlConnection(yourConnectionString)) { var cmd = new SqlCommand("insert into Foo values (@bar)", conn); cmd.Parameters.AddWithValue("@bar", 17); conn.Open(); cmd.ExecuteNonQuery(); }
C# - SQLClient - Simplest INSERT I'm basically trying to figure out the simplest way to perform your basic insert operation in C#.NET using the SqlClient namespace. I'm using SqlConnection for my db link, I've already had success executing some reads, and I want to know the simplest way to insert data. I'm finding what seem to be pretty verbose methods when I google.
TITLE: C# - SQLClient - Simplest INSERT QUESTION: I'm basically trying to figure out the simplest way to perform your basic insert operation in C#.NET using the SqlClient namespace. I'm using SqlConnection for my db link, I've already had success executing some reads, and I want to know the simplest way to insert data. I'm finding what seem to be pretty verbose methods when I google. ANSWER: using (var conn = new SqlConnection(yourConnectionString)) { var cmd = new SqlCommand("insert into Foo values (@bar)", conn); cmd.Parameters.AddWithValue("@bar", 17); conn.Open(); cmd.ExecuteNonQuery(); }
[ "c#", "sql", "sql-server", "t-sql" ]
10
20
17,223
3
0
2008-08-28T10:37:39.367000
2008-08-28T10:48:25.767000
32,001
32,057
Resettable Java Timer
I'd like to have a java.utils.Timer with a resettable time in java.I need to set a once off event to occur in X seconds. If nothing happens in between the time the timer was created and X seconds, then the event occurs as normal. If, however, before X seconds has elapsed, I decide that the event should occur after Y seconds instead, then I want to be able to tell the timer to reset its time so that the event occurs in Y seconds. E.g. the timer should be able to do something like: Timer timer = new Timer(); timer.schedule(timerTask, 5000); //Timer starts in 5000 ms (X) //At some point between 0 and 5000 ms... setNewTime(timer, 8000); //timerTask will fire in 8000ms from NOW (Y). I don't see a way to do this using the utils timer, as if you call cancel() you cannot schedule it again. The only way I've come close to replicating this behavior is by using javax.swing.Timer and involves stopping the origional timer, and creating a new one. i.e.: timer.stop(); timer = new Timer(8000, ActionListener); timer.start(); Is there an easier way??
According to the Timer documentation, in Java 1.5 onwards, you should prefer the ScheduledThreadPoolExecutor instead. (You may like to create this executor using Executors.newSingleThreadScheduledExecutor() for ease of use; it creates something much like a Timer.) The cool thing is, when you schedule a task (by calling schedule() ), it returns a ScheduledFuture object. You can use this to cancel the scheduled task. You're then free to submit a new task with a different triggering time. ETA: The Timer documentation linked to doesn't say anything about ScheduledThreadPoolExecutor, however the OpenJDK version had this to say: Java 5.0 introduced the java.util.concurrent package and one of the concurrency utilities therein is the ScheduledThreadPoolExecutor which is a thread pool for repeatedly executing tasks at a given rate or delay. It is effectively a more versatile replacement for the Timer / TimerTask combination, as it allows multiple service threads, accepts various time units, and doesn't require subclassing TimerTask (just implement Runnable ). Configuring ScheduledThreadPoolExecutor with one thread makes it equivalent to Timer.
Resettable Java Timer I'd like to have a java.utils.Timer with a resettable time in java.I need to set a once off event to occur in X seconds. If nothing happens in between the time the timer was created and X seconds, then the event occurs as normal. If, however, before X seconds has elapsed, I decide that the event should occur after Y seconds instead, then I want to be able to tell the timer to reset its time so that the event occurs in Y seconds. E.g. the timer should be able to do something like: Timer timer = new Timer(); timer.schedule(timerTask, 5000); //Timer starts in 5000 ms (X) //At some point between 0 and 5000 ms... setNewTime(timer, 8000); //timerTask will fire in 8000ms from NOW (Y). I don't see a way to do this using the utils timer, as if you call cancel() you cannot schedule it again. The only way I've come close to replicating this behavior is by using javax.swing.Timer and involves stopping the origional timer, and creating a new one. i.e.: timer.stop(); timer = new Timer(8000, ActionListener); timer.start(); Is there an easier way??
TITLE: Resettable Java Timer QUESTION: I'd like to have a java.utils.Timer with a resettable time in java.I need to set a once off event to occur in X seconds. If nothing happens in between the time the timer was created and X seconds, then the event occurs as normal. If, however, before X seconds has elapsed, I decide that the event should occur after Y seconds instead, then I want to be able to tell the timer to reset its time so that the event occurs in Y seconds. E.g. the timer should be able to do something like: Timer timer = new Timer(); timer.schedule(timerTask, 5000); //Timer starts in 5000 ms (X) //At some point between 0 and 5000 ms... setNewTime(timer, 8000); //timerTask will fire in 8000ms from NOW (Y). I don't see a way to do this using the utils timer, as if you call cancel() you cannot schedule it again. The only way I've come close to replicating this behavior is by using javax.swing.Timer and involves stopping the origional timer, and creating a new one. i.e.: timer.stop(); timer = new Timer(8000, ActionListener); timer.start(); Is there an easier way?? ANSWER: According to the Timer documentation, in Java 1.5 onwards, you should prefer the ScheduledThreadPoolExecutor instead. (You may like to create this executor using Executors.newSingleThreadScheduledExecutor() for ease of use; it creates something much like a Timer.) The cool thing is, when you schedule a task (by calling schedule() ), it returns a ScheduledFuture object. You can use this to cancel the scheduled task. You're then free to submit a new task with a different triggering time. ETA: The Timer documentation linked to doesn't say anything about ScheduledThreadPoolExecutor, however the OpenJDK version had this to say: Java 5.0 introduced the java.util.concurrent package and one of the concurrency utilities therein is the ScheduledThreadPoolExecutor which is a thread pool for repeatedly executing tasks at a given rate or delay. It is effectively a more versatile replacement for the Timer / TimerTask combination, as it allows multiple service threads, accepts various time units, and doesn't require subclassing TimerTask (just implement Runnable ). Configuring ScheduledThreadPoolExecutor with one thread makes it equivalent to Timer.
[ "java", "timer" ]
40
50
47,939
8
0
2008-08-28T10:38:03.687000
2008-08-28T11:52:00.717000
32,003
32,019
Tool for commandline "bookmarks" on windows?
Im searching a tool which allows me to specify some folders as "bookmarks" and than access them on the commandline (on Windows XP) via a keyword. Something like: C:\> go home D:\profiles\user\home\> go svn-project1 D:\projects\project1\svn\branch\src\> I'm currently using a bunch of batch files, but editing them by hand is a daunting task. On Linux there is cdargs or shell bookmarks but I haven't found something on windows. Thanks for the Powershell suggestion, but I'm not allowed to install it on my box at work, so it should be a "classic" cmd.exe solution.
What you are looking for is called DOSKEY You can use the doskey command to create macros in the command interpreter. For example: doskey mcd=mkdir "$*"$Tpushd "$*" creates a new command "mcd" that creates a new directory and then changes to that directory (I prefer "pushd" to "cd" in this case because it lets me use "popd" later to go back to where I was before) The $* will be replaced with the remainder of the command line after the macro, and the $T is used to delimit the two different commands that I want to evaluate. If I typed: mcd foo/bar at the command line, it would be equivalent to: mkdir "foo/bar"&pushd "foo/bar" The next step is to create a file that contains a set of macros which you can then import by using the /macrofile switch. I have a file (c:\tools\doskey.macros) which defines the commands that I regularly use. Each macro should be specified on a line with the same syntax as above. But you don't want to have to manually import your macros every time you launch a new command interpreter, to make it happen automatically, just open up the registry key HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun and set the value to be doskey /macrofile "c:\tools\doskey.macro". Doing this will make sure that your macros are automatically predefined every time you start a new interpreter. Extra thoughts: - If you want to do other things in AutoRun (like set environment parameters), you can delimit the commands with the ampersand. Mine looks like: set root=c:\SomeDir&doskey /macrofile "c:\tools\doskey.macros" - If you prefer that your AutoRun settings be set per-user, you can use the HKCU node instead of HKLM. - You can also use doskey to control things like the size of the command history. - I like to end all of my navigation macros with \$* so that I can chain things together - Be careful to add quotes as appropriate in your macros if you want to be able to handle paths with spaces in them.
Tool for commandline "bookmarks" on windows? Im searching a tool which allows me to specify some folders as "bookmarks" and than access them on the commandline (on Windows XP) via a keyword. Something like: C:\> go home D:\profiles\user\home\> go svn-project1 D:\projects\project1\svn\branch\src\> I'm currently using a bunch of batch files, but editing them by hand is a daunting task. On Linux there is cdargs or shell bookmarks but I haven't found something on windows. Thanks for the Powershell suggestion, but I'm not allowed to install it on my box at work, so it should be a "classic" cmd.exe solution.
TITLE: Tool for commandline "bookmarks" on windows? QUESTION: Im searching a tool which allows me to specify some folders as "bookmarks" and than access them on the commandline (on Windows XP) via a keyword. Something like: C:\> go home D:\profiles\user\home\> go svn-project1 D:\projects\project1\svn\branch\src\> I'm currently using a bunch of batch files, but editing them by hand is a daunting task. On Linux there is cdargs or shell bookmarks but I haven't found something on windows. Thanks for the Powershell suggestion, but I'm not allowed to install it on my box at work, so it should be a "classic" cmd.exe solution. ANSWER: What you are looking for is called DOSKEY You can use the doskey command to create macros in the command interpreter. For example: doskey mcd=mkdir "$*"$Tpushd "$*" creates a new command "mcd" that creates a new directory and then changes to that directory (I prefer "pushd" to "cd" in this case because it lets me use "popd" later to go back to where I was before) The $* will be replaced with the remainder of the command line after the macro, and the $T is used to delimit the two different commands that I want to evaluate. If I typed: mcd foo/bar at the command line, it would be equivalent to: mkdir "foo/bar"&pushd "foo/bar" The next step is to create a file that contains a set of macros which you can then import by using the /macrofile switch. I have a file (c:\tools\doskey.macros) which defines the commands that I regularly use. Each macro should be specified on a line with the same syntax as above. But you don't want to have to manually import your macros every time you launch a new command interpreter, to make it happen automatically, just open up the registry key HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun and set the value to be doskey /macrofile "c:\tools\doskey.macro". Doing this will make sure that your macros are automatically predefined every time you start a new interpreter. Extra thoughts: - If you want to do other things in AutoRun (like set environment parameters), you can delimit the commands with the ampersand. Mine looks like: set root=c:\SomeDir&doskey /macrofile "c:\tools\doskey.macros" - If you prefer that your AutoRun settings be set per-user, you can use the HKCU node instead of HKLM. - You can also use doskey to control things like the size of the command history. - I like to end all of my navigation macros with \$* so that I can chain things together - Be careful to add quotes as appropriate in your macros if you want to be able to handle paths with spaces in them.
[ "command-line" ]
12
25
7,140
8
0
2008-08-28T10:47:38.063000
2008-08-28T11:23:38.290000
32,010
32,021
Is regex case insensitivity slower?
Source RegexOptions.IgnoreCase is more expensive than I would have thought (eg, should be barely measurable) Assuming that this applies to PHP, Python, Perl, Ruby etc as well as C# (which is what I assume Jeff was using), how much of a slowdown is it and will I incur a similar penalty with /[a-zA-z]/ as I will with /[a-z]/i?
Yes, [A-Za-z] will be much faster than setting the RegexOptions.IgnoreCase, largely because of Unicode strings. But it's also much more limiting -- [A-Za-z] does not match accented international characters, it's literally the A-Za-z ASCII set and nothing more. I don't know if you saw Tim Bray's answer to my message, but it's a good one: One of the trickiest issues in internationalized search is upper and lower case. This notion of case is limited to languages written in the Latin, Greek, and Cyrillic character sets. English-speakers naturally expect search to be case-insensitive if only because they’re lazy: if Nadia Jones wants to look herself up on Google she’ll probably just type in nadia jones and expect the system to take care of it. So it’s fairly common for search systems to “normalize” words by converting them all to lower- or upper-case, both for indexing and queries. The trouble is that the mapping between cases is not always as straightforward as it is in English. For example, the German lower-case character “ß” becomes “SS” when upper-cased, and good old capital “I” when down-cased in Turkish becomes the dotless “ı” (yes, they have “i”, its upper-case version is “İ”). I have read (but not verified first-hand) that the rules for upcasing accented characters such “é” are different in France and Québec. One of the results of all this is that software such as java.String.toLowerCase() tends to run astonishingly slow as it tries to work around all these corner-cases. http://www.tbray.org/ongoing/When/200x/2003/10/11/SearchI18n
Is regex case insensitivity slower? Source RegexOptions.IgnoreCase is more expensive than I would have thought (eg, should be barely measurable) Assuming that this applies to PHP, Python, Perl, Ruby etc as well as C# (which is what I assume Jeff was using), how much of a slowdown is it and will I incur a similar penalty with /[a-zA-z]/ as I will with /[a-z]/i?
TITLE: Is regex case insensitivity slower? QUESTION: Source RegexOptions.IgnoreCase is more expensive than I would have thought (eg, should be barely measurable) Assuming that this applies to PHP, Python, Perl, Ruby etc as well as C# (which is what I assume Jeff was using), how much of a slowdown is it and will I incur a similar penalty with /[a-zA-z]/ as I will with /[a-z]/i? ANSWER: Yes, [A-Za-z] will be much faster than setting the RegexOptions.IgnoreCase, largely because of Unicode strings. But it's also much more limiting -- [A-Za-z] does not match accented international characters, it's literally the A-Za-z ASCII set and nothing more. I don't know if you saw Tim Bray's answer to my message, but it's a good one: One of the trickiest issues in internationalized search is upper and lower case. This notion of case is limited to languages written in the Latin, Greek, and Cyrillic character sets. English-speakers naturally expect search to be case-insensitive if only because they’re lazy: if Nadia Jones wants to look herself up on Google she’ll probably just type in nadia jones and expect the system to take care of it. So it’s fairly common for search systems to “normalize” words by converting them all to lower- or upper-case, both for indexing and queries. The trouble is that the mapping between cases is not always as straightforward as it is in English. For example, the German lower-case character “ß” becomes “SS” when upper-cased, and good old capital “I” when down-cased in Turkish becomes the dotless “ı” (yes, they have “i”, its upper-case version is “İ”). I have read (but not verified first-hand) that the rules for upcasing accented characters such “é” are different in France and Québec. One of the results of all this is that software such as java.String.toLowerCase() tends to run astonishingly slow as it tries to work around all these corner-cases. http://www.tbray.org/ongoing/When/200x/2003/10/11/SearchI18n
[ "regex", "language-agnostic" ]
15
22
3,948
3
0
2008-08-28T10:55:17.950000
2008-08-28T11:23:59.427000
32,020
32,032
Is soapUI the best web services testing tool/client/framework?
I have been working on a web services related project for about the last year. Our team found soapUI near the start of our project and we have been mostly (*) satisfied with it (the free version, that is). My question is: are there other tools/clients/frameworks that you have used/currently use for web services testing and would recommend? (*) There are some weird GUI glitches that appear once in a while. As is mentioned by some of the answers, we attributed this to a memory leak.
I use soapUI, and it's generally pretty good. Be aware that it seems to leak memory, and eventually it will no longer save your project, so save regularly! This is about the only hassle I have with it (other than the general ugliness that almost every Java application has!), and I can't live without it.
Is soapUI the best web services testing tool/client/framework? I have been working on a web services related project for about the last year. Our team found soapUI near the start of our project and we have been mostly (*) satisfied with it (the free version, that is). My question is: are there other tools/clients/frameworks that you have used/currently use for web services testing and would recommend? (*) There are some weird GUI glitches that appear once in a while. As is mentioned by some of the answers, we attributed this to a memory leak.
TITLE: Is soapUI the best web services testing tool/client/framework? QUESTION: I have been working on a web services related project for about the last year. Our team found soapUI near the start of our project and we have been mostly (*) satisfied with it (the free version, that is). My question is: are there other tools/clients/frameworks that you have used/currently use for web services testing and would recommend? (*) There are some weird GUI glitches that appear once in a while. As is mentioned by some of the answers, we attributed this to a memory leak. ANSWER: I use soapUI, and it's generally pretty good. Be aware that it seems to leak memory, and eventually it will no longer save your project, so save regularly! This is about the only hassle I have with it (other than the general ugliness that almost every Java application has!), and I can't live without it.
[ "web-services", "testing" ]
14
9
12,326
5
0
2008-08-28T11:23:44.327000
2008-08-28T11:36:36.370000
32,027
32,317
NAnt and dual platform build - best way to build on Windows AND Mono/Linux
I'm new to NAnt but have some experience with Ant and CruiseControl. What I want to do is have my SVN project include all tools needed (like NUnit and Mocks etc) so I can check out onto a fresh machine and build. This strategy is outlined by J.P Boodhoo here. So far so good if I only want to run on Windows, but I want to be able to check out onto Linux and build/test/run against Mono too. I want no dependencies external to the SVN project. I don't mind having two sets of tools in the project but want only one NAnt build file This must be possible - but how? what are the tricks / 'traps for young players'
This shouldn't be a particularly difficult excercise. We do some fairly similar stuff on one of my projects since half of it runs on Java using Ant to run relevant targets, and the other half is.Net (C#) for the UI. The projects get run on windows machines for development, but the servers (Java) run linux, but in the UAT environment (linux) we need to run the nunits (integration tests). The real trick (not really a difficult trick) behind this is having a NAnt build file that can run in both environments which seems to be the same thing you're trying to do here. Of course you realise you'll need to install NAnt on Mono first: $ export MONO_NO_UNLOAD=1 $ make clean $ make $ mono bin/NAnt.exe clean build And then your build file needs to be written in such a way that it seperates concerns. Some parts of the build file written for windows will not work in linux for example. So you really just need to divide it up ito specific targets in the build file. After that, there are a number of ways you can run a specific targets from the command line. An example might look like this: You get the idea... You get the idea... You get the idea... For brevity, I've left both sides out. The neat thing is you can use NUnit as well as NAnt on both environments and that makes things really easy from a dependency point of view. And for each executable you can swap out for others that work in that environment, for example (xBuild for MSBuild, and svn for tortoise etc) For more help on Nunit etc on Mono, check out this fantastic post. Hope that helps, Cheers, Rob G
NAnt and dual platform build - best way to build on Windows AND Mono/Linux I'm new to NAnt but have some experience with Ant and CruiseControl. What I want to do is have my SVN project include all tools needed (like NUnit and Mocks etc) so I can check out onto a fresh machine and build. This strategy is outlined by J.P Boodhoo here. So far so good if I only want to run on Windows, but I want to be able to check out onto Linux and build/test/run against Mono too. I want no dependencies external to the SVN project. I don't mind having two sets of tools in the project but want only one NAnt build file This must be possible - but how? what are the tricks / 'traps for young players'
TITLE: NAnt and dual platform build - best way to build on Windows AND Mono/Linux QUESTION: I'm new to NAnt but have some experience with Ant and CruiseControl. What I want to do is have my SVN project include all tools needed (like NUnit and Mocks etc) so I can check out onto a fresh machine and build. This strategy is outlined by J.P Boodhoo here. So far so good if I only want to run on Windows, but I want to be able to check out onto Linux and build/test/run against Mono too. I want no dependencies external to the SVN project. I don't mind having two sets of tools in the project but want only one NAnt build file This must be possible - but how? what are the tricks / 'traps for young players' ANSWER: This shouldn't be a particularly difficult excercise. We do some fairly similar stuff on one of my projects since half of it runs on Java using Ant to run relevant targets, and the other half is.Net (C#) for the UI. The projects get run on windows machines for development, but the servers (Java) run linux, but in the UAT environment (linux) we need to run the nunits (integration tests). The real trick (not really a difficult trick) behind this is having a NAnt build file that can run in both environments which seems to be the same thing you're trying to do here. Of course you realise you'll need to install NAnt on Mono first: $ export MONO_NO_UNLOAD=1 $ make clean $ make $ mono bin/NAnt.exe clean build And then your build file needs to be written in such a way that it seperates concerns. Some parts of the build file written for windows will not work in linux for example. So you really just need to divide it up ito specific targets in the build file. After that, there are a number of ways you can run a specific targets from the command line. An example might look like this: You get the idea... You get the idea... You get the idea... For brevity, I've left both sides out. The neat thing is you can use NUnit as well as NAnt on both environments and that makes things really easy from a dependency point of view. And for each executable you can swap out for others that work in that environment, for example (xBuild for MSBuild, and svn for tortoise etc) For more help on Nunit etc on Mono, check out this fantastic post. Hope that helps, Cheers, Rob G
[ ".net", "linux", "build-process", "mono", "nant" ]
6
8
1,726
4
0
2008-08-28T11:35:12.473000
2008-08-28T13:47:12.423000
32,034
32,036
In C#, isn't the observer pattern already implemented using Events?
After reading the Head First Design Patterns book and using a number of other design patterns, I'm trying to understand the Observer pattern. Isn't this already implemented using Events in the.NET Framework?
Yes, it is. The observer pattern is also called the publish/subscribe pattern, which is exactly what events allow you to do.
In C#, isn't the observer pattern already implemented using Events? After reading the Head First Design Patterns book and using a number of other design patterns, I'm trying to understand the Observer pattern. Isn't this already implemented using Events in the.NET Framework?
TITLE: In C#, isn't the observer pattern already implemented using Events? QUESTION: After reading the Head First Design Patterns book and using a number of other design patterns, I'm trying to understand the Observer pattern. Isn't this already implemented using Events in the.NET Framework? ANSWER: Yes, it is. The observer pattern is also called the publish/subscribe pattern, which is exactly what events allow you to do.
[ "c#", ".net", "design-patterns" ]
33
26
14,223
8
0
2008-08-28T11:36:52.297000
2008-08-28T11:38:45.850000
32,041
32,122
How to remove debug statements from production code in Java
Is it possible for the compiler to remove statements used for debugging purposes (such as logging) from production code? The debug statements would need to be marked somehow, maybe using annotations. It's easy to set a property (debug = true) and check it at each debug statement, but this can reduce performance. It would be nice if the compiler would simply make the debug statements vanish.
Two recommendations. First: for real logging, use a modern logging package like log4j or java's own built in logging. Don't worry about performance so much, the logging level check is on the order of nanoseconds. (it's an integer comparison). And if you have more than a single log statement, guard the whole block: (log4j, for example:) if (logger.isDebugEnabled()) { // perform expensive operations // build string to log logger.debug("...."); } This gives you the added ability control logging at runtime. Having to restart and run a debug build can be very inconvenient. Second: You may find assertions are more what you need. An assertion is a statement which evaluates to a boolean result, with an optional message: assert (sky.state!= FALLING): "The sky is falling!"; Whenever the assertion results in a false, the assertion fails and an AssertionError is thrown containing your message (this is an unchecked exception, intended to exit the application). The neat thing is, these are treated special by the JVM and can toggled at runtime down to the class level, using a VM parameter (no recompile needed). If not enabled, there is zero overhead.
How to remove debug statements from production code in Java Is it possible for the compiler to remove statements used for debugging purposes (such as logging) from production code? The debug statements would need to be marked somehow, maybe using annotations. It's easy to set a property (debug = true) and check it at each debug statement, but this can reduce performance. It would be nice if the compiler would simply make the debug statements vanish.
TITLE: How to remove debug statements from production code in Java QUESTION: Is it possible for the compiler to remove statements used for debugging purposes (such as logging) from production code? The debug statements would need to be marked somehow, maybe using annotations. It's easy to set a property (debug = true) and check it at each debug statement, but this can reduce performance. It would be nice if the compiler would simply make the debug statements vanish. ANSWER: Two recommendations. First: for real logging, use a modern logging package like log4j or java's own built in logging. Don't worry about performance so much, the logging level check is on the order of nanoseconds. (it's an integer comparison). And if you have more than a single log statement, guard the whole block: (log4j, for example:) if (logger.isDebugEnabled()) { // perform expensive operations // build string to log logger.debug("...."); } This gives you the added ability control logging at runtime. Having to restart and run a debug build can be very inconvenient. Second: You may find assertions are more what you need. An assertion is a statement which evaluates to a boolean result, with an optional message: assert (sky.state!= FALLING): "The sky is falling!"; Whenever the assertion results in a false, the assertion fails and an AssertionError is thrown containing your message (this is an unchecked exception, intended to exit the application). The neat thing is, these are treated special by the JVM and can toggled at runtime down to the class level, using a VM parameter (no recompile needed). If not enabled, there is zero overhead.
[ "java", "debugging", "compiler-construction" ]
16
24
15,712
8
0
2008-08-28T11:40:58.420000
2008-08-28T12:46:23.707000
32,044
32,125
How can I render a tree structure (recursive) using a django template?
I have a tree structure in memory that I would like to render in HTML using a Django template. class Node(): name = "node name" children = [] There will be some object root that is a Node, and children is a list of Node s. root will be passed in the content of the template. I have found this one discussion of how this might be achieved, but the poster suggests this might not be good in a production environment. Does anybody know of a better way?
I think the canonical answer is: "Don't". What you should probably do instead is unravel the thing in your view code, so it's just a matter of iterating over (in|de)dents in the template. I think I'd do it by appending indents and dedents to a list while recursing through the tree and then sending that "travelogue" list to the template. (the template would then insert and from that list, creating the recursive structure with "understanding" it.) I'm also pretty sure recursively including template files is really a wrong way to do it...
How can I render a tree structure (recursive) using a django template? I have a tree structure in memory that I would like to render in HTML using a Django template. class Node(): name = "node name" children = [] There will be some object root that is a Node, and children is a list of Node s. root will be passed in the content of the template. I have found this one discussion of how this might be achieved, but the poster suggests this might not be good in a production environment. Does anybody know of a better way?
TITLE: How can I render a tree structure (recursive) using a django template? QUESTION: I have a tree structure in memory that I would like to render in HTML using a Django template. class Node(): name = "node name" children = [] There will be some object root that is a Node, and children is a list of Node s. root will be passed in the content of the template. I have found this one discussion of how this might be achieved, but the poster suggests this might not be good in a production environment. Does anybody know of a better way? ANSWER: I think the canonical answer is: "Don't". What you should probably do instead is unravel the thing in your view code, so it's just a matter of iterating over (in|de)dents in the template. I think I'd do it by appending indents and dedents to a list while recursing through the tree and then sending that "travelogue" list to the template. (the template would then insert and from that list, creating the recursive structure with "understanding" it.) I'm also pretty sure recursively including template files is really a wrong way to do it...
[ "python", "django" ]
76
29
40,772
10
0
2008-08-28T11:43:10.287000
2008-08-28T12:47:29.243000
32,058
32,508
How do I extract the inner exception from a soap exception in ASP.NET?
I have a simple web service operation like this one: [WebMethod] public string HelloWorld() { throw new Exception("HelloWorldException"); return "Hello World"; } And then I have a client application that consumes the web service and then calls the operation. Obviously it will throw an exception:-) try { hwservicens.Service1 service1 = new hwservicens.Service1(); service1.HelloWorld(); } catch(Exception e) { Console.WriteLine(e.ToString()); } In my catch-block, what I would like to do is extract the Message of the actual exception to use it in my code. The exception caught is a SoapException, which is fine, but it's Message property is like this... System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.Exception: HelloWorldException at WebService1.Service1.HelloWorld() in C:\svnroot\Vordur\WebService1\Service1.asmx.cs:line 27 --- End of inner exception stack trace ---...and the InnerException is null. What I would like to do is extract the Message property of the InnerException (the HelloWorldException text in my sample), can anyone help with that? If you can avoid it, please don't suggest parsing the Message property of the SoapException.
Unfortunately I don't think this is possible. The exception you are raising in your web service code is being encoded into a Soap Fault, which then being passed as a string back to your client code. What you are seeing in the SoapException message is simply the text from the Soap fault, which is not being converted back to an exception, but merely stored as text. If you want to return useful information in error conditions then I recommend returning a custom class from your web service which can have an "Error" property which contains your information. [WebMethod] public ResponseClass HelloWorld() { ResponseClass c = new ResponseClass(); try { throw new Exception("Exception Text"); // The following would be returned on a success c.WasError = false; c.ReturnValue = "Hello World"; } catch(Exception e) { c.WasError = true; c.ErrorMessage = e.Message; return c; } }
How do I extract the inner exception from a soap exception in ASP.NET? I have a simple web service operation like this one: [WebMethod] public string HelloWorld() { throw new Exception("HelloWorldException"); return "Hello World"; } And then I have a client application that consumes the web service and then calls the operation. Obviously it will throw an exception:-) try { hwservicens.Service1 service1 = new hwservicens.Service1(); service1.HelloWorld(); } catch(Exception e) { Console.WriteLine(e.ToString()); } In my catch-block, what I would like to do is extract the Message of the actual exception to use it in my code. The exception caught is a SoapException, which is fine, but it's Message property is like this... System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.Exception: HelloWorldException at WebService1.Service1.HelloWorld() in C:\svnroot\Vordur\WebService1\Service1.asmx.cs:line 27 --- End of inner exception stack trace ---...and the InnerException is null. What I would like to do is extract the Message property of the InnerException (the HelloWorldException text in my sample), can anyone help with that? If you can avoid it, please don't suggest parsing the Message property of the SoapException.
TITLE: How do I extract the inner exception from a soap exception in ASP.NET? QUESTION: I have a simple web service operation like this one: [WebMethod] public string HelloWorld() { throw new Exception("HelloWorldException"); return "Hello World"; } And then I have a client application that consumes the web service and then calls the operation. Obviously it will throw an exception:-) try { hwservicens.Service1 service1 = new hwservicens.Service1(); service1.HelloWorld(); } catch(Exception e) { Console.WriteLine(e.ToString()); } In my catch-block, what I would like to do is extract the Message of the actual exception to use it in my code. The exception caught is a SoapException, which is fine, but it's Message property is like this... System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.Exception: HelloWorldException at WebService1.Service1.HelloWorld() in C:\svnroot\Vordur\WebService1\Service1.asmx.cs:line 27 --- End of inner exception stack trace ---...and the InnerException is null. What I would like to do is extract the Message property of the InnerException (the HelloWorldException text in my sample), can anyone help with that? If you can avoid it, please don't suggest parsing the Message property of the SoapException. ANSWER: Unfortunately I don't think this is possible. The exception you are raising in your web service code is being encoded into a Soap Fault, which then being passed as a string back to your client code. What you are seeing in the SoapException message is simply the text from the Soap fault, which is not being converted back to an exception, but merely stored as text. If you want to return useful information in error conditions then I recommend returning a custom class from your web service which can have an "Error" property which contains your information. [WebMethod] public ResponseClass HelloWorld() { ResponseClass c = new ResponseClass(); try { throw new Exception("Exception Text"); // The following would be returned on a success c.WasError = false; c.ReturnValue = "Hello World"; } catch(Exception e) { c.WasError = true; c.ErrorMessage = e.Message; return c; } }
[ ".net", "asp.net", "web-services", "exception", "soap" ]
16
6
13,462
3
0
2008-08-28T11:52:34.007000
2008-08-28T15:03:21.397000
32,059
32,560
How can I get the number of occurrences in a SQL IN clause?
Let's say I have four tables: PAGE, USER, TAG, and PAGE-TAG: Table | Fields ------------------------------------------ PAGE | ID, CONTENT TAG | ID, NAME USER | ID, NAME PAGE-TAG | ID, PAGE-ID, TAG-ID, USER-ID And let's say I have four pages: PAGE#1 'Content page 1' tagged with tag#1 by user1, tagged with tag#1 by user2 PAGE#2 'Content page 2' tagged with tag#3 by user2, tagged by tag#1 by user2, tagged by tag#8 by user1 PAGE#3 'Content page 3' tagged with tag#7 by user#1 PAGE#4 'Content page 4' tagged with tag#1 by user1, tagged with tag#8 by user1 I expect my query to look something like this: select page.content? from page, page-tag where page.id = page-tag.pag-id and page-tag.tag-id in (1, 3, 8) order by? desc I would like to get output like this: Content page 2, 3 Content page 4, 2 Content page 1, 1 Quoting Neall Your question is a bit confusing. Do you want to get the number of times each page has been tagged? No The number of times each page has gotten each tag? No The number of unique users that have tagged a page? No The number of unique users that have tagged each page with each tag? No I want to know how many of the passed tags appear in a particular page, not just if any of the tags appear. SQL IN works like an boolean operator OR. If a page was tagged with any value within the IN Clause then it returns true. I would like to know how many of the values inside of the IN clause return true. Below i show, the output i expect: page 1 | in (1,2) -> 1 page 1 | in (1,2,3) -> 1 page 1 | in (1) -> 1 page 1 | in (1,3,8) -> 1 page 2 | in (1,2) -> 1 page 2 | in (1,2,3) -> 2 page 2 | in (1) -> 1 page 2 | in (1,3,8) -> 3 page 4 | in (1,2,3) -> 1 page 4 | in (1,2,3) -> 1 page 4 | in (1) -> 1 page 4 | in (1,3,8) -> 2 This will be the content of the page-tag table i mentioned before: id page-id tag-id user-id 1 1 1 1 2 1 1 2 3 2 3 2 4 2 1 2 5 2 8 1 6 3 7 1 7 4 1 1 8 4 8 1 @Kristof does not exactly what i am searching for but thanks anyway. @Daren If i execute you code i get the next error: #1054 - Unknown column 'page-tag.tag-id' in 'having clause' @Eduardo Molteni Your answer does not give the output in the question but: Content page 2 8 Content page 4 8 content page 2 3 content page 1 1 content page 1 1 content page 2 1 cotnent page 4 1 @Keith I am using plain SQL not T-SQL and i am not familiar with T-SQL, so i do not know how your query translate to plain SQL. Any more ideas?
OK, so the key difference between this and kristof's answer is that you only want a count of 1 to show against page 1, because it has been tagged only with one tag from the set (even though two separate users both tagged it). I would suggest this: SELECT page.ID, page.content, count(*) AS uniquetags FROM ( SELECT DISTINCT page.content, page.ID, page-tag.tag-id FROM page INNER JOIN page-tag ON page.ID=page-tag.page-ID WHERE page-tag.tag-id IN (1, 3, 8) ) GROUP BY page.ID I don't have a SQL Server installation to check this, so apologies if there's a syntax mistake. But semantically I think this is what you need. This may not give the output in descending order of number of tags, but try adding: ORDER BY uniquetags DESC at the end. My uncertainty is whether you can use ORDER BY outside of grouping in SQL Server. If not, then you may need to nest the whole thing in another SELECT.
How can I get the number of occurrences in a SQL IN clause? Let's say I have four tables: PAGE, USER, TAG, and PAGE-TAG: Table | Fields ------------------------------------------ PAGE | ID, CONTENT TAG | ID, NAME USER | ID, NAME PAGE-TAG | ID, PAGE-ID, TAG-ID, USER-ID And let's say I have four pages: PAGE#1 'Content page 1' tagged with tag#1 by user1, tagged with tag#1 by user2 PAGE#2 'Content page 2' tagged with tag#3 by user2, tagged by tag#1 by user2, tagged by tag#8 by user1 PAGE#3 'Content page 3' tagged with tag#7 by user#1 PAGE#4 'Content page 4' tagged with tag#1 by user1, tagged with tag#8 by user1 I expect my query to look something like this: select page.content? from page, page-tag where page.id = page-tag.pag-id and page-tag.tag-id in (1, 3, 8) order by? desc I would like to get output like this: Content page 2, 3 Content page 4, 2 Content page 1, 1 Quoting Neall Your question is a bit confusing. Do you want to get the number of times each page has been tagged? No The number of times each page has gotten each tag? No The number of unique users that have tagged a page? No The number of unique users that have tagged each page with each tag? No I want to know how many of the passed tags appear in a particular page, not just if any of the tags appear. SQL IN works like an boolean operator OR. If a page was tagged with any value within the IN Clause then it returns true. I would like to know how many of the values inside of the IN clause return true. Below i show, the output i expect: page 1 | in (1,2) -> 1 page 1 | in (1,2,3) -> 1 page 1 | in (1) -> 1 page 1 | in (1,3,8) -> 1 page 2 | in (1,2) -> 1 page 2 | in (1,2,3) -> 2 page 2 | in (1) -> 1 page 2 | in (1,3,8) -> 3 page 4 | in (1,2,3) -> 1 page 4 | in (1,2,3) -> 1 page 4 | in (1) -> 1 page 4 | in (1,3,8) -> 2 This will be the content of the page-tag table i mentioned before: id page-id tag-id user-id 1 1 1 1 2 1 1 2 3 2 3 2 4 2 1 2 5 2 8 1 6 3 7 1 7 4 1 1 8 4 8 1 @Kristof does not exactly what i am searching for but thanks anyway. @Daren If i execute you code i get the next error: #1054 - Unknown column 'page-tag.tag-id' in 'having clause' @Eduardo Molteni Your answer does not give the output in the question but: Content page 2 8 Content page 4 8 content page 2 3 content page 1 1 content page 1 1 content page 2 1 cotnent page 4 1 @Keith I am using plain SQL not T-SQL and i am not familiar with T-SQL, so i do not know how your query translate to plain SQL. Any more ideas?
TITLE: How can I get the number of occurrences in a SQL IN clause? QUESTION: Let's say I have four tables: PAGE, USER, TAG, and PAGE-TAG: Table | Fields ------------------------------------------ PAGE | ID, CONTENT TAG | ID, NAME USER | ID, NAME PAGE-TAG | ID, PAGE-ID, TAG-ID, USER-ID And let's say I have four pages: PAGE#1 'Content page 1' tagged with tag#1 by user1, tagged with tag#1 by user2 PAGE#2 'Content page 2' tagged with tag#3 by user2, tagged by tag#1 by user2, tagged by tag#8 by user1 PAGE#3 'Content page 3' tagged with tag#7 by user#1 PAGE#4 'Content page 4' tagged with tag#1 by user1, tagged with tag#8 by user1 I expect my query to look something like this: select page.content? from page, page-tag where page.id = page-tag.pag-id and page-tag.tag-id in (1, 3, 8) order by? desc I would like to get output like this: Content page 2, 3 Content page 4, 2 Content page 1, 1 Quoting Neall Your question is a bit confusing. Do you want to get the number of times each page has been tagged? No The number of times each page has gotten each tag? No The number of unique users that have tagged a page? No The number of unique users that have tagged each page with each tag? No I want to know how many of the passed tags appear in a particular page, not just if any of the tags appear. SQL IN works like an boolean operator OR. If a page was tagged with any value within the IN Clause then it returns true. I would like to know how many of the values inside of the IN clause return true. Below i show, the output i expect: page 1 | in (1,2) -> 1 page 1 | in (1,2,3) -> 1 page 1 | in (1) -> 1 page 1 | in (1,3,8) -> 1 page 2 | in (1,2) -> 1 page 2 | in (1,2,3) -> 2 page 2 | in (1) -> 1 page 2 | in (1,3,8) -> 3 page 4 | in (1,2,3) -> 1 page 4 | in (1,2,3) -> 1 page 4 | in (1) -> 1 page 4 | in (1,3,8) -> 2 This will be the content of the page-tag table i mentioned before: id page-id tag-id user-id 1 1 1 1 2 1 1 2 3 2 3 2 4 2 1 2 5 2 8 1 6 3 7 1 7 4 1 1 8 4 8 1 @Kristof does not exactly what i am searching for but thanks anyway. @Daren If i execute you code i get the next error: #1054 - Unknown column 'page-tag.tag-id' in 'having clause' @Eduardo Molteni Your answer does not give the output in the question but: Content page 2 8 Content page 4 8 content page 2 3 content page 1 1 content page 1 1 content page 2 1 cotnent page 4 1 @Keith I am using plain SQL not T-SQL and i am not familiar with T-SQL, so i do not know how your query translate to plain SQL. Any more ideas? ANSWER: OK, so the key difference between this and kristof's answer is that you only want a count of 1 to show against page 1, because it has been tagged only with one tag from the set (even though two separate users both tagged it). I would suggest this: SELECT page.ID, page.content, count(*) AS uniquetags FROM ( SELECT DISTINCT page.content, page.ID, page-tag.tag-id FROM page INNER JOIN page-tag ON page.ID=page-tag.page-ID WHERE page-tag.tag-id IN (1, 3, 8) ) GROUP BY page.ID I don't have a SQL Server installation to check this, so apologies if there's a syntax mistake. But semantically I think this is what you need. This may not give the output in descending order of number of tags, but try adding: ORDER BY uniquetags DESC at the end. My uncertainty is whether you can use ORDER BY outside of grouping in SQL Server. If not, then you may need to nest the whole thing in another SELECT.
[ "sql" ]
1
1
4,493
6
0
2008-08-28T11:54:02.507000
2008-08-28T15:19:27.257000
32,087
32,093
What tools and languages are available for windows shell scripting?
I want to know what are the options to do some scripting jobs in windows platform. I need functionality like file manipulations, registry editing etc. Can files be edited using scripting tools? What other functionality does windows scripting tools offer? Can everything that can be done using the Windows GUI be done using a scripting language?
I think Windows PowerShell from Microsoft is the current favourite for this sort of thing.
What tools and languages are available for windows shell scripting? I want to know what are the options to do some scripting jobs in windows platform. I need functionality like file manipulations, registry editing etc. Can files be edited using scripting tools? What other functionality does windows scripting tools offer? Can everything that can be done using the Windows GUI be done using a scripting language?
TITLE: What tools and languages are available for windows shell scripting? QUESTION: I want to know what are the options to do some scripting jobs in windows platform. I need functionality like file manipulations, registry editing etc. Can files be edited using scripting tools? What other functionality does windows scripting tools offer? Can everything that can be done using the Windows GUI be done using a scripting language? ANSWER: I think Windows PowerShell from Microsoft is the current favourite for this sort of thing.
[ "windows", "scripting" ]
4
5
1,776
12
0
2008-08-28T12:32:43.473000
2008-08-28T12:35:56.603000
32,100
32,111
What is the simplest SQL Query to find the second largest value?
What is the simplest SQL query to find the second largest integer value in a specific column? There are maybe duplicate values in the column.
SELECT MAX( col ) FROM table WHERE col < ( SELECT MAX( col ) FROM table )
What is the simplest SQL Query to find the second largest value? What is the simplest SQL query to find the second largest integer value in a specific column? There are maybe duplicate values in the column.
TITLE: What is the simplest SQL Query to find the second largest value? QUESTION: What is the simplest SQL query to find the second largest integer value in a specific column? There are maybe duplicate values in the column. ANSWER: SELECT MAX( col ) FROM table WHERE col < ( SELECT MAX( col ) FROM table )
[ "sql", "puzzle" ]
207
373
494,621
46
0
2008-08-28T12:39:53.287000
2008-08-28T12:43:40.563000
32,123
32,662
procmail lockfile utility and NFS
Has anyone used the lockfile utility that ships with procmail in conjunction with NFS mounted directories? The lockfile man page states that "Lockfile is NFS-resistant and eight-bit clean."
I've used it. My company had an very NFS-intensive infrastructure at one point (less so now) and many Perl sysadmin tools dating back to the mid 90s. We wrapped lockfile in a perl module so that we could do consistent locking across NFS mounts. For that matter, our home directories were NFS mounted and we used procmail to deliver mail into them using the same style of locking and never had any problems with it (procmail delivering mail via NFS from server-a and mail being read via firect file access or UW-imap from a bunch of other servers).
procmail lockfile utility and NFS Has anyone used the lockfile utility that ships with procmail in conjunction with NFS mounted directories? The lockfile man page states that "Lockfile is NFS-resistant and eight-bit clean."
TITLE: procmail lockfile utility and NFS QUESTION: Has anyone used the lockfile utility that ships with procmail in conjunction with NFS mounted directories? The lockfile man page states that "Lockfile is NFS-resistant and eight-bit clean." ANSWER: I've used it. My company had an very NFS-intensive infrastructure at one point (less so now) and many Perl sysadmin tools dating back to the mid 90s. We wrapped lockfile in a perl module so that we could do consistent locking across NFS mounts. For that matter, our home directories were NFS mounted and we used procmail to deliver mail into them using the same style of locking and never had any problems with it (procmail delivering mail via NFS from server-a and mail being read via firect file access or UW-imap from a bunch of other servers).
[ "unix", "nfs", "procmail", "lockfile" ]
2
2
1,111
1
0
2008-08-28T12:46:26.593000
2008-08-28T15:58:44.383000
32,144
34,211
Why can't SQL Server run on a Novell server?
I'm not sure whether I'm asking the question correctly, but I've been told SQL Server cannot run on a Novell server. Is this true? If yes, why not?
NOW I see your problem! Sorry dude! Yes, VERY easy. Kinda. SQL Server used to be able to talk IPX (the netware protocol) but I think Netware will now talk TCPIP, and you can run IPX and TCP/IP on the same network without an issue - windows clients can run both at the same time, 99% of routers handle all protocols etc. Windows (XP/2003/etc) can run the netware client, so it can talk to shares etc. Use the SQL Server logins (rather than windows integrated logins), and it'll work from anything - we have Java on Linux talking to SQL Server on windows just fine:) It's all in the connection string: userid=username;pwd=whatever;server=yourserverhere; etc. But you MUST use the SQL Server Configuration Manager to set these up - the default is shared memory, so you have to enable TCPIP etc.
Why can't SQL Server run on a Novell server? I'm not sure whether I'm asking the question correctly, but I've been told SQL Server cannot run on a Novell server. Is this true? If yes, why not?
TITLE: Why can't SQL Server run on a Novell server? QUESTION: I'm not sure whether I'm asking the question correctly, but I've been told SQL Server cannot run on a Novell server. Is this true? If yes, why not? ANSWER: NOW I see your problem! Sorry dude! Yes, VERY easy. Kinda. SQL Server used to be able to talk IPX (the netware protocol) but I think Netware will now talk TCPIP, and you can run IPX and TCP/IP on the same network without an issue - windows clients can run both at the same time, 99% of routers handle all protocols etc. Windows (XP/2003/etc) can run the netware client, so it can talk to shares etc. Use the SQL Server logins (rather than windows integrated logins), and it'll work from anything - we have Java on Linux talking to SQL Server on windows just fine:) It's all in the connection string: userid=username;pwd=whatever;server=yourserverhere; etc. But you MUST use the SQL Server Configuration Manager to set these up - the default is shared memory, so you have to enable TCPIP etc.
[ "sql-server", "novell" ]
3
3
1,782
13
0
2008-08-28T12:54:02.503000
2008-08-29T09:05:03.527000
32,149
33,168
Does anyone have a good Proper Case algorithm
Does anyone have a trusted Proper Case or PCase algorithm (similar to a UCase or Upper)? I'm looking for something that takes a value such as "GEORGE BURDELL" or "george burdell" and turns it into "George Burdell". I have a simple one that handles the simple cases. The ideal would be to have something that can handle things such as "O'REILLY" and turn it into "O'Reilly", but I know that is tougher. I am mainly focused on the English language if that simplifies things. UPDATE: I'm using C# as the language, but I can convert from almost anything (assuming like functionality exists). I agree that the McDonald's scneario is a tough one. I meant to mention that along with my O'Reilly example, but did not in the original post.
Unless I've misunderstood your question I don't think you need to roll your own, the TextInfo class can do it for you. using System.Globalization; CultureInfo.InvariantCulture.TextInfo.ToTitleCase("GeOrGE bUrdEll") Will return "George Burdell. And you can use your own culture if there's some special rules involved. Update: Michael (in a comment to this answer) pointed out that this will not work if the input is all caps since the method will assume that it is an acronym. The naive workaround for this is to.ToLower() the text before submitting it to ToTitleCase.
Does anyone have a good Proper Case algorithm Does anyone have a trusted Proper Case or PCase algorithm (similar to a UCase or Upper)? I'm looking for something that takes a value such as "GEORGE BURDELL" or "george burdell" and turns it into "George Burdell". I have a simple one that handles the simple cases. The ideal would be to have something that can handle things such as "O'REILLY" and turn it into "O'Reilly", but I know that is tougher. I am mainly focused on the English language if that simplifies things. UPDATE: I'm using C# as the language, but I can convert from almost anything (assuming like functionality exists). I agree that the McDonald's scneario is a tough one. I meant to mention that along with my O'Reilly example, but did not in the original post.
TITLE: Does anyone have a good Proper Case algorithm QUESTION: Does anyone have a trusted Proper Case or PCase algorithm (similar to a UCase or Upper)? I'm looking for something that takes a value such as "GEORGE BURDELL" or "george burdell" and turns it into "George Burdell". I have a simple one that handles the simple cases. The ideal would be to have something that can handle things such as "O'REILLY" and turn it into "O'Reilly", but I know that is tougher. I am mainly focused on the English language if that simplifies things. UPDATE: I'm using C# as the language, but I can convert from almost anything (assuming like functionality exists). I agree that the McDonald's scneario is a tough one. I meant to mention that along with my O'Reilly example, but did not in the original post. ANSWER: Unless I've misunderstood your question I don't think you need to roll your own, the TextInfo class can do it for you. using System.Globalization; CultureInfo.InvariantCulture.TextInfo.ToTitleCase("GeOrGE bUrdEll") Will return "George Burdell. And you can use your own culture if there's some special rules involved. Update: Michael (in a comment to this answer) pointed out that this will not work if the input is all caps since the method will assume that it is an acronym. The naive workaround for this is to.ToLower() the text before submitting it to ToTitleCase.
[ "algorithm", "string" ]
26
17
14,213
13
0
2008-08-28T12:55:58.193000
2008-08-28T19:18:49.037000
32,151
32,176
Best way to export html to Word without having MS Word installed?
Is there a way to export a simple HTML page to Word (.doc format, not.docx) without having Microsoft Word installed?
If you have only simple HTML pages as you said, it can be opened with Word. Otherwise, there are some libraries which can do this, but I don't have experience with them. My last idea is that if you are using ASP.NET, try to add application/msword to the header and you can save it as a Word document (it won't be a real Word doc, only an HTML renamed to doc to be able to open).
Best way to export html to Word without having MS Word installed? Is there a way to export a simple HTML page to Word (.doc format, not.docx) without having Microsoft Word installed?
TITLE: Best way to export html to Word without having MS Word installed? QUESTION: Is there a way to export a simple HTML page to Word (.doc format, not.docx) without having Microsoft Word installed? ANSWER: If you have only simple HTML pages as you said, it can be opened with Word. Otherwise, there are some libraries which can do this, but I don't have experience with them. My last idea is that if you are using ASP.NET, try to add application/msword to the header and you can save it as a Word document (it won't be a real Word doc, only an HTML renamed to doc to be able to open).
[ "html", "ms-word" ]
16
12
42,163
10
0
2008-08-28T12:57:11.840000
2008-08-28T13:03:33.900000
32,168
32,224
C++ cast syntax styles
A question related to Regular cast vs. static_cast vs. dynamic_cast: What cast syntax style do you prefer in C++? C-style cast syntax: (int)foo C++-style cast syntax: static_cast (foo) constructor syntax: int(foo) They may not translate to exactly the same instructions (do they?) but their effect should be the same (right?). If you're just casting between the built-in numeric types, I find C++-style cast syntax too verbose. As a former Java coder I tend to use C-style cast syntax instead, but my local C++ guru insists on using constructor syntax. What do you think?
It's best practice never to use C-style casts for three main reasons: as already mentioned, no checking is performed here. The programmer simply cannot know which of the various casts is used which weakens strong typing the new casts are intentionally visually striking. Since casts often reveal a weakness in the code, it's argued that making casts visible in the code is a good thing. this is especially true if searching for casts with an automated tool. Finding C-style casts reliably is nearly impossible. As palm3D noted: I find C++-style cast syntax too verbose. This is intentional, for the reasons given above. The constructor syntax (official name: function-style cast) is semantically the same as the C-style cast and should be avoided as well (except for variable initializations on declaration), for the same reasons. It is debatable whether this should be true even for types that define custom constructors but in Effective C++, Meyers argues that even in those cases you should refrain from using them. To illustrate: void f(auto_ptr x); f(static_cast >(new int(5))); // GOOD f(auto_ptr (new int(5)); // BAD The static_cast here will actually call the auto_ptr constructor.
C++ cast syntax styles A question related to Regular cast vs. static_cast vs. dynamic_cast: What cast syntax style do you prefer in C++? C-style cast syntax: (int)foo C++-style cast syntax: static_cast (foo) constructor syntax: int(foo) They may not translate to exactly the same instructions (do they?) but their effect should be the same (right?). If you're just casting between the built-in numeric types, I find C++-style cast syntax too verbose. As a former Java coder I tend to use C-style cast syntax instead, but my local C++ guru insists on using constructor syntax. What do you think?
TITLE: C++ cast syntax styles QUESTION: A question related to Regular cast vs. static_cast vs. dynamic_cast: What cast syntax style do you prefer in C++? C-style cast syntax: (int)foo C++-style cast syntax: static_cast (foo) constructor syntax: int(foo) They may not translate to exactly the same instructions (do they?) but their effect should be the same (right?). If you're just casting between the built-in numeric types, I find C++-style cast syntax too verbose. As a former Java coder I tend to use C-style cast syntax instead, but my local C++ guru insists on using constructor syntax. What do you think? ANSWER: It's best practice never to use C-style casts for three main reasons: as already mentioned, no checking is performed here. The programmer simply cannot know which of the various casts is used which weakens strong typing the new casts are intentionally visually striking. Since casts often reveal a weakness in the code, it's argued that making casts visible in the code is a good thing. this is especially true if searching for casts with an automated tool. Finding C-style casts reliably is nearly impossible. As palm3D noted: I find C++-style cast syntax too verbose. This is intentional, for the reasons given above. The constructor syntax (official name: function-style cast) is semantically the same as the C-style cast and should be avoided as well (except for variable initializations on declaration), for the same reasons. It is debatable whether this should be true even for types that define custom constructors but in Effective C++, Meyers argues that even in those cases you should refrain from using them. To illustrate: void f(auto_ptr x); f(static_cast >(new int(5))); // GOOD f(auto_ptr (new int(5)); // BAD The static_cast here will actually call the auto_ptr constructor.
[ "c++", "coding-style", "casting" ]
39
61
19,177
10
0
2008-08-28T13:01:41.720000
2008-08-28T13:16:18.267000
32,173
32,473
Disable asp.net radiobutton with javascript
I'm trying to disable a bunch of controls with JavaScript (so that they post back values). All the controls work fine except for my radio buttons as they lose their value. In the below code which is called via a recursive function to disable all child controls the Second else (else if (control is RadioButton )) is never hit and the RadioButton control is identified as a Checkbox control. private static void DisableControl(WebControl control) { if (control is CheckBox) { ((CheckBox)control).InputAttributes.Add("disabled", "disabled"); } else if (control is RadioButton) { } else if (control is ImageButton) { ((ImageButton)control).Enabled = false; } else { control.Attributes.Add("readonly", "readonly"); } } Two Questions: 1. How do I identify which control is a radiobutton? 2. How do I disable it so that it posts back its value?
I found 2 ways to get this to work, the below code correctly distinguishes between the RadioButton and Checkbox controls. private static void DisableControl(WebControl control) { Type controlType = control.GetType(); if (controlType == typeof(CheckBox)) { ((CheckBox)control).InputAttributes.Add("disabled", "disabled"); } else if (controlType == typeof(RadioButton)) { ((RadioButton)control).InputAttributes.Add("disabled", "true"); } else if (controlType == typeof(ImageButton)) { ((ImageButton)control).Enabled = false; } else { control.Attributes.Add("readonly", "readonly"); } } And the solution I used is to set SubmitDisabledControls="True" in the form element which is not ideal as it allows a user to fiddle with the values but is fine in my scenario. The second solution is to mimic the Disabled behavior and details can be found here: https://web.archive.org/web/20210608183803/http://aspnet.4guysfromrolla.com/articles/012506-1.aspx'> https://web.archive.org/web/20210608183803/http://aspnet.4guysfromrolla.com/articles/012506-1.aspx.
Disable asp.net radiobutton with javascript I'm trying to disable a bunch of controls with JavaScript (so that they post back values). All the controls work fine except for my radio buttons as they lose their value. In the below code which is called via a recursive function to disable all child controls the Second else (else if (control is RadioButton )) is never hit and the RadioButton control is identified as a Checkbox control. private static void DisableControl(WebControl control) { if (control is CheckBox) { ((CheckBox)control).InputAttributes.Add("disabled", "disabled"); } else if (control is RadioButton) { } else if (control is ImageButton) { ((ImageButton)control).Enabled = false; } else { control.Attributes.Add("readonly", "readonly"); } } Two Questions: 1. How do I identify which control is a radiobutton? 2. How do I disable it so that it posts back its value?
TITLE: Disable asp.net radiobutton with javascript QUESTION: I'm trying to disable a bunch of controls with JavaScript (so that they post back values). All the controls work fine except for my radio buttons as they lose their value. In the below code which is called via a recursive function to disable all child controls the Second else (else if (control is RadioButton )) is never hit and the RadioButton control is identified as a Checkbox control. private static void DisableControl(WebControl control) { if (control is CheckBox) { ((CheckBox)control).InputAttributes.Add("disabled", "disabled"); } else if (control is RadioButton) { } else if (control is ImageButton) { ((ImageButton)control).Enabled = false; } else { control.Attributes.Add("readonly", "readonly"); } } Two Questions: 1. How do I identify which control is a radiobutton? 2. How do I disable it so that it posts back its value? ANSWER: I found 2 ways to get this to work, the below code correctly distinguishes between the RadioButton and Checkbox controls. private static void DisableControl(WebControl control) { Type controlType = control.GetType(); if (controlType == typeof(CheckBox)) { ((CheckBox)control).InputAttributes.Add("disabled", "disabled"); } else if (controlType == typeof(RadioButton)) { ((RadioButton)control).InputAttributes.Add("disabled", "true"); } else if (controlType == typeof(ImageButton)) { ((ImageButton)control).Enabled = false; } else { control.Attributes.Add("readonly", "readonly"); } } And the solution I used is to set SubmitDisabledControls="True" in the form element which is not ideal as it allows a user to fiddle with the values but is fine in my scenario. The second solution is to mimic the Disabled behavior and details can be found here: https://web.archive.org/web/20210608183803/http://aspnet.4guysfromrolla.com/articles/012506-1.aspx'> https://web.archive.org/web/20210608183803/http://aspnet.4guysfromrolla.com/articles/012506-1.aspx.
[ "c#", "javascript", "asp.net" ]
3
3
6,980
2
0
2008-08-28T13:03:20.857000
2008-08-28T14:49:10.340000
32,175
32,196
Installing a .NET service using InstallUtil
I'm trying to install a.NET service I wrote. As recommended by MSDN, I'm using InstallUtil. But I have missed how I can set the default service user on the command-line or even in the service itself. Now, when InstallUtil is run, it will display a dialog asking the user for the credentials for a user. I'm trying to integrate the service installation into a larger install and need the service installation to remain silent.
I think I may have found it. In the service itself, the automatically created ServiceProcessInstaller component has a property "Account" which can be set to "LocalService", "LocalSystem", "NetworkService" or "User". It was defaulting to "User" which must have displayed the prompt.
Installing a .NET service using InstallUtil I'm trying to install a.NET service I wrote. As recommended by MSDN, I'm using InstallUtil. But I have missed how I can set the default service user on the command-line or even in the service itself. Now, when InstallUtil is run, it will display a dialog asking the user for the credentials for a user. I'm trying to integrate the service installation into a larger install and need the service installation to remain silent.
TITLE: Installing a .NET service using InstallUtil QUESTION: I'm trying to install a.NET service I wrote. As recommended by MSDN, I'm using InstallUtil. But I have missed how I can set the default service user on the command-line or even in the service itself. Now, when InstallUtil is run, it will display a dialog asking the user for the credentials for a user. I'm trying to integrate the service installation into a larger install and need the service installation to remain silent. ANSWER: I think I may have found it. In the service itself, the automatically created ServiceProcessInstaller component has a property "Account" which can be set to "LocalService", "LocalSystem", "NetworkService" or "User". It was defaulting to "User" which must have displayed the prompt.
[ ".net", "windows-services", "installutil" ]
38
46
33,421
5
0
2008-08-28T13:03:25.240000
2008-08-28T13:07:36.167000
32,198
32,242
How do you minimize the number of threads used in a tcp server application?
I am looking for any strategies people use when implementing server applications that service client TCP (or UDP) requests: design patterns, implementation techniques, best practices, etc. Let's assume for the purposes of this question that the requests are relatively long-lived (several minutes) and that the traffic is time sensitive, so no delays are acceptable in responding to messages. Also, we are both servicing requests from clients and making our own connections to other servers. My platform is.NET, but since the underlying technology is the same regardless of platform, I'm interested to see answers for any language.
The modern approach is to make use of the operating system to multiplex many network sockets for you, freeing your application to only processing active connections with traffic. Whenever you open a socket it's associated it with a selector. You use a single thread to poll that selector. Whenever data arrives, the selector will indicate the socket which is active, you hand off that operation to a child thread and continue polling. This way you only need a thread for each concurrent operation. Sockets which are open but idle will not tie up a thread. Using the select() and poll() methods Building Highly Scalable Servers with Java NIO
How do you minimize the number of threads used in a tcp server application? I am looking for any strategies people use when implementing server applications that service client TCP (or UDP) requests: design patterns, implementation techniques, best practices, etc. Let's assume for the purposes of this question that the requests are relatively long-lived (several minutes) and that the traffic is time sensitive, so no delays are acceptable in responding to messages. Also, we are both servicing requests from clients and making our own connections to other servers. My platform is.NET, but since the underlying technology is the same regardless of platform, I'm interested to see answers for any language.
TITLE: How do you minimize the number of threads used in a tcp server application? QUESTION: I am looking for any strategies people use when implementing server applications that service client TCP (or UDP) requests: design patterns, implementation techniques, best practices, etc. Let's assume for the purposes of this question that the requests are relatively long-lived (several minutes) and that the traffic is time sensitive, so no delays are acceptable in responding to messages. Also, we are both servicing requests from clients and making our own connections to other servers. My platform is.NET, but since the underlying technology is the same regardless of platform, I'm interested to see answers for any language. ANSWER: The modern approach is to make use of the operating system to multiplex many network sockets for you, freeing your application to only processing active connections with traffic. Whenever you open a socket it's associated it with a selector. You use a single thread to poll that selector. Whenever data arrives, the selector will indicate the socket which is active, you hand off that operation to a child thread and continue polling. This way you only need a thread for each concurrent operation. Sockets which are open but idle will not tie up a thread. Using the select() and poll() methods Building Highly Scalable Servers with Java NIO
[ "multithreading", "sockets", "tcp", "udp" ]
4
6
3,516
4
0
2008-08-28T13:07:57.307000
2008-08-28T13:23:31.200000
32,227
39,350
Data model for a extensible web form
Suppose that I have a form that contains three 10 fields: field1..field10. I store the form data in one or more database tables, probably using 10 database columns. Now suppose a few months later that I want to add 3 more fields. And in the future I may add/delete fields from this form based on changing requirements. If I have a database column per form field, then I would have to make the corresponding changes to the database each time I change the form. This seems like a maintenance headache. There must be a more sophisticated way. So my question is, how do I design a data model that is loosely coupled with my UI? A concrete use case is a CRM system that is extensible/customizable by users.
Unless you have a really good reason to do this, then this generally is a bad idea. It makes it very difficult to optimize and scale the database. If you absolutely must do it, then Travis's suggestion is fine for small tables, but its not really going to scale that well.
Data model for a extensible web form Suppose that I have a form that contains three 10 fields: field1..field10. I store the form data in one or more database tables, probably using 10 database columns. Now suppose a few months later that I want to add 3 more fields. And in the future I may add/delete fields from this form based on changing requirements. If I have a database column per form field, then I would have to make the corresponding changes to the database each time I change the form. This seems like a maintenance headache. There must be a more sophisticated way. So my question is, how do I design a data model that is loosely coupled with my UI? A concrete use case is a CRM system that is extensible/customizable by users.
TITLE: Data model for a extensible web form QUESTION: Suppose that I have a form that contains three 10 fields: field1..field10. I store the form data in one or more database tables, probably using 10 database columns. Now suppose a few months later that I want to add 3 more fields. And in the future I may add/delete fields from this form based on changing requirements. If I have a database column per form field, then I would have to make the corresponding changes to the database each time I change the form. This seems like a maintenance headache. There must be a more sophisticated way. So my question is, how do I design a data model that is loosely coupled with my UI? A concrete use case is a CRM system that is extensible/customizable by users. ANSWER: Unless you have a really good reason to do this, then this generally is a bad idea. It makes it very difficult to optimize and scale the database. If you absolutely must do it, then Travis's suggestion is fine for small tables, but its not really going to scale that well.
[ "database-design", "forms" ]
2
1
1,581
4
0
2008-08-28T13:17:20.263000
2008-09-02T12:09:06.970000
32,231
32,297
Adaptive Database
Are there any rapid Database protoyping tools that don't require me to declare a database schema, but rather create it based on the way I'm using my entities. For example, assuming an empty database (pseudo code): user1 = new User() // Creates the user table with a single id column user1.firstName = "Allain" // alters the table to have a firstName column as varchar(255) user2 = new User() // Reuses the table user2.firstName = "Bob" user2.lastName = "Loblaw" // Alters the table to have a last name column Since there are logical assumptions that can be made when dynamically creating the schema, and you could always override its choices by using your DB tools to tweak it later. Also, you could generate your schema by unit testing it this way. And obviously this is only for prototyping. Is there anything like this out there?
Google's Application Engine works like this. When you download the toolkit you get a local copy of the database engine for testing.
Adaptive Database Are there any rapid Database protoyping tools that don't require me to declare a database schema, but rather create it based on the way I'm using my entities. For example, assuming an empty database (pseudo code): user1 = new User() // Creates the user table with a single id column user1.firstName = "Allain" // alters the table to have a firstName column as varchar(255) user2 = new User() // Reuses the table user2.firstName = "Bob" user2.lastName = "Loblaw" // Alters the table to have a last name column Since there are logical assumptions that can be made when dynamically creating the schema, and you could always override its choices by using your DB tools to tweak it later. Also, you could generate your schema by unit testing it this way. And obviously this is only for prototyping. Is there anything like this out there?
TITLE: Adaptive Database QUESTION: Are there any rapid Database protoyping tools that don't require me to declare a database schema, but rather create it based on the way I'm using my entities. For example, assuming an empty database (pseudo code): user1 = new User() // Creates the user table with a single id column user1.firstName = "Allain" // alters the table to have a firstName column as varchar(255) user2 = new User() // Reuses the table user2.firstName = "Bob" user2.lastName = "Loblaw" // Alters the table to have a last name column Since there are logical assumptions that can be made when dynamically creating the schema, and you could always override its choices by using your DB tools to tweak it later. Also, you could generate your schema by unit testing it this way. And obviously this is only for prototyping. Is there anything like this out there? ANSWER: Google's Application Engine works like this. When you download the toolkit you get a local copy of the database engine for testing.
[ "database", "orm" ]
3
2
523
6
0
2008-08-28T13:18:23.567000
2008-08-28T13:39:17.120000
32,241
32,429
Algorithm to format text to Pascal or camel casing
Using this question as the base is there an alogrithm or coding example to change some text to Pascal or Camel casing. For example: mynameisfred becomes Camel: myNameIsFred Pascal: MyNameIsFred
I found a thread with a bunch of Perl guys arguing the toss on this question over at http://www.perlmonks.org/?node_id=336331. I hope this isn't too much of a non-answer to the question, but I would say you have a bit of a problem in that it would be a very open-ended algorithm which could have a lot of 'misses' as well as hits. For example, say you inputted:- camelCase("hithisisatest"); The output could be:- "hiThisIsATest" Or:- "hitHisIsATest" There's no way the algorithm would know which to prefer. You could add some extra code to specify that you'd prefer more common words, but again misses would occur (Peter Norvig wrote a very small spelling corrector over at http://norvig.com/spell-correct.html which might help algorithm-wise, I wrote a C# implementation if C#'s your language). I'd agree with Mark and say you'd be better off having an algorithm that takes a delimited input, i.e. this_is_a_test and converts that. That'd be simple to implement, i.e. in pseudocode:- SetPhraseCase(phrase, CamelOrPascal): if no delimiters if camelCase return lowerFirstLetter(phrase) else return capitaliseFirstLetter(phrase) words = splitOnDelimiter(phrase) if camelCase ret = lowerFirstLetter(first word) else ret = capitaliseFirstLetter(first word) for i in 2 to len(words): ret += capitaliseFirstLetter(words[i]) return ret capitaliseFirstLetter(word): if len(word) <= 1 return upper(word) return upper(word[0]) + word[1..len(word)] lowerFirstLetter(word): if len(word) <= 1 return lower(word) return lower(word[0]) + word[1..len(word)] You could also replace my capitaliseFirstLetter() function with a proper case algorithm if you so wished. A C# implementation of the above described algorithm is as follows (complete console program with test harness):- using System; class Program { static void Main(string[] args) { var caseAlgorithm = new CaseAlgorithm('_'); while (true) { string input = Console.ReadLine(); if (string.IsNullOrEmpty(input)) return; Console.WriteLine("Input '{0}' in camel case: '{1}', pascal case: '{2}'", input, caseAlgorithm.SetPhraseCase(input, CaseAlgorithm.CaseMode.CamelCase), caseAlgorithm.SetPhraseCase(input, CaseAlgorithm.CaseMode.PascalCase)); } } } public class CaseAlgorithm { public enum CaseMode { PascalCase, CamelCase } private char delimiterChar; public CaseAlgorithm(char inDelimiterChar) { delimiterChar = inDelimiterChar; } public string SetPhraseCase(string phrase, CaseMode caseMode) { // You might want to do some sanity checks here like making sure // there's no invalid characters, etc. if (string.IsNullOrEmpty(phrase)) return phrase; //.Split() will simply return a string[] of size 1 if no delimiter present so // no need to explicitly check this. var words = phrase.Split(delimiterChar); // Set first word accordingly. string ret = setWordCase(words[0], caseMode); // If there are other words, set them all to pascal case. if (words.Length > 1) { for (int i = 1; i < words.Length; ++i) ret += setWordCase(words[i], CaseMode.PascalCase); } return ret; } private string setWordCase(string word, CaseMode caseMode) { switch (caseMode) { case CaseMode.CamelCase: return lowerFirstLetter(word); case CaseMode.PascalCase: return capitaliseFirstLetter(word); default: throw new NotImplementedException( string.Format("Case mode '{0}' is not recognised.", caseMode.ToString())); } } private string lowerFirstLetter(string word) { return char.ToLower(word[0]) + word.Substring(1); } private string capitaliseFirstLetter(string word) { return char.ToUpper(word[0]) + word.Substring(1); } }
Algorithm to format text to Pascal or camel casing Using this question as the base is there an alogrithm or coding example to change some text to Pascal or Camel casing. For example: mynameisfred becomes Camel: myNameIsFred Pascal: MyNameIsFred
TITLE: Algorithm to format text to Pascal or camel casing QUESTION: Using this question as the base is there an alogrithm or coding example to change some text to Pascal or Camel casing. For example: mynameisfred becomes Camel: myNameIsFred Pascal: MyNameIsFred ANSWER: I found a thread with a bunch of Perl guys arguing the toss on this question over at http://www.perlmonks.org/?node_id=336331. I hope this isn't too much of a non-answer to the question, but I would say you have a bit of a problem in that it would be a very open-ended algorithm which could have a lot of 'misses' as well as hits. For example, say you inputted:- camelCase("hithisisatest"); The output could be:- "hiThisIsATest" Or:- "hitHisIsATest" There's no way the algorithm would know which to prefer. You could add some extra code to specify that you'd prefer more common words, but again misses would occur (Peter Norvig wrote a very small spelling corrector over at http://norvig.com/spell-correct.html which might help algorithm-wise, I wrote a C# implementation if C#'s your language). I'd agree with Mark and say you'd be better off having an algorithm that takes a delimited input, i.e. this_is_a_test and converts that. That'd be simple to implement, i.e. in pseudocode:- SetPhraseCase(phrase, CamelOrPascal): if no delimiters if camelCase return lowerFirstLetter(phrase) else return capitaliseFirstLetter(phrase) words = splitOnDelimiter(phrase) if camelCase ret = lowerFirstLetter(first word) else ret = capitaliseFirstLetter(first word) for i in 2 to len(words): ret += capitaliseFirstLetter(words[i]) return ret capitaliseFirstLetter(word): if len(word) <= 1 return upper(word) return upper(word[0]) + word[1..len(word)] lowerFirstLetter(word): if len(word) <= 1 return lower(word) return lower(word[0]) + word[1..len(word)] You could also replace my capitaliseFirstLetter() function with a proper case algorithm if you so wished. A C# implementation of the above described algorithm is as follows (complete console program with test harness):- using System; class Program { static void Main(string[] args) { var caseAlgorithm = new CaseAlgorithm('_'); while (true) { string input = Console.ReadLine(); if (string.IsNullOrEmpty(input)) return; Console.WriteLine("Input '{0}' in camel case: '{1}', pascal case: '{2}'", input, caseAlgorithm.SetPhraseCase(input, CaseAlgorithm.CaseMode.CamelCase), caseAlgorithm.SetPhraseCase(input, CaseAlgorithm.CaseMode.PascalCase)); } } } public class CaseAlgorithm { public enum CaseMode { PascalCase, CamelCase } private char delimiterChar; public CaseAlgorithm(char inDelimiterChar) { delimiterChar = inDelimiterChar; } public string SetPhraseCase(string phrase, CaseMode caseMode) { // You might want to do some sanity checks here like making sure // there's no invalid characters, etc. if (string.IsNullOrEmpty(phrase)) return phrase; //.Split() will simply return a string[] of size 1 if no delimiter present so // no need to explicitly check this. var words = phrase.Split(delimiterChar); // Set first word accordingly. string ret = setWordCase(words[0], caseMode); // If there are other words, set them all to pascal case. if (words.Length > 1) { for (int i = 1; i < words.Length; ++i) ret += setWordCase(words[i], CaseMode.PascalCase); } return ret; } private string setWordCase(string word, CaseMode caseMode) { switch (caseMode) { case CaseMode.CamelCase: return lowerFirstLetter(word); case CaseMode.PascalCase: return capitaliseFirstLetter(word); default: throw new NotImplementedException( string.Format("Case mode '{0}' is not recognised.", caseMode.ToString())); } } private string lowerFirstLetter(string word) { return char.ToLower(word[0]) + word.Substring(1); } private string capitaliseFirstLetter(string word) { return char.ToUpper(word[0]) + word.Substring(1); } }
[ "algorithm", "coding-style", "camelcasing", "pascalcasing" ]
8
3
3,501
2
0
2008-08-28T13:23:07.863000
2008-08-28T14:34:55.863000
32,243
32,302
Can PNG image transparency be preserved when using PHP's GDlib imagecopyresampled?
The following PHP code snippet uses GD to resize a browser-uploaded PNG to 128x128. It works great, except that the transparent areas in the original image are being replaced with a solid color- black in my case. Even though imagesavealpha is set, something isn't quite right. What's the best way to preserve the transparency in the resampled image? $uploadTempFile = $myField[ 'tmp_name' ] list( $uploadWidth, $uploadHeight, $uploadType ) = getimagesize( $uploadTempFile ); $srcImage = imagecreatefrompng( $uploadTempFile ); imagesavealpha( $targetImage, true ); $targetImage = imagecreatetruecolor( 128, 128 ); imagecopyresampled( $targetImage, $srcImage, 0, 0, 0, 0, 128, 128, $uploadWidth, $uploadHeight ); imagepng( $targetImage, 'out.png', 9 );
imagealphablending( $targetImage, false ); imagesavealpha( $targetImage, true ); did it for me. Thanks ceejayoz. note, the target image needs the alpha settings, not the source image. Edit: full replacement code. See also answers below and their comments. This is not guaranteed to be be perfect in any way, but did achieve my needs at the time. $uploadTempFile = $myField[ 'tmp_name' ] list( $uploadWidth, $uploadHeight, $uploadType ) = getimagesize( $uploadTempFile ); $srcImage = imagecreatefrompng( $uploadTempFile ); $targetImage = imagecreatetruecolor( 128, 128 ); imagealphablending( $targetImage, false ); imagesavealpha( $targetImage, true ); imagecopyresampled( $targetImage, $srcImage, 0, 0, 0, 0, 128, 128, $uploadWidth, $uploadHeight ); imagepng( $targetImage, 'out.png', 9 );
Can PNG image transparency be preserved when using PHP's GDlib imagecopyresampled? The following PHP code snippet uses GD to resize a browser-uploaded PNG to 128x128. It works great, except that the transparent areas in the original image are being replaced with a solid color- black in my case. Even though imagesavealpha is set, something isn't quite right. What's the best way to preserve the transparency in the resampled image? $uploadTempFile = $myField[ 'tmp_name' ] list( $uploadWidth, $uploadHeight, $uploadType ) = getimagesize( $uploadTempFile ); $srcImage = imagecreatefrompng( $uploadTempFile ); imagesavealpha( $targetImage, true ); $targetImage = imagecreatetruecolor( 128, 128 ); imagecopyresampled( $targetImage, $srcImage, 0, 0, 0, 0, 128, 128, $uploadWidth, $uploadHeight ); imagepng( $targetImage, 'out.png', 9 );
TITLE: Can PNG image transparency be preserved when using PHP's GDlib imagecopyresampled? QUESTION: The following PHP code snippet uses GD to resize a browser-uploaded PNG to 128x128. It works great, except that the transparent areas in the original image are being replaced with a solid color- black in my case. Even though imagesavealpha is set, something isn't quite right. What's the best way to preserve the transparency in the resampled image? $uploadTempFile = $myField[ 'tmp_name' ] list( $uploadWidth, $uploadHeight, $uploadType ) = getimagesize( $uploadTempFile ); $srcImage = imagecreatefrompng( $uploadTempFile ); imagesavealpha( $targetImage, true ); $targetImage = imagecreatetruecolor( 128, 128 ); imagecopyresampled( $targetImage, $srcImage, 0, 0, 0, 0, 128, 128, $uploadWidth, $uploadHeight ); imagepng( $targetImage, 'out.png', 9 ); ANSWER: imagealphablending( $targetImage, false ); imagesavealpha( $targetImage, true ); did it for me. Thanks ceejayoz. note, the target image needs the alpha settings, not the source image. Edit: full replacement code. See also answers below and their comments. This is not guaranteed to be be perfect in any way, but did achieve my needs at the time. $uploadTempFile = $myField[ 'tmp_name' ] list( $uploadWidth, $uploadHeight, $uploadType ) = getimagesize( $uploadTempFile ); $srcImage = imagecreatefrompng( $uploadTempFile ); $targetImage = imagecreatetruecolor( 128, 128 ); imagealphablending( $targetImage, false ); imagesavealpha( $targetImage, true ); imagecopyresampled( $targetImage, $srcImage, 0, 0, 0, 0, 128, 128, $uploadWidth, $uploadHeight ); imagepng( $targetImage, 'out.png', 9 );
[ "php", "png", "transparency", "gd", "alpha" ]
112
215
102,021
11
0
2008-08-28T13:23:33.320000
2008-08-28T13:41:12.640000
32,246
32,263
how to get the googlebot to get the correct GEOIPed content?
OK. This problem is doing my head in. And I don't know if there even IS a definitive answer. We have a website, lets call it mycompany.com. It's a UK-based site, with UK based content. Google knows about it, and we have done a load of SEO on it. All is well. Except, we are about to relaunch my company, the GLOBAL brand, so we now need mycompany.com/uk, mycompany.com/us, and mycompany.com/au, for the various countries local content. We are using GEOIP, so if someone from the US loads mycompany.com, they get redirected to mycompany.com/us etc. If someone isn't in one of those three countries (US, Australia, or UK) they get the UK site. This is all well and good, but we dont want to lose the rather large amount of Google juice we have on mycompany.com! And worse, the Google bot appears to be 100% based in the US, so the US site (which is pretty much out LEAST important one of the three) will appear to be the main one. We have thought about detecting the bot, and serving UK content, but it appears Google may smack us for that. Has anyone else come across this situation, and have a solution?
As long as Google can find mycompany.com/uk and mycompany.com/au, it'll index all three versions of the site. Your domain's Google juice should apply to all three URLs just fine if they're on the same domain.
how to get the googlebot to get the correct GEOIPed content? OK. This problem is doing my head in. And I don't know if there even IS a definitive answer. We have a website, lets call it mycompany.com. It's a UK-based site, with UK based content. Google knows about it, and we have done a load of SEO on it. All is well. Except, we are about to relaunch my company, the GLOBAL brand, so we now need mycompany.com/uk, mycompany.com/us, and mycompany.com/au, for the various countries local content. We are using GEOIP, so if someone from the US loads mycompany.com, they get redirected to mycompany.com/us etc. If someone isn't in one of those three countries (US, Australia, or UK) they get the UK site. This is all well and good, but we dont want to lose the rather large amount of Google juice we have on mycompany.com! And worse, the Google bot appears to be 100% based in the US, so the US site (which is pretty much out LEAST important one of the three) will appear to be the main one. We have thought about detecting the bot, and serving UK content, but it appears Google may smack us for that. Has anyone else come across this situation, and have a solution?
TITLE: how to get the googlebot to get the correct GEOIPed content? QUESTION: OK. This problem is doing my head in. And I don't know if there even IS a definitive answer. We have a website, lets call it mycompany.com. It's a UK-based site, with UK based content. Google knows about it, and we have done a load of SEO on it. All is well. Except, we are about to relaunch my company, the GLOBAL brand, so we now need mycompany.com/uk, mycompany.com/us, and mycompany.com/au, for the various countries local content. We are using GEOIP, so if someone from the US loads mycompany.com, they get redirected to mycompany.com/us etc. If someone isn't in one of those three countries (US, Australia, or UK) they get the UK site. This is all well and good, but we dont want to lose the rather large amount of Google juice we have on mycompany.com! And worse, the Google bot appears to be 100% based in the US, so the US site (which is pretty much out LEAST important one of the three) will appear to be the main one. We have thought about detecting the bot, and serving UK content, but it appears Google may smack us for that. Has anyone else come across this situation, and have a solution? ANSWER: As long as Google can find mycompany.com/uk and mycompany.com/au, it'll index all three versions of the site. Your domain's Google juice should apply to all three URLs just fine if they're on the same domain.
[ "seo", "bots", "google-search" ]
0
2
235
5
0
2008-08-28T13:24:09.013000
2008-08-28T13:29:38.330000
32,260
32,336
Sending email in .NET through Gmail
Instead of relying on my host to send an email, I was thinking of sending the email messages using my Gmail account. The emails are personalized emails to the bands I play on my show. Is it possible to do it?
Be sure to use System.Net.Mail, not the deprecated System.Web.Mail. Doing SSL with System.Web.Mail is a gross mess of hacky extensions. using System.Net; using System.Net.Mail; var fromAddress = new MailAddress("from@gmail.com", "From Name"); var toAddress = new MailAddress("to@example.com", "To Name"); const string fromPassword = "fromPassword"; const string subject = "Subject"; const string body = "Body"; var smtp = new SmtpClient { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(fromAddress.Address, fromPassword) }; using (var message = new MailMessage(fromAddress, toAddress) { Subject = subject, Body = body }) { smtp.Send(message); } Additionally go to the Google Account > Security page and look at the Signing in to Google > 2-Step Verification setting. If it is enabled, then you have to generate a password allowing.NET to bypass the 2-Step Verification. To do this, click on Signing in to Google > App passwords, select app = Mail, and device = Windows Computer, and finally generate the password. Use the generated password in the fromPassword constant instead of your standard Gmail password. If it is disabled, then you have to turn on Less secure app access, which is not recommended! So better enable the 2-Step verification.
Sending email in .NET through Gmail Instead of relying on my host to send an email, I was thinking of sending the email messages using my Gmail account. The emails are personalized emails to the bands I play on my show. Is it possible to do it?
TITLE: Sending email in .NET through Gmail QUESTION: Instead of relying on my host to send an email, I was thinking of sending the email messages using my Gmail account. The emails are personalized emails to the bands I play on my show. Is it possible to do it? ANSWER: Be sure to use System.Net.Mail, not the deprecated System.Web.Mail. Doing SSL with System.Web.Mail is a gross mess of hacky extensions. using System.Net; using System.Net.Mail; var fromAddress = new MailAddress("from@gmail.com", "From Name"); var toAddress = new MailAddress("to@example.com", "To Name"); const string fromPassword = "fromPassword"; const string subject = "Subject"; const string body = "Body"; var smtp = new SmtpClient { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(fromAddress.Address, fromPassword) }; using (var message = new MailMessage(fromAddress, toAddress) { Subject = subject, Body = body }) { smtp.Send(message); } Additionally go to the Google Account > Security page and look at the Signing in to Google > 2-Step Verification setting. If it is enabled, then you have to generate a password allowing.NET to bypass the 2-Step Verification. To do this, click on Signing in to Google > App passwords, select app = Mail, and device = Windows Computer, and finally generate the password. Use the generated password in the fromPassword constant instead of your standard Gmail password. If it is disabled, then you have to turn on Less secure app access, which is not recommended! So better enable the 2-Step verification.
[ "c#", ".net", "email", "smtp", "gmail" ]
964
1,168
663,584
26
0
2008-08-28T13:28:38.147000
2008-08-28T14:08:03.307000
32,280
33,552
Passing null to a method
I am in the middle of reading the excellent Clean Code One discussion is regarding passing nulls into a method. public class MetricsCalculator { public double xProjection(Point p1, Point p2) { return (p2.x - p1.x) * 1.5; } }... calculator.xProjection(null, new Point(12,13)); It represents different ways of handling this: public double xProjection(Point p1, Point p2) { if (p1 == null || p2 == null) { throw new IllegalArgumentException("Invalid argument for xProjection"); } return (p2.x - p1.x) * 1.5; } public double xProjection(Point p1, Point p2) { assert p1!= null: "p1 should not be null"; assert p2!= null: "p2 should not be null"; return (p2.x - p1.x) * 1.5; } I prefer the assertions approach, but I don't like the fact that assertions are turned off by default. The book finally states: In most programming languages there is no good way to deal with a null that is passed by a caller accidentally. Because this is the case, the rational approach is to forbid passing null by default. It doesn't really go into how you would enforce this restriction? Do any of you have strong opinions either way.
Both the use of assertions and the throwing of exceptions are valid approaches here. Either mechanism can be used to indicate a programming error, not a runtime error, as is the case here. Assertions have the advantage of performance as they are typically disabled on production systems. Exceptions have the advantage of safety, as the check is always performed. The choice really depends on the development practices of the project. The project as a whole needs to decide on an assertion policy: if the choice is to enable assertions during all development, then I'd say to use assertions to check this kind of invalid parameter - in a production system, a NullPointerException thrown due to a programming error is unlikely to be able to be caught and handled in a meaningful way anyway and so will act just like an assertion. Practically though, I know a lot of developers that don't trust that assertions will be enabled when appropriate and so opt for the safety of throwing a NullPointerException. Of course if you can't enforce a policy for your code (if you're creating a library, for example, and so are dependent on how other developers run your code), you should opt for the safe approach of throwing NullPointerException for those methods that are part of the library's API.
Passing null to a method I am in the middle of reading the excellent Clean Code One discussion is regarding passing nulls into a method. public class MetricsCalculator { public double xProjection(Point p1, Point p2) { return (p2.x - p1.x) * 1.5; } }... calculator.xProjection(null, new Point(12,13)); It represents different ways of handling this: public double xProjection(Point p1, Point p2) { if (p1 == null || p2 == null) { throw new IllegalArgumentException("Invalid argument for xProjection"); } return (p2.x - p1.x) * 1.5; } public double xProjection(Point p1, Point p2) { assert p1!= null: "p1 should not be null"; assert p2!= null: "p2 should not be null"; return (p2.x - p1.x) * 1.5; } I prefer the assertions approach, but I don't like the fact that assertions are turned off by default. The book finally states: In most programming languages there is no good way to deal with a null that is passed by a caller accidentally. Because this is the case, the rational approach is to forbid passing null by default. It doesn't really go into how you would enforce this restriction? Do any of you have strong opinions either way.
TITLE: Passing null to a method QUESTION: I am in the middle of reading the excellent Clean Code One discussion is regarding passing nulls into a method. public class MetricsCalculator { public double xProjection(Point p1, Point p2) { return (p2.x - p1.x) * 1.5; } }... calculator.xProjection(null, new Point(12,13)); It represents different ways of handling this: public double xProjection(Point p1, Point p2) { if (p1 == null || p2 == null) { throw new IllegalArgumentException("Invalid argument for xProjection"); } return (p2.x - p1.x) * 1.5; } public double xProjection(Point p1, Point p2) { assert p1!= null: "p1 should not be null"; assert p2!= null: "p2 should not be null"; return (p2.x - p1.x) * 1.5; } I prefer the assertions approach, but I don't like the fact that assertions are turned off by default. The book finally states: In most programming languages there is no good way to deal with a null that is passed by a caller accidentally. Because this is the case, the rational approach is to forbid passing null by default. It doesn't really go into how you would enforce this restriction? Do any of you have strong opinions either way. ANSWER: Both the use of assertions and the throwing of exceptions are valid approaches here. Either mechanism can be used to indicate a programming error, not a runtime error, as is the case here. Assertions have the advantage of performance as they are typically disabled on production systems. Exceptions have the advantage of safety, as the check is always performed. The choice really depends on the development practices of the project. The project as a whole needs to decide on an assertion policy: if the choice is to enable assertions during all development, then I'd say to use assertions to check this kind of invalid parameter - in a production system, a NullPointerException thrown due to a programming error is unlikely to be able to be caught and handled in a meaningful way anyway and so will act just like an assertion. Practically though, I know a lot of developers that don't trust that assertions will be enabled when appropriate and so opt for the safety of throwing a NullPointerException. Of course if you can't enforce a policy for your code (if you're creating a library, for example, and so are dependent on how other developers run your code), you should opt for the safe approach of throwing NullPointerException for those methods that are part of the library's API.
[ "java", "null", "assert" ]
21
4
47,405
16
0
2008-08-28T13:34:40.313000
2008-08-28T22:26:27.197000
32,282
32,290
How can test I regular expressions using multiple RE engines?
How can I test the same regex against different regular expression engines?
The most powerful free online regexp testing tool is by far http://regex101.com/ - lets you select the RE engine (PCRE, JavaScript, Python), has a debugger, colorizes the matches, explains the regexp on the fly, can create permalinks to the regex playground. Other online tools: http://regexpal.com/ - powered by the XRegExp JavaScript library http://www.rubular.com/ - Ruby-based Perl Regex Tutor - uses PCRE Windows desktop tools: The Regex Coach - free Windows application RegexBuddy recommended by most, costs US$ 39.95 Jeff Atwood [wrote about regular expressions]( post:). Other tools recommended by SO users include: http://www.txt2re.com/ Online free tool to generate regular expressions for multiple language (@ palmsey another thread) The Added Bytes Regular Expressions Cheat Sheet (@ GateKiller another thread) http://regexhero.net/ - The Online.NET Regular Expression Tester. Not free.
How can test I regular expressions using multiple RE engines? How can I test the same regex against different regular expression engines?
TITLE: How can test I regular expressions using multiple RE engines? QUESTION: How can I test the same regex against different regular expression engines? ANSWER: The most powerful free online regexp testing tool is by far http://regex101.com/ - lets you select the RE engine (PCRE, JavaScript, Python), has a debugger, colorizes the matches, explains the regexp on the fly, can create permalinks to the regex playground. Other online tools: http://regexpal.com/ - powered by the XRegExp JavaScript library http://www.rubular.com/ - Ruby-based Perl Regex Tutor - uses PCRE Windows desktop tools: The Regex Coach - free Windows application RegexBuddy recommended by most, costs US$ 39.95 Jeff Atwood [wrote about regular expressions]( post:). Other tools recommended by SO users include: http://www.txt2re.com/ Online free tool to generate regular expressions for multiple language (@ palmsey another thread) The Added Bytes Regular Expressions Cheat Sheet (@ GateKiller another thread) http://regexhero.net/ - The Online.NET Regular Expression Tester. Not free.
[ "regex", "testing" ]
85
75
49,836
29
0
2008-08-28T13:34:55.510000
2008-08-28T13:37:34.410000
32,332
37,542
Why don't the std::fstream classes take a std::string?
This isn't a design question, really, though it may seem like it. (Well, okay, it's kind of a design question). What I'm wondering is why the C++ std::fstream classes don't take a std::string in their constructor or open methods. Everyone loves code examples so: #include #include #include int main() { std::string filename = "testfile"; std::ifstream fin; fin.open(filename.c_str()); // Works just fine. fin.close(); //fin.open(filename); // Error: no such method. //fin.close(); } This gets me all the time when working with files. Surely the C++ library would use std::string wherever possible?
By taking a C string the C++03 std::fstream class reduced dependency on the std::string class. In C++11, however, the std::fstream class does allow passing a std::string for its constructor parameter. Now, you may wonder why isn't there a transparent conversion from a std:string to a C string, so a class that expects a C string could still take a std::string just like a class that expects a std::string can take a C string. The reason is that this would cause a conversion cycle, which in turn may lead to problems. For example, suppose std::string would be convertible to a C string so that you could use std::string s with fstream s. Suppose also that C string are convertible to std::string s as is the state in the current standard. Now, consider the following: void f(std::string str1, std::string str2); void f(char* cstr1, char* cstr2); void g() { char* cstr = "abc"; std::string str = "def"; f(cstr, str); // ERROR: ambiguous } Because you can convert either way between a std::string and a C string the call to f() could resolve to either of the two f() alternatives, and is thus ambiguous. The solution is to break the conversion cycle by making one conversion direction explicit, which is what the STL chose to do with c_str().
Why don't the std::fstream classes take a std::string? This isn't a design question, really, though it may seem like it. (Well, okay, it's kind of a design question). What I'm wondering is why the C++ std::fstream classes don't take a std::string in their constructor or open methods. Everyone loves code examples so: #include #include #include int main() { std::string filename = "testfile"; std::ifstream fin; fin.open(filename.c_str()); // Works just fine. fin.close(); //fin.open(filename); // Error: no such method. //fin.close(); } This gets me all the time when working with files. Surely the C++ library would use std::string wherever possible?
TITLE: Why don't the std::fstream classes take a std::string? QUESTION: This isn't a design question, really, though it may seem like it. (Well, okay, it's kind of a design question). What I'm wondering is why the C++ std::fstream classes don't take a std::string in their constructor or open methods. Everyone loves code examples so: #include #include #include int main() { std::string filename = "testfile"; std::ifstream fin; fin.open(filename.c_str()); // Works just fine. fin.close(); //fin.open(filename); // Error: no such method. //fin.close(); } This gets me all the time when working with files. Surely the C++ library would use std::string wherever possible? ANSWER: By taking a C string the C++03 std::fstream class reduced dependency on the std::string class. In C++11, however, the std::fstream class does allow passing a std::string for its constructor parameter. Now, you may wonder why isn't there a transparent conversion from a std:string to a C string, so a class that expects a C string could still take a std::string just like a class that expects a std::string can take a C string. The reason is that this would cause a conversion cycle, which in turn may lead to problems. For example, suppose std::string would be convertible to a C string so that you could use std::string s with fstream s. Suppose also that C string are convertible to std::string s as is the state in the current standard. Now, consider the following: void f(std::string str1, std::string str2); void f(char* cstr1, char* cstr2); void g() { char* cstr = "abc"; std::string str = "def"; f(cstr, str); // ERROR: ambiguous } Because you can convert either way between a std::string and a C string the call to f() could resolve to either of the two f() alternatives, and is thus ambiguous. The solution is to break the conversion cycle by making one conversion direction explicit, which is what the STL chose to do with c_str().
[ "c++", "stl", "file-io", "stdstring" ]
36
26
27,567
10
0
2008-08-28T14:07:00.207000
2008-09-01T06:53:24.820000
32,333
161,268
How can I program defensively in Ruby?
Here's a perfect example of the problem: Classifier gem breaks Rails. ** Original question: ** One thing that concerns me as a security professional is that Ruby doesn't have a parallel of Java's package-privacy. That is, this isn't valid Ruby: public module Foo public module Bar # factory method for new Bar implementations def self.new(...) SimpleBarImplementation.new(...) end def baz raise NotImplementedError.new('Implementing Classes MUST redefine #baz') end end private class SimpleBarImplementation include Bar def baz... end end end It'd be really nice to be able to prevent monkey-patching of Foo::BarImpl. That way, people who rely on the library know that nobody has messed with it. Imagine if somebody changed the implementation of MD5 or SHA1 on you! I can call freeze on these classes, but I have to do it on a class-by-class basis, and other scripts might modify them before I finish securing my application if I'm not very careful about load order. Java provides lots of other tools for defensive programming, many of which are not possible in Ruby. (See Josh Bloch's book for a good list.) Is this really a concern? Should I just stop complaining and use Ruby for lightweight things and not hope for "enterprise-ready" solutions? (And no, core classes are not frozen by default in Ruby. See below:) require 'md5' # => true MD5.frozen? # => false
Check out Immutable by Garry Dolley. You can prevent redefinition of individual methods.
How can I program defensively in Ruby? Here's a perfect example of the problem: Classifier gem breaks Rails. ** Original question: ** One thing that concerns me as a security professional is that Ruby doesn't have a parallel of Java's package-privacy. That is, this isn't valid Ruby: public module Foo public module Bar # factory method for new Bar implementations def self.new(...) SimpleBarImplementation.new(...) end def baz raise NotImplementedError.new('Implementing Classes MUST redefine #baz') end end private class SimpleBarImplementation include Bar def baz... end end end It'd be really nice to be able to prevent monkey-patching of Foo::BarImpl. That way, people who rely on the library know that nobody has messed with it. Imagine if somebody changed the implementation of MD5 or SHA1 on you! I can call freeze on these classes, but I have to do it on a class-by-class basis, and other scripts might modify them before I finish securing my application if I'm not very careful about load order. Java provides lots of other tools for defensive programming, many of which are not possible in Ruby. (See Josh Bloch's book for a good list.) Is this really a concern? Should I just stop complaining and use Ruby for lightweight things and not hope for "enterprise-ready" solutions? (And no, core classes are not frozen by default in Ruby. See below:) require 'md5' # => true MD5.frozen? # => false
TITLE: How can I program defensively in Ruby? QUESTION: Here's a perfect example of the problem: Classifier gem breaks Rails. ** Original question: ** One thing that concerns me as a security professional is that Ruby doesn't have a parallel of Java's package-privacy. That is, this isn't valid Ruby: public module Foo public module Bar # factory method for new Bar implementations def self.new(...) SimpleBarImplementation.new(...) end def baz raise NotImplementedError.new('Implementing Classes MUST redefine #baz') end end private class SimpleBarImplementation include Bar def baz... end end end It'd be really nice to be able to prevent monkey-patching of Foo::BarImpl. That way, people who rely on the library know that nobody has messed with it. Imagine if somebody changed the implementation of MD5 or SHA1 on you! I can call freeze on these classes, but I have to do it on a class-by-class basis, and other scripts might modify them before I finish securing my application if I'm not very careful about load order. Java provides lots of other tools for defensive programming, many of which are not possible in Ruby. (See Josh Bloch's book for a good list.) Is this really a concern? Should I just stop complaining and use Ruby for lightweight things and not hope for "enterprise-ready" solutions? (And no, core classes are not frozen by default in Ruby. See below:) require 'md5' # => true MD5.frozen? # => false ANSWER: Check out Immutable by Garry Dolley. You can prevent redefinition of individual methods.
[ "ruby", "security", "defensive-programming" ]
5
1
1,141
9
0
2008-08-28T14:07:15.197000
2008-10-02T07:57:17.693000