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
20,233
25,760
Audio player on Windows Mobile
I'm trying to develop specialized audio player for windows mobile devices (Professional ones). And I've ran into the problem an once. There no compressed audio APIs on WM or I was unable to found house in documentation. Yes there are WM6 Sound API but it cannot even pause playback or seek to specified position. There are allways Windows Media Player on WM device but I've not found it APIs documentation. So the question is: Is there simple way to play, pause, forward, rewind, getting playback position and getting audio file length on compressed audio of several popular formats? Any library? platform APIs? Anything?
I've found quite a sufficient compressed audio playback library FMOD. There are WM version of it. And I've found sample application on CodeProject to start with.
Audio player on Windows Mobile I'm trying to develop specialized audio player for windows mobile devices (Professional ones). And I've ran into the problem an once. There no compressed audio APIs on WM or I was unable to found house in documentation. Yes there are WM6 Sound API but it cannot even pause playback or seek to specified position. There are allways Windows Media Player on WM device but I've not found it APIs documentation. So the question is: Is there simple way to play, pause, forward, rewind, getting playback position and getting audio file length on compressed audio of several popular formats? Any library? platform APIs? Anything?
TITLE: Audio player on Windows Mobile QUESTION: I'm trying to develop specialized audio player for windows mobile devices (Professional ones). And I've ran into the problem an once. There no compressed audio APIs on WM or I was unable to found house in documentation. Yes there are WM6 Sound API but it cannot even pause playback or seek to specified position. There are allways Windows Media Player on WM device but I've not found it APIs documentation. So the question is: Is there simple way to play, pause, forward, rewind, getting playback position and getting audio file length on compressed audio of several popular formats? Any library? platform APIs? Anything? ANSWER: I've found quite a sufficient compressed audio playback library FMOD. There are WM version of it. And I've found sample application on CodeProject to start with.
[ "windows-mobile" ]
1
0
889
2
0
2008-08-21T15:27:23.377000
2008-08-25T08:08:26.380000
20,245
20,274
Process raw HTTP request content
I am doing an e-commerce solution in ASP.NET which uses PayPal's Website Payments Standard service. Together with that I use a service they offer ( Payment Data Transfer ) that sends you back order information after a user has completed a payment. The final thing I need to do is to parse the POST request from them and persist the info in it. The HTTP request's content is in this form: SUCCESS first_name=Jane+Doe last_name=Smith payment_status=Completed payer_email=janedoesmith%40hotmail.com payment_gross=3.99 mc_currency=USD custom=For+the+purchase+of+the+rare+book+Green+Eggs+%26+Ham Basically I want to parse this information and do something meaningful, like send it through e-mail or save it in DB. My question is what is the right approach to do parsing raw HTTP data in ASP.NET, not how the parsing itself is done.
Something like this placed in your onload event. if (Request.RequestType == "POST") { using (StreamReader sr = new StreamReader(Request.InputStream)) { if (sr.ReadLine() == "SUCCESS") { /* Do your parsing here */ } } } Mind you that they might want some special sort of response to (ie; not your full webpage), so you might do something like this after you're done parsing. Response.Clear(); Response.ContentType = "text/plain"; Response.Write("Thanks!"); Response.End(); Update: this should be done in a Generic Handler (.ashx) file in order to avoid a great deal of overhead from the page model. Check out this article for more information about.ashx files
Process raw HTTP request content I am doing an e-commerce solution in ASP.NET which uses PayPal's Website Payments Standard service. Together with that I use a service they offer ( Payment Data Transfer ) that sends you back order information after a user has completed a payment. The final thing I need to do is to parse the POST request from them and persist the info in it. The HTTP request's content is in this form: SUCCESS first_name=Jane+Doe last_name=Smith payment_status=Completed payer_email=janedoesmith%40hotmail.com payment_gross=3.99 mc_currency=USD custom=For+the+purchase+of+the+rare+book+Green+Eggs+%26+Ham Basically I want to parse this information and do something meaningful, like send it through e-mail or save it in DB. My question is what is the right approach to do parsing raw HTTP data in ASP.NET, not how the parsing itself is done.
TITLE: Process raw HTTP request content QUESTION: I am doing an e-commerce solution in ASP.NET which uses PayPal's Website Payments Standard service. Together with that I use a service they offer ( Payment Data Transfer ) that sends you back order information after a user has completed a payment. The final thing I need to do is to parse the POST request from them and persist the info in it. The HTTP request's content is in this form: SUCCESS first_name=Jane+Doe last_name=Smith payment_status=Completed payer_email=janedoesmith%40hotmail.com payment_gross=3.99 mc_currency=USD custom=For+the+purchase+of+the+rare+book+Green+Eggs+%26+Ham Basically I want to parse this information and do something meaningful, like send it through e-mail or save it in DB. My question is what is the right approach to do parsing raw HTTP data in ASP.NET, not how the parsing itself is done. ANSWER: Something like this placed in your onload event. if (Request.RequestType == "POST") { using (StreamReader sr = new StreamReader(Request.InputStream)) { if (sr.ReadLine() == "SUCCESS") { /* Do your parsing here */ } } } Mind you that they might want some special sort of response to (ie; not your full webpage), so you might do something like this after you're done parsing. Response.Clear(); Response.ContentType = "text/plain"; Response.Write("Thanks!"); Response.End(); Update: this should be done in a Generic Handler (.ashx) file in order to avoid a great deal of overhead from the page model. Check out this article for more information about.ashx files
[ "asp.net", "http", "e-commerce" ]
7
14
10,760
5
0
2008-08-21T15:30:28.457000
2008-08-21T15:39:32.053000
20,249
20,380
ILMerge and Web Resources
We're attemtping to merge our DLL's into one for deployment, thus ILMerge. Almost everything seems to work great. We have a couple web controls that use ClientScript.RegisterClientScriptResource and these are 404-ing after the merge (These worked before the merge). For example one of our controls would look like namespace Company.WebControls { public class ControlA: CompositeControl, INamingContainer { protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); this.Page.ClientScript.RegisterClientScriptResource(typeof(ControlA), "Company.WebControls.ControlA.js"); } } } It would be located in Project WebControls, assembly Company.WebControls. Underneath would be ControlA.cs and ControlA.js. ControlA.js is marked as an embedded resource. In the AssemblyInfo.cs I include the following: [assembly: System.Web.UI.WebResource("Company.WebControls.ControlA.js", "application/x-javascript")] After this is merged into CompanyA.dll, what is the proper way to reference this web resource? The ILMerge command line is as follows (from the bin directory after the build): "C:\Program Files\Microsoft\ILMerge\ILMerge.exe" /keyfile:../../CompanySK.snk /wildcards:True /copyattrs:True /out:Company.dll Company.*.dll
OK - I got this working. It looks like the primary assembly was the only one whose assembly attributes were being copied. With copyattrs set, the last one in would win, not a merge (as far as I can tell). I created a dummy project to reference the other DLL's and included all the web resources from those projects in the dummy assembly info - now multiple resources from multiple projects are all loading correctly. Final post-build command line for dummy project: "C:\Program Files\Microsoft\ILMerge\ILMerge.exe" /keyfile:../../Company.snk /wildcards:True /out:Company.dll Company.Merge.dll Company.*.dll
ILMerge and Web Resources We're attemtping to merge our DLL's into one for deployment, thus ILMerge. Almost everything seems to work great. We have a couple web controls that use ClientScript.RegisterClientScriptResource and these are 404-ing after the merge (These worked before the merge). For example one of our controls would look like namespace Company.WebControls { public class ControlA: CompositeControl, INamingContainer { protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); this.Page.ClientScript.RegisterClientScriptResource(typeof(ControlA), "Company.WebControls.ControlA.js"); } } } It would be located in Project WebControls, assembly Company.WebControls. Underneath would be ControlA.cs and ControlA.js. ControlA.js is marked as an embedded resource. In the AssemblyInfo.cs I include the following: [assembly: System.Web.UI.WebResource("Company.WebControls.ControlA.js", "application/x-javascript")] After this is merged into CompanyA.dll, what is the proper way to reference this web resource? The ILMerge command line is as follows (from the bin directory after the build): "C:\Program Files\Microsoft\ILMerge\ILMerge.exe" /keyfile:../../CompanySK.snk /wildcards:True /copyattrs:True /out:Company.dll Company.*.dll
TITLE: ILMerge and Web Resources QUESTION: We're attemtping to merge our DLL's into one for deployment, thus ILMerge. Almost everything seems to work great. We have a couple web controls that use ClientScript.RegisterClientScriptResource and these are 404-ing after the merge (These worked before the merge). For example one of our controls would look like namespace Company.WebControls { public class ControlA: CompositeControl, INamingContainer { protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); this.Page.ClientScript.RegisterClientScriptResource(typeof(ControlA), "Company.WebControls.ControlA.js"); } } } It would be located in Project WebControls, assembly Company.WebControls. Underneath would be ControlA.cs and ControlA.js. ControlA.js is marked as an embedded resource. In the AssemblyInfo.cs I include the following: [assembly: System.Web.UI.WebResource("Company.WebControls.ControlA.js", "application/x-javascript")] After this is merged into CompanyA.dll, what is the proper way to reference this web resource? The ILMerge command line is as follows (from the bin directory after the build): "C:\Program Files\Microsoft\ILMerge\ILMerge.exe" /keyfile:../../CompanySK.snk /wildcards:True /copyattrs:True /out:Company.dll Company.*.dll ANSWER: OK - I got this working. It looks like the primary assembly was the only one whose assembly attributes were being copied. With copyattrs set, the last one in would win, not a merge (as far as I can tell). I created a dummy project to reference the other DLL's and included all the web resources from those projects in the dummy assembly info - now multiple resources from multiple projects are all loading correctly. Final post-build command line for dummy project: "C:\Program Files\Microsoft\ILMerge\ILMerge.exe" /keyfile:../../Company.snk /wildcards:True /out:Company.dll Company.Merge.dll Company.*.dll
[ "c#", "asp.net", "ilmerge", "webresource" ]
4
4
1,791
2
0
2008-08-21T15:31:45.007000
2008-08-21T16:09:36.070000
20,262
20,271
Refactoring for Testability on an existing system
I've joined a team that works on a product. This product has been around for ~5 years or so, and uses ASP.NET WebForms. Its original architecture has faded over time, and things have become relatively disorganized throughout the solution. It's by no means terrible, but definitely can use some work; you all know what I mean. I've been performing some refactorings since coming on to the project team about 6 months ago. Some of those refactorings are simple, Extract Method, Pull Method Up, etc. Some of the refactorings are more structural. The latter changes make me nervous as there isn't a comprehensive suite of unit tests to accompany every component. The whole team is on board for the need to make structural changes through refactoring, but our Project Manager has expressed some concerns that we don't have adequate tests to make refactorings with the confidence that we aren't introducing regression bugs into the system. He would like us to write more tests first (against the existing architecture), then perform the refactorings. My argument is that the system's class structure is too tightly coupled to write adequate tests, and that using a more Test Driven approach while we perform our refactorings may be better. What I mean by this is not writing tests against the existing components, but writing tests for specific functional requirements, then refactoring existing code to meet those requirements. This will allow us to write tests that will probably have more longevity in the system, rather than writing a bunch of 'throw away' tests. Does anyone have any experience as to what the best course of action is? I have my own thoughts, but would like to hear some input from the community.
Your PM's concerns are valid - make sure you get your system under test before making any major refactorings. I would strongly recommend getting a copy of Michael Feather's book Working Effectively With Legacy Code (by "Legacy Code" Feathers means any system that isn't adequately covered by unit tests). This is chock full of good ideas for how to break down those couplings and dependencies you speak of, in a safe manner that won't risk introducing regression bugs. Good luck with the refactoring programme; in my experience it's an enjoyable and cathartic process from which you can learn a lot.
Refactoring for Testability on an existing system I've joined a team that works on a product. This product has been around for ~5 years or so, and uses ASP.NET WebForms. Its original architecture has faded over time, and things have become relatively disorganized throughout the solution. It's by no means terrible, but definitely can use some work; you all know what I mean. I've been performing some refactorings since coming on to the project team about 6 months ago. Some of those refactorings are simple, Extract Method, Pull Method Up, etc. Some of the refactorings are more structural. The latter changes make me nervous as there isn't a comprehensive suite of unit tests to accompany every component. The whole team is on board for the need to make structural changes through refactoring, but our Project Manager has expressed some concerns that we don't have adequate tests to make refactorings with the confidence that we aren't introducing regression bugs into the system. He would like us to write more tests first (against the existing architecture), then perform the refactorings. My argument is that the system's class structure is too tightly coupled to write adequate tests, and that using a more Test Driven approach while we perform our refactorings may be better. What I mean by this is not writing tests against the existing components, but writing tests for specific functional requirements, then refactoring existing code to meet those requirements. This will allow us to write tests that will probably have more longevity in the system, rather than writing a bunch of 'throw away' tests. Does anyone have any experience as to what the best course of action is? I have my own thoughts, but would like to hear some input from the community.
TITLE: Refactoring for Testability on an existing system QUESTION: I've joined a team that works on a product. This product has been around for ~5 years or so, and uses ASP.NET WebForms. Its original architecture has faded over time, and things have become relatively disorganized throughout the solution. It's by no means terrible, but definitely can use some work; you all know what I mean. I've been performing some refactorings since coming on to the project team about 6 months ago. Some of those refactorings are simple, Extract Method, Pull Method Up, etc. Some of the refactorings are more structural. The latter changes make me nervous as there isn't a comprehensive suite of unit tests to accompany every component. The whole team is on board for the need to make structural changes through refactoring, but our Project Manager has expressed some concerns that we don't have adequate tests to make refactorings with the confidence that we aren't introducing regression bugs into the system. He would like us to write more tests first (against the existing architecture), then perform the refactorings. My argument is that the system's class structure is too tightly coupled to write adequate tests, and that using a more Test Driven approach while we perform our refactorings may be better. What I mean by this is not writing tests against the existing components, but writing tests for specific functional requirements, then refactoring existing code to meet those requirements. This will allow us to write tests that will probably have more longevity in the system, rather than writing a bunch of 'throw away' tests. Does anyone have any experience as to what the best course of action is? I have my own thoughts, but would like to hear some input from the community. ANSWER: Your PM's concerns are valid - make sure you get your system under test before making any major refactorings. I would strongly recommend getting a copy of Michael Feather's book Working Effectively With Legacy Code (by "Legacy Code" Feathers means any system that isn't adequately covered by unit tests). This is chock full of good ideas for how to break down those couplings and dependencies you speak of, in a safe manner that won't risk introducing regression bugs. Good luck with the refactoring programme; in my experience it's an enjoyable and cathartic process from which you can learn a lot.
[ "asp.net", "refactoring", "automated-tests" ]
5
5
767
5
0
2008-08-21T15:34:46.200000
2008-08-21T15:38:51.463000
20,263
20,438
Is there a Profiler equivalent for MySql?
"Microsoft SQL Server Profiler is a graphical user interface to SQL Trace for monitoring an instance of the Database Engine or Analysis Services." I find using SQL Server Profiler extremely useful during development, testing and when I am debugging database application problems. Does anybody know if there is an equivalent program for MySql?
Something cool that is in version 5.0.37 of the community server is MySQL's new profiler. This may give you what info you are looking for.
Is there a Profiler equivalent for MySql? "Microsoft SQL Server Profiler is a graphical user interface to SQL Trace for monitoring an instance of the Database Engine or Analysis Services." I find using SQL Server Profiler extremely useful during development, testing and when I am debugging database application problems. Does anybody know if there is an equivalent program for MySql?
TITLE: Is there a Profiler equivalent for MySql? QUESTION: "Microsoft SQL Server Profiler is a graphical user interface to SQL Trace for monitoring an instance of the Database Engine or Analysis Services." I find using SQL Server Profiler extremely useful during development, testing and when I am debugging database application problems. Does anybody know if there is an equivalent program for MySql? ANSWER: Something cool that is in version 5.0.37 of the community server is MySQL's new profiler. This may give you what info you are looking for.
[ "mysql", "sql-server", "database" ]
79
39
88,708
9
0
2008-08-21T15:34:55.467000
2008-08-21T16:24:12.587000
20,267
20,270
Best way to replace tokens in a large text template
I have a large text template which needs tokenized sections replaced by other text. The tokens look something like this: ##USERNAME##. My first instinct is just to use String.Replace(), but is there a better, more efficient way or is Replace() already optimized for this?
System.Text.RegularExpressions.Regex.Replace() is what you seek - IF your tokens are odd enough that you need a regex to find them. Some kind soul did some performance testing, and between Regex.Replace(), String.Replace(), and StringBuilder.Replace(), String.Replace() actually came out on top.
Best way to replace tokens in a large text template I have a large text template which needs tokenized sections replaced by other text. The tokens look something like this: ##USERNAME##. My first instinct is just to use String.Replace(), but is there a better, more efficient way or is Replace() already optimized for this?
TITLE: Best way to replace tokens in a large text template QUESTION: I have a large text template which needs tokenized sections replaced by other text. The tokens look something like this: ##USERNAME##. My first instinct is just to use String.Replace(), but is there a better, more efficient way or is Replace() already optimized for this? ANSWER: System.Text.RegularExpressions.Regex.Replace() is what you seek - IF your tokens are odd enough that you need a regex to find them. Some kind soul did some performance testing, and between Regex.Replace(), String.Replace(), and StringBuilder.Replace(), String.Replace() actually came out on top.
[ "c#", ".net" ]
13
14
17,159
10
0
2008-08-21T15:36:24.590000
2008-08-21T15:38:33.897000
20,272
29,042
Why doesn't 'shell' work in VBscript in VS6?
In a macro for Visual Studio 6, I wanted to run an external program, so I typed: shell("p4 open " + ActiveDocument.FullName) Which gave me a type mismatch runtime error. What I ended up having to type was this: Dim wshShell Set wshShell = CreateObject("WScript.Shell") strResult = wshShell.Run("p4 open " + ActiveDocument.FullName) What is going on here? Is that nonsense really necessary or have I missed something?
As lassevk pointed out, VBScript is not Visual Basic. I believe the only built in object in VBScript is the WScript object. WScript.Echo "Hello, World!" From the docs The WScript object is the root object of the Windows Script Host object model hierarchy. It never needs to be instantiated before invoking its properties and methods, and it is always available from any script file. Everything else must be created via the CreateObject call. Some of those objects are listed here. The Shell object is one of the other objects that you need to create if you want to call methods on it. One caveat, is that RegExp is sort of built in, in that you can instantiate a RegExp object like so in VBScript: Dim r as New RegExp
Why doesn't 'shell' work in VBscript in VS6? In a macro for Visual Studio 6, I wanted to run an external program, so I typed: shell("p4 open " + ActiveDocument.FullName) Which gave me a type mismatch runtime error. What I ended up having to type was this: Dim wshShell Set wshShell = CreateObject("WScript.Shell") strResult = wshShell.Run("p4 open " + ActiveDocument.FullName) What is going on here? Is that nonsense really necessary or have I missed something?
TITLE: Why doesn't 'shell' work in VBscript in VS6? QUESTION: In a macro for Visual Studio 6, I wanted to run an external program, so I typed: shell("p4 open " + ActiveDocument.FullName) Which gave me a type mismatch runtime error. What I ended up having to type was this: Dim wshShell Set wshShell = CreateObject("WScript.Shell") strResult = wshShell.Run("p4 open " + ActiveDocument.FullName) What is going on here? Is that nonsense really necessary or have I missed something? ANSWER: As lassevk pointed out, VBScript is not Visual Basic. I believe the only built in object in VBScript is the WScript object. WScript.Echo "Hello, World!" From the docs The WScript object is the root object of the Windows Script Host object model hierarchy. It never needs to be instantiated before invoking its properties and methods, and it is always available from any script file. Everything else must be created via the CreateObject call. Some of those objects are listed here. The Shell object is one of the other objects that you need to create if you want to call methods on it. One caveat, is that RegExp is sort of built in, in that you can instantiate a RegExp object like so in VBScript: Dim r as New RegExp
[ "visual-studio", "vbscript" ]
1
1
2,146
4
0
2008-08-21T15:39:07.953000
2008-08-26T21:57:10.593000
20,286
20,293
Associating source and search keywords with account creation
As a part of the signup process for my online application, I'm thinking of tracking the source and/or search keywords used to get to my site. This would allow me to see what advertising is working and from where with a somewhat finer grain than Google Analytics would. I assume I could set some kind of cookie with this information when people get to my site, but I'm not sure how I would go about getting it. Is it even possible? I'm using Rails, but a language-independent solution (or even just pointers to where to find this information) would be appreciated!
Your best bet IMO would be to use javascript to look for a cookie named "origReferrer" or something like that and if that cookie doesn't exist you should create one (with an expiry of ~24hours) and fill it with the current referrer. That way you'll have preserved the original referrer all the way from your users first visit and when your users have completed whatever steps you want them to have completed (ie, account creation) you can read back that cookie on the server and do whatever parsing/analyzing you want. Andy Brice explains the technique in his blog post Cookie tracking for profit and pleasure.
Associating source and search keywords with account creation As a part of the signup process for my online application, I'm thinking of tracking the source and/or search keywords used to get to my site. This would allow me to see what advertising is working and from where with a somewhat finer grain than Google Analytics would. I assume I could set some kind of cookie with this information when people get to my site, but I'm not sure how I would go about getting it. Is it even possible? I'm using Rails, but a language-independent solution (or even just pointers to where to find this information) would be appreciated!
TITLE: Associating source and search keywords with account creation QUESTION: As a part of the signup process for my online application, I'm thinking of tracking the source and/or search keywords used to get to my site. This would allow me to see what advertising is working and from where with a somewhat finer grain than Google Analytics would. I assume I could set some kind of cookie with this information when people get to my site, but I'm not sure how I would go about getting it. Is it even possible? I'm using Rails, but a language-independent solution (or even just pointers to where to find this information) would be appreciated! ANSWER: Your best bet IMO would be to use javascript to look for a cookie named "origReferrer" or something like that and if that cookie doesn't exist you should create one (with an expiry of ~24hours) and fill it with the current referrer. That way you'll have preserved the original referrer all the way from your users first visit and when your users have completed whatever steps you want them to have completed (ie, account creation) you can read back that cookie on the server and do whatever parsing/analyzing you want. Andy Brice explains the technique in his blog post Cookie tracking for profit and pleasure.
[ "ruby-on-rails", "cookies", "seo" ]
2
3
264
1
0
2008-08-21T15:42:20.330000
2008-08-21T15:44:32.823000
20,298
20,306
How to stop an animation in C# / WPF?
I have something like this: barProgress.BeginAnimation(RangeBase.ValueProperty, new DoubleAnimation( barProgress.Value, dNextProgressValue, new Duration(TimeSpan.FromSeconds(dDuration))); Now, how would you stop that animation (the DoubleAnimation )? The reason I want to do this, is because I would like to start new animations (this seems to work, but it's hard to tell) and eventually stop the last animation...
To stop it, call BeginAnimation again with the second argument set to null.
How to stop an animation in C# / WPF? I have something like this: barProgress.BeginAnimation(RangeBase.ValueProperty, new DoubleAnimation( barProgress.Value, dNextProgressValue, new Duration(TimeSpan.FromSeconds(dDuration))); Now, how would you stop that animation (the DoubleAnimation )? The reason I want to do this, is because I would like to start new animations (this seems to work, but it's hard to tell) and eventually stop the last animation...
TITLE: How to stop an animation in C# / WPF? QUESTION: I have something like this: barProgress.BeginAnimation(RangeBase.ValueProperty, new DoubleAnimation( barProgress.Value, dNextProgressValue, new Duration(TimeSpan.FromSeconds(dDuration))); Now, how would you stop that animation (the DoubleAnimation )? The reason I want to do this, is because I would like to start new animations (this seems to work, but it's hard to tell) and eventually stop the last animation... ANSWER: To stop it, call BeginAnimation again with the second argument set to null.
[ "c#", "wpf" ]
54
92
68,869
8
0
2008-08-21T15:45:24.800000
2008-08-21T15:47:49.053000
20,322
20,364
How do I log uncaught exceptions in PHP?
I've found out how to convert errors into exceptions, and I display them nicely if they aren't caught, but I don't know how to log them in a useful way. Simply writing them to a file won't be useful, will it? And would you risk accessing a database, when you don't know what caused the exception yet?
I really like log4php for logging, even though it's not yet out of the incubator. I use log4net in just about everything, and have found the style quite natural for me. With regard to system crashes, you can log the error to multiple destinations (e.g., have appenders whose threshold is CRITICAL or ERROR that only come into play when things go wrong). I'm not sure how fail-safe the existing appenders are--if the database is down, how does that appender fail?--but you could quite easily write your own appender that will fail gracefully if it's unable to log.
How do I log uncaught exceptions in PHP? I've found out how to convert errors into exceptions, and I display them nicely if they aren't caught, but I don't know how to log them in a useful way. Simply writing them to a file won't be useful, will it? And would you risk accessing a database, when you don't know what caused the exception yet?
TITLE: How do I log uncaught exceptions in PHP? QUESTION: I've found out how to convert errors into exceptions, and I display them nicely if they aren't caught, but I don't know how to log them in a useful way. Simply writing them to a file won't be useful, will it? And would you risk accessing a database, when you don't know what caused the exception yet? ANSWER: I really like log4php for logging, even though it's not yet out of the incubator. I use log4net in just about everything, and have found the style quite natural for me. With regard to system crashes, you can log the error to multiple destinations (e.g., have appenders whose threshold is CRITICAL or ERROR that only come into play when things go wrong). I'm not sure how fail-safe the existing appenders are--if the database is down, how does that appender fail?--but you could quite easily write your own appender that will fail gracefully if it's unable to log.
[ "php", "exception", "error-handling", "error-logging" ]
12
6
6,990
7
0
2008-08-21T15:54:14.513000
2008-08-21T16:04:43.133000
20,326
20,649
Double postback issue
I have a ASP.NET 1.1 application, and I'm trying to find out why when I change a ComboBox which value is used to fill another one (parent-child relation), two postbacks are produced. I have checked and checked the code, and I can't find the cause. Here are both call stacks which end in a page_load First postback (generated by teh ComboBox's autopostback) Postback call stack (broken) Second postback (this is what I want to find why it's happening) alt text (broken) Any suggestion? What can I check?
It's a very specific problem with this code, I doubt it will be useful for someone else, but here it goes: A check was added to the combo's onchange with an if, if the condition was met, an explicit call to the postback function was made. If the combo was set to AutoPostback, asp.net added the postback call again, producing the two postbacks... The generated html was like this: [select onchange="javascript: if (CustomFunction()){__doPostBack('name','')}; __doPostBack('name','')"]
Double postback issue I have a ASP.NET 1.1 application, and I'm trying to find out why when I change a ComboBox which value is used to fill another one (parent-child relation), two postbacks are produced. I have checked and checked the code, and I can't find the cause. Here are both call stacks which end in a page_load First postback (generated by teh ComboBox's autopostback) Postback call stack (broken) Second postback (this is what I want to find why it's happening) alt text (broken) Any suggestion? What can I check?
TITLE: Double postback issue QUESTION: I have a ASP.NET 1.1 application, and I'm trying to find out why when I change a ComboBox which value is used to fill another one (parent-child relation), two postbacks are produced. I have checked and checked the code, and I can't find the cause. Here are both call stacks which end in a page_load First postback (generated by teh ComboBox's autopostback) Postback call stack (broken) Second postback (this is what I want to find why it's happening) alt text (broken) Any suggestion? What can I check? ANSWER: It's a very specific problem with this code, I doubt it will be useful for someone else, but here it goes: A check was added to the combo's onchange with an if, if the condition was met, an explicit call to the postback function was made. If the combo was set to AutoPostback, asp.net added the postback call again, producing the two postbacks... The generated html was like this: [select onchange="javascript: if (CustomFunction()){__doPostBack('name','')}; __doPostBack('name','')"]
[ "asp.net", ".net-1.1" ]
6
5
6,676
5
0
2008-08-21T15:55:12.517000
2008-08-21T17:45:30.893000
20,336
20,368
State of Registers After Bootup
I'm working on a boot loader on an x86 machine. When the BIOS copies the contents of the MBR to 0x7c00 and jumps to that address, is there a standard meaning to the contents of the registers? Do the registers have standard values? I know that the segment registers are typically set to 0, but will sometimes be 0x7c0. What about the other hardware registers?
This early execution environment is highly implementation defined, meaning the implementation of your particular BIOS. Never make any assumptions on the contents of registers. They might be initialized to 0, but they might contain a random value just as well. from the OS dev Wiki, which is where I get information when I'm playing with my toy OS's
State of Registers After Bootup I'm working on a boot loader on an x86 machine. When the BIOS copies the contents of the MBR to 0x7c00 and jumps to that address, is there a standard meaning to the contents of the registers? Do the registers have standard values? I know that the segment registers are typically set to 0, but will sometimes be 0x7c0. What about the other hardware registers?
TITLE: State of Registers After Bootup QUESTION: I'm working on a boot loader on an x86 machine. When the BIOS copies the contents of the MBR to 0x7c00 and jumps to that address, is there a standard meaning to the contents of the registers? Do the registers have standard values? I know that the segment registers are typically set to 0, but will sometimes be 0x7c0. What about the other hardware registers? ANSWER: This early execution environment is highly implementation defined, meaning the implementation of your particular BIOS. Never make any assumptions on the contents of registers. They might be initialized to 0, but they might contain a random value just as well. from the OS dev Wiki, which is where I get information when I'm playing with my toy OS's
[ "boot", "bios" ]
7
8
294
7
0
2008-08-21T15:57:36.363000
2008-08-21T16:06:07.857000
20,346
20,418
What are attributes in .NET?
What are attributes in.NET, what are they good for, and how do I create my own attributes?
Metadata. Data about your objects/methods/properties. For example I might declare an Attribute called: DisplayOrder so I can easily control in what order properties should appear in the UI. I could then append it to a class and write some GUI components that extract the attributes and order the UI elements appropriately. public class DisplayWrapper { private UnderlyingClass underlyingObject; public DisplayWrapper(UnderlyingClass u) { underlyingObject = u; } [DisplayOrder(1)] public int SomeInt { get { return underlyingObject.SomeInt; } } [DisplayOrder(2)] public DateTime SomeDate { get { return underlyingObject.SomeDate; } } } Thereby ensuring that SomeInt is always displayed before SomeDate when working with my custom GUI components. However, you'll see them most commonly used outside of the direct coding environment. For example the Windows Designer uses them extensively so it knows how to deal with custom made objects. Using the BrowsableAttribute like so: [Browsable(false)] public SomeCustomType DontShowThisInTheDesigner { get{/*do something*/} } Tells the designer not to list this in the available properties in the Properties window at design time for example. You could also use them for code-generation, pre-compile operations (such as Post-Sharp) or run-time operations such as Reflection.Emit. For example, you could write a bit of code for profiling that transparently wrapped every single call your code makes and times it. You could "opt-out" of the timing via an attribute that you place on particular methods. public void SomeProfilingMethod(MethodInfo targetMethod, object target, params object[] args) { bool time = true; foreach (Attribute a in target.GetCustomAttributes()) { if (a.GetType() is NoTimingAttribute) { time = false; break; } } if (time) { StopWatch stopWatch = new StopWatch(); stopWatch.Start(); targetMethod.Invoke(target, args); stopWatch.Stop(); HandleTimingOutput(targetMethod, stopWatch.Duration); } else { targetMethod.Invoke(target, args); } } Declaring them is easy, just make a class that inherits from Attribute. public class DisplayOrderAttribute: Attribute { private int order; public DisplayOrderAttribute(int order) { this.order = order; } public int Order { get { return order; } } } And remember that when you use the attribute you can omit the suffix "attribute" the compiler will add that for you. NOTE: Attributes don't do anything by themselves - there needs to be some other code that uses them. Sometimes that code has been written for you but sometimes you have to write it yourself. For example, the C# compiler cares about some and certain frameworks frameworks use some (e.g. NUnit looks for [TestFixture] on a class and [Test] on a test method when loading an assembly). So when creating your own custom attribute be aware that it will not impact the behaviour of your code at all. You'll need to write the other part that checks attributes (via reflection) and act on them.
What are attributes in .NET? What are attributes in.NET, what are they good for, and how do I create my own attributes?
TITLE: What are attributes in .NET? QUESTION: What are attributes in.NET, what are they good for, and how do I create my own attributes? ANSWER: Metadata. Data about your objects/methods/properties. For example I might declare an Attribute called: DisplayOrder so I can easily control in what order properties should appear in the UI. I could then append it to a class and write some GUI components that extract the attributes and order the UI elements appropriately. public class DisplayWrapper { private UnderlyingClass underlyingObject; public DisplayWrapper(UnderlyingClass u) { underlyingObject = u; } [DisplayOrder(1)] public int SomeInt { get { return underlyingObject.SomeInt; } } [DisplayOrder(2)] public DateTime SomeDate { get { return underlyingObject.SomeDate; } } } Thereby ensuring that SomeInt is always displayed before SomeDate when working with my custom GUI components. However, you'll see them most commonly used outside of the direct coding environment. For example the Windows Designer uses them extensively so it knows how to deal with custom made objects. Using the BrowsableAttribute like so: [Browsable(false)] public SomeCustomType DontShowThisInTheDesigner { get{/*do something*/} } Tells the designer not to list this in the available properties in the Properties window at design time for example. You could also use them for code-generation, pre-compile operations (such as Post-Sharp) or run-time operations such as Reflection.Emit. For example, you could write a bit of code for profiling that transparently wrapped every single call your code makes and times it. You could "opt-out" of the timing via an attribute that you place on particular methods. public void SomeProfilingMethod(MethodInfo targetMethod, object target, params object[] args) { bool time = true; foreach (Attribute a in target.GetCustomAttributes()) { if (a.GetType() is NoTimingAttribute) { time = false; break; } } if (time) { StopWatch stopWatch = new StopWatch(); stopWatch.Start(); targetMethod.Invoke(target, args); stopWatch.Stop(); HandleTimingOutput(targetMethod, stopWatch.Duration); } else { targetMethod.Invoke(target, args); } } Declaring them is easy, just make a class that inherits from Attribute. public class DisplayOrderAttribute: Attribute { private int order; public DisplayOrderAttribute(int order) { this.order = order; } public int Order { get { return order; } } } And remember that when you use the attribute you can omit the suffix "attribute" the compiler will add that for you. NOTE: Attributes don't do anything by themselves - there needs to be some other code that uses them. Sometimes that code has been written for you but sometimes you have to write it yourself. For example, the C# compiler cares about some and certain frameworks frameworks use some (e.g. NUnit looks for [TestFixture] on a class and [Test] on a test method when loading an assembly). So when creating your own custom attribute be aware that it will not impact the behaviour of your code at all. You'll need to write the other part that checks attributes (via reflection) and act on them.
[ "c#", ".net", "glossary", ".net-attributes" ]
211
150
69,026
11
0
2008-08-21T15:59:39.773000
2008-08-21T16:18:26.767000
20,386
24,079
Memory leaks in .NET
What are all the possible ways in which we can get memory leaks in.NET? I know of two: Not properly un-registering Event Handlers/Delegates. Not disposing dynamic child controls in Windows Forms: Example: // Causes Leaks Label label = new Label(); this.Controls.Add(label); this.Controls.Remove(label); // Correct Code Label label = new Label(); this.Controls.Add(label); this.Controls.Remove(label); label.Dispose(); Update: The idea is to list common pitfalls which are not too obvious (such as the above). Usually the notion is that memory leaks are not a big problem because of the garbage collector. Not like it used to be in C++. Great discussion guys, but let me clarify... by definition, if there is no reference left to an object in.NET, it will be Garbage Collected at some time. So that is not a way to induce memory leaks. In the managed environment, I would consider it a memory leak if you had an unintended reference to any object that you aren't aware of (hence the two examples in my question). So, what are the various possible ways in which such a memory leak can happen?
Block the finalizer thread. No other objects will be garbage collected until the finalizer thread is unblocked. Thus the amount of memory used will grow and grow. Further reading: http://dotnetdebug.net/2005/06/22/blocked-finalizer-thread/
Memory leaks in .NET What are all the possible ways in which we can get memory leaks in.NET? I know of two: Not properly un-registering Event Handlers/Delegates. Not disposing dynamic child controls in Windows Forms: Example: // Causes Leaks Label label = new Label(); this.Controls.Add(label); this.Controls.Remove(label); // Correct Code Label label = new Label(); this.Controls.Add(label); this.Controls.Remove(label); label.Dispose(); Update: The idea is to list common pitfalls which are not too obvious (such as the above). Usually the notion is that memory leaks are not a big problem because of the garbage collector. Not like it used to be in C++. Great discussion guys, but let me clarify... by definition, if there is no reference left to an object in.NET, it will be Garbage Collected at some time. So that is not a way to induce memory leaks. In the managed environment, I would consider it a memory leak if you had an unintended reference to any object that you aren't aware of (hence the two examples in my question). So, what are the various possible ways in which such a memory leak can happen?
TITLE: Memory leaks in .NET QUESTION: What are all the possible ways in which we can get memory leaks in.NET? I know of two: Not properly un-registering Event Handlers/Delegates. Not disposing dynamic child controls in Windows Forms: Example: // Causes Leaks Label label = new Label(); this.Controls.Add(label); this.Controls.Remove(label); // Correct Code Label label = new Label(); this.Controls.Add(label); this.Controls.Remove(label); label.Dispose(); Update: The idea is to list common pitfalls which are not too obvious (such as the above). Usually the notion is that memory leaks are not a big problem because of the garbage collector. Not like it used to be in C++. Great discussion guys, but let me clarify... by definition, if there is no reference left to an object in.NET, it will be Garbage Collected at some time. So that is not a way to induce memory leaks. In the managed environment, I would consider it a memory leak if you had an unintended reference to any object that you aren't aware of (hence the two examples in my question). So, what are the various possible ways in which such a memory leak can happen? ANSWER: Block the finalizer thread. No other objects will be garbage collected until the finalizer thread is unblocked. Thus the amount of memory used will grow and grow. Further reading: http://dotnetdebug.net/2005/06/22/blocked-finalizer-thread/
[ ".net", "optimization", "memory-leaks" ]
20
5
14,740
14
0
2008-08-21T16:11:34.520000
2008-08-23T08:17:01.867000
20,389
33,052
Deploying InfoPath forms to different SharePoint servers
How do you manage deploying InfoPath forms to different sharepoint servers? Is there a better way to deal all the data connections being site-specific without opening the forms, editing the data connections and republishing for each environment?
If I understand your scenario correctly: You have an InfoPath form, with data connections that submit your data. You wish to deploy this form on multiple SharePoint Servers and have those data connections submit data to the currently deployed server. You can't really get around needing to do work on every SharePoint server that you would want to deploy the form to. However, you can get around needing to modify the InfoPath Form Template. If you use the SharePoint Data Connection Library (DCL), and create a UDC file from your data connection, on every SharePoint Server that you would want to use...then your InfoPath Template can just talk to the UDC file. Here's a link to an article about integrating InfoPath with SharePoint's DCL: http://msdn.microsoft.com/en-us/library/bb267335.aspx
Deploying InfoPath forms to different SharePoint servers How do you manage deploying InfoPath forms to different sharepoint servers? Is there a better way to deal all the data connections being site-specific without opening the forms, editing the data connections and republishing for each environment?
TITLE: Deploying InfoPath forms to different SharePoint servers QUESTION: How do you manage deploying InfoPath forms to different sharepoint servers? Is there a better way to deal all the data connections being site-specific without opening the forms, editing the data connections and republishing for each environment? ANSWER: If I understand your scenario correctly: You have an InfoPath form, with data connections that submit your data. You wish to deploy this form on multiple SharePoint Servers and have those data connections submit data to the currently deployed server. You can't really get around needing to do work on every SharePoint server that you would want to deploy the form to. However, you can get around needing to modify the InfoPath Form Template. If you use the SharePoint Data Connection Library (DCL), and create a UDC file from your data connection, on every SharePoint Server that you would want to use...then your InfoPath Template can just talk to the UDC file. Here's a link to an article about integrating InfoPath with SharePoint's DCL: http://msdn.microsoft.com/en-us/library/bb267335.aspx
[ "sharepoint", "moss", "infopath" ]
6
2
11,868
7
0
2008-08-21T16:12:45.220000
2008-08-28T18:42:29.327000
20,391
20,453
Script to backup svn repository to network share
I have a svn repo on my machine (Windows). Anyone have a script to back it up to a network share? I'm using the repo locally since I'm disconnected a lot. The network share is on a server with a backup strategy. I'm a perfect candidate for git/hg but I don't want to give up my VS integration just yet.
I wrote a batch file to do this for a bunch of repos, you could just hook that batch file up to windows scheduler and run it on a schedule. svnadmin hotcopy m:\Source\Q4Press\Repo m:\SvnOut\Q4Press I use the hotcopy but the svn dump would work just as well.
Script to backup svn repository to network share I have a svn repo on my machine (Windows). Anyone have a script to back it up to a network share? I'm using the repo locally since I'm disconnected a lot. The network share is on a server with a backup strategy. I'm a perfect candidate for git/hg but I don't want to give up my VS integration just yet.
TITLE: Script to backup svn repository to network share QUESTION: I have a svn repo on my machine (Windows). Anyone have a script to back it up to a network share? I'm using the repo locally since I'm disconnected a lot. The network share is on a server with a backup strategy. I'm a perfect candidate for git/hg but I don't want to give up my VS integration just yet. ANSWER: I wrote a batch file to do this for a bunch of repos, you could just hook that batch file up to windows scheduler and run it on a schedule. svnadmin hotcopy m:\Source\Q4Press\Repo m:\SvnOut\Q4Press I use the hotcopy but the svn dump would work just as well.
[ "svn" ]
5
3
3,193
3
0
2008-08-21T16:12:53.707000
2008-08-21T16:32:44.063000
20,392
20,486
Is it OK to drop sql statistics?
We've been trying to alter a lot of columns from nullable to not nullable, which involves dropping all the associated objects, making the change, and recreating the associated objects. We've been using SQL Compare to generate the scripts, but I noticed that SQL Compare doesn't script statistic objects. Does this mean its ok to drop them and the database will work as well as it did before without them, or have Red Gate missed a trick?
It is considered best practice to auto create and auto update statistics. Sql Server will create them if it needs them. You will often see the tuning wizard generate lots of these, and you will also see people advise that you update statistics as a part of your maintenance plan, but this is not necessary and might actually make things worse, just so long as auto create and auto update are enabled.
Is it OK to drop sql statistics? We've been trying to alter a lot of columns from nullable to not nullable, which involves dropping all the associated objects, making the change, and recreating the associated objects. We've been using SQL Compare to generate the scripts, but I noticed that SQL Compare doesn't script statistic objects. Does this mean its ok to drop them and the database will work as well as it did before without them, or have Red Gate missed a trick?
TITLE: Is it OK to drop sql statistics? QUESTION: We've been trying to alter a lot of columns from nullable to not nullable, which involves dropping all the associated objects, making the change, and recreating the associated objects. We've been using SQL Compare to generate the scripts, but I noticed that SQL Compare doesn't script statistic objects. Does this mean its ok to drop them and the database will work as well as it did before without them, or have Red Gate missed a trick? ANSWER: It is considered best practice to auto create and auto update statistics. Sql Server will create them if it needs them. You will often see the tuning wizard generate lots of these, and you will also see people advise that you update statistics as a part of your maintenance plan, but this is not necessary and might actually make things worse, just so long as auto create and auto update are enabled.
[ "sql", "sql-server", "scripting", "statistics" ]
5
2
6,538
4
0
2008-08-21T16:12:58.540000
2008-08-21T16:46:25.513000
20,420
21,106
Any ReSharper equivalent for Xcode?
I'm a complete Xcode/Objective-C/Cocoa newbie but I'm learning fast and really starting to enjoy getting to grips with a new language, platform and paradigm. One thing is though, having been using Visual Studio with R# for so long I've kind of been spoiled with the coding tools such as refactorings and completion etc and as far as I can tell Xcode has some fairly limited built in support for this stuff. On that note, does anyone know if any add-ins or whatever are available for the Xcode environment which add coding helpers such as automatically generating implementation skeletons from a class interface definition etc? I suspect there aren't but I suppose it can't help to ask.
You sound as if you're looking for three major things: code templates, refactoring tools, and auto-completion. The good news is that Xcode 3 and later come with superb auto-completion and template support. By default, you have to explicitly request completion by hitting the escape key. (This actually works in all NSTextView s; try it!) If you want to have the completions appear automatically, you can go to Preferences -> Code Sense and set the pop-up to appear automatically after a few seconds. You should find good completions for C and Objective-C code, and pretty good completions for C++. Xcode also has a solid template/skeleton system that you can use. You can see what templates are available by default by going to Edit -> Insert Text Macro. Of course, you don't want to insert text macros with the mouse; that defeats the point. Instead, you have two options: Back in Preferences,go to Key Bindings, and then, under Menu Key Bindings, assign a specific shortcut to macros you use often. I personally don't bother doing this, but I know plenty of great Mac devs who do Use the CompletionPrefix. By default, nearly all of the templates have a special prefix that, if you type and then hit the escape key, will result in the template being inserted. You can use Control-/ to move between the completion fields. You can see a full list of Xcode's default macros and their associated CompletionPrefix es at Crooked Spin. You can also add your own macros, or modify the defaults. To do so, edit the file /Developer/Library/Xcode/Specifications/{C,HTML}.xctxtmacro. The syntax should be self-explanatory, if not terribly friendly. Unfortunately, if you're addicted to R#, you will be disappointed by your refactoring options. Basic refactoring is provided within Xcode through the context menu or by hitting Shift-Apple-J. From there, you can extract and rename methods, promote and demote them through the class hierarchy, and a few other common operations. Unfortunately, neither Xcode nor any third-party utilities offer anything approaching Resharper, so on that front, you're currently out of luck. Thankfully, Apple has already demonstrated versions of Xcode in the works that have vastly improved refactoring capabilities, so hopefully you won't have to wait too long before the situation starts to improve.
Any ReSharper equivalent for Xcode? I'm a complete Xcode/Objective-C/Cocoa newbie but I'm learning fast and really starting to enjoy getting to grips with a new language, platform and paradigm. One thing is though, having been using Visual Studio with R# for so long I've kind of been spoiled with the coding tools such as refactorings and completion etc and as far as I can tell Xcode has some fairly limited built in support for this stuff. On that note, does anyone know if any add-ins or whatever are available for the Xcode environment which add coding helpers such as automatically generating implementation skeletons from a class interface definition etc? I suspect there aren't but I suppose it can't help to ask.
TITLE: Any ReSharper equivalent for Xcode? QUESTION: I'm a complete Xcode/Objective-C/Cocoa newbie but I'm learning fast and really starting to enjoy getting to grips with a new language, platform and paradigm. One thing is though, having been using Visual Studio with R# for so long I've kind of been spoiled with the coding tools such as refactorings and completion etc and as far as I can tell Xcode has some fairly limited built in support for this stuff. On that note, does anyone know if any add-ins or whatever are available for the Xcode environment which add coding helpers such as automatically generating implementation skeletons from a class interface definition etc? I suspect there aren't but I suppose it can't help to ask. ANSWER: You sound as if you're looking for three major things: code templates, refactoring tools, and auto-completion. The good news is that Xcode 3 and later come with superb auto-completion and template support. By default, you have to explicitly request completion by hitting the escape key. (This actually works in all NSTextView s; try it!) If you want to have the completions appear automatically, you can go to Preferences -> Code Sense and set the pop-up to appear automatically after a few seconds. You should find good completions for C and Objective-C code, and pretty good completions for C++. Xcode also has a solid template/skeleton system that you can use. You can see what templates are available by default by going to Edit -> Insert Text Macro. Of course, you don't want to insert text macros with the mouse; that defeats the point. Instead, you have two options: Back in Preferences,go to Key Bindings, and then, under Menu Key Bindings, assign a specific shortcut to macros you use often. I personally don't bother doing this, but I know plenty of great Mac devs who do Use the CompletionPrefix. By default, nearly all of the templates have a special prefix that, if you type and then hit the escape key, will result in the template being inserted. You can use Control-/ to move between the completion fields. You can see a full list of Xcode's default macros and their associated CompletionPrefix es at Crooked Spin. You can also add your own macros, or modify the defaults. To do so, edit the file /Developer/Library/Xcode/Specifications/{C,HTML}.xctxtmacro. The syntax should be self-explanatory, if not terribly friendly. Unfortunately, if you're addicted to R#, you will be disappointed by your refactoring options. Basic refactoring is provided within Xcode through the context menu or by hitting Shift-Apple-J. From there, you can extract and rename methods, promote and demote them through the class hierarchy, and a few other common operations. Unfortunately, neither Xcode nor any third-party utilities offer anything approaching Resharper, so on that front, you're currently out of luck. Thankfully, Apple has already demonstrated versions of Xcode in the works that have vastly improved refactoring capabilities, so hopefully you won't have to wait too long before the situation starts to improve.
[ "objective-c", "xcode", "macos", "refactoring" ]
40
40
12,781
5
0
2008-08-21T16:18:41.460000
2008-08-21T20:33:18.150000
20,426
21,636
How to maintain a recursive invariant in a MySQL database?
I have a tree encoded in a MySQL database as edges: CREATE TABLE items ( num INT, tot INT, PRIMARY KEY (num) ); CREATE TABLE tree ( orig INT, term INT FOREIGN KEY (orig,term) REFERENCES items (num,num) ) For each leaf in the tree, items.tot is set by someone. For interior nodes, items.tot needs to be the sum of it's children. Running the following query repeatedly would generate the desired result. UPDATE items SET tot = ( SELECT SUM(b.tot) FROM tree JOIN items AS b ON tree.term = b.num WHERE tree.orig=items.num) WHERE EXISTS (SELECT * FROM tree WHERE orig=items.num) (note this actually doesn't work but that's beside the point) Assume that the database exists and the invariant are already satisfied. The question is: What is the most practical way to update the DB while maintaining this requirement? Updates may move nodes around or alter the value of tot on leaf nodes. It can be assumed that leaf nodes will stay as leaf nodes, interior nodes will stay as interior nodes and the whole thing will remain as a proper tree. Some thoughts I have had: Full Invalidation, after any update, recompute everything (Um... No) Set a trigger on the items table to update the parent of any row that is updated This would be recursive (updates trigger updates, trigger updates,...) Doesn't work, MySQL can't update the table that kicked off the trigger Set a trigger to schedule an update of the parent of any row that is updated This would be iterative (get an item from the schedule, processing it schedules more items) What kicks this off? Trust client code to get it right? An advantage is that if the updates are ordered correctly fewer sums need to be computer. But that ordering is a complication in and of it's own. An ideal solution would generalize to other "aggregating invariants" FWIW I know this is "a bit overboard", but I'm doing this for fun (Fun: verb, Finding the impossible by doing it.:-)
The problem you are having is clear, recursion in SQL. You need to get the parent of the parent... of the leaf and updates it's total (either subtracting the old and adding the new, or recomputing). You need some form of identifier to see the structure of the tree, and grab all of a nodes children and a list of the parents/path to a leaf to update. This method adds constant space (2 columns to your table --but you only need one table, else you can do a join later). I played around with a structure awhile ago that used a hierarchical format using 'left' and 'right' columns (obviously not those names), calculated by a pre-order traversal and a post-order traversal, respectively --don't worry these don't need to be recalculated every time. I'll let you take a look at a page using this method in mysql instead of continuing this discussion in case you don't like this method as an answer. But if you like it, post/edit and I'll take some time and clarify.
How to maintain a recursive invariant in a MySQL database? I have a tree encoded in a MySQL database as edges: CREATE TABLE items ( num INT, tot INT, PRIMARY KEY (num) ); CREATE TABLE tree ( orig INT, term INT FOREIGN KEY (orig,term) REFERENCES items (num,num) ) For each leaf in the tree, items.tot is set by someone. For interior nodes, items.tot needs to be the sum of it's children. Running the following query repeatedly would generate the desired result. UPDATE items SET tot = ( SELECT SUM(b.tot) FROM tree JOIN items AS b ON tree.term = b.num WHERE tree.orig=items.num) WHERE EXISTS (SELECT * FROM tree WHERE orig=items.num) (note this actually doesn't work but that's beside the point) Assume that the database exists and the invariant are already satisfied. The question is: What is the most practical way to update the DB while maintaining this requirement? Updates may move nodes around or alter the value of tot on leaf nodes. It can be assumed that leaf nodes will stay as leaf nodes, interior nodes will stay as interior nodes and the whole thing will remain as a proper tree. Some thoughts I have had: Full Invalidation, after any update, recompute everything (Um... No) Set a trigger on the items table to update the parent of any row that is updated This would be recursive (updates trigger updates, trigger updates,...) Doesn't work, MySQL can't update the table that kicked off the trigger Set a trigger to schedule an update of the parent of any row that is updated This would be iterative (get an item from the schedule, processing it schedules more items) What kicks this off? Trust client code to get it right? An advantage is that if the updates are ordered correctly fewer sums need to be computer. But that ordering is a complication in and of it's own. An ideal solution would generalize to other "aggregating invariants" FWIW I know this is "a bit overboard", but I'm doing this for fun (Fun: verb, Finding the impossible by doing it.:-)
TITLE: How to maintain a recursive invariant in a MySQL database? QUESTION: I have a tree encoded in a MySQL database as edges: CREATE TABLE items ( num INT, tot INT, PRIMARY KEY (num) ); CREATE TABLE tree ( orig INT, term INT FOREIGN KEY (orig,term) REFERENCES items (num,num) ) For each leaf in the tree, items.tot is set by someone. For interior nodes, items.tot needs to be the sum of it's children. Running the following query repeatedly would generate the desired result. UPDATE items SET tot = ( SELECT SUM(b.tot) FROM tree JOIN items AS b ON tree.term = b.num WHERE tree.orig=items.num) WHERE EXISTS (SELECT * FROM tree WHERE orig=items.num) (note this actually doesn't work but that's beside the point) Assume that the database exists and the invariant are already satisfied. The question is: What is the most practical way to update the DB while maintaining this requirement? Updates may move nodes around or alter the value of tot on leaf nodes. It can be assumed that leaf nodes will stay as leaf nodes, interior nodes will stay as interior nodes and the whole thing will remain as a proper tree. Some thoughts I have had: Full Invalidation, after any update, recompute everything (Um... No) Set a trigger on the items table to update the parent of any row that is updated This would be recursive (updates trigger updates, trigger updates,...) Doesn't work, MySQL can't update the table that kicked off the trigger Set a trigger to schedule an update of the parent of any row that is updated This would be iterative (get an item from the schedule, processing it schedules more items) What kicks this off? Trust client code to get it right? An advantage is that if the updates are ordered correctly fewer sums need to be computer. But that ordering is a complication in and of it's own. An ideal solution would generalize to other "aggregating invariants" FWIW I know this is "a bit overboard", but I'm doing this for fun (Fun: verb, Finding the impossible by doing it.:-) ANSWER: The problem you are having is clear, recursion in SQL. You need to get the parent of the parent... of the leaf and updates it's total (either subtracting the old and adding the new, or recomputing). You need some form of identifier to see the structure of the tree, and grab all of a nodes children and a list of the parents/path to a leaf to update. This method adds constant space (2 columns to your table --but you only need one table, else you can do a join later). I played around with a structure awhile ago that used a hierarchical format using 'left' and 'right' columns (obviously not those names), calculated by a pre-order traversal and a post-order traversal, respectively --don't worry these don't need to be recalculated every time. I'll let you take a look at a page using this method in mysql instead of continuing this discussion in case you don't like this method as an answer. But if you like it, post/edit and I'll take some time and clarify.
[ "mysql", "algorithm", "data-structures", "invariants" ]
2
1
1,242
2
0
2008-08-21T16:20:12.563000
2008-08-22T02:14:04.820000
20,450
20,628
Cleaning up RTF text
I'd like to take some RTF input and clean it to remove all RTF formatting except \ul \b \i to paste it into Word with minor format information. The command used to paste into Word will be something like: oWord.ActiveDocument.ActiveWindow.Selection.PasteAndFormat(0) (with some RTF text already in the Clipboard) {\rtf1\ansi\deff0{\fonttbl{\f0\fnil\fcharset0 Courier New;}} {\colortbl;\red255\green255\blue140;} \viewkind4\uc1\pard\highlight1\lang3084\f0\fs18 The company is a global leader in responsible tourism and was \ul the first major hotel chain in North America\ulnone to embrace environmental stewardship within its daily operations\highlight0\par Do you have any idea on how I can clean up the RTF safely with some regular expressions or something? I am using VB.NET to do the processing but any.NET language sample will do.
I would use a hidden RichTextBox, set the Rtf member, then retrieve the Text member to sanitize the RTF in a well-supported way. Then I would use manually inject the desired formatting afterwards.
Cleaning up RTF text I'd like to take some RTF input and clean it to remove all RTF formatting except \ul \b \i to paste it into Word with minor format information. The command used to paste into Word will be something like: oWord.ActiveDocument.ActiveWindow.Selection.PasteAndFormat(0) (with some RTF text already in the Clipboard) {\rtf1\ansi\deff0{\fonttbl{\f0\fnil\fcharset0 Courier New;}} {\colortbl;\red255\green255\blue140;} \viewkind4\uc1\pard\highlight1\lang3084\f0\fs18 The company is a global leader in responsible tourism and was \ul the first major hotel chain in North America\ulnone to embrace environmental stewardship within its daily operations\highlight0\par Do you have any idea on how I can clean up the RTF safely with some regular expressions or something? I am using VB.NET to do the processing but any.NET language sample will do.
TITLE: Cleaning up RTF text QUESTION: I'd like to take some RTF input and clean it to remove all RTF formatting except \ul \b \i to paste it into Word with minor format information. The command used to paste into Word will be something like: oWord.ActiveDocument.ActiveWindow.Selection.PasteAndFormat(0) (with some RTF text already in the Clipboard) {\rtf1\ansi\deff0{\fonttbl{\f0\fnil\fcharset0 Courier New;}} {\colortbl;\red255\green255\blue140;} \viewkind4\uc1\pard\highlight1\lang3084\f0\fs18 The company is a global leader in responsible tourism and was \ul the first major hotel chain in North America\ulnone to embrace environmental stewardship within its daily operations\highlight0\par Do you have any idea on how I can clean up the RTF safely with some regular expressions or something? I am using VB.NET to do the processing but any.NET language sample will do. ANSWER: I would use a hidden RichTextBox, set the Rtf member, then retrieve the Text member to sanitize the RTF in a well-supported way. Then I would use manually inject the desired formatting afterwards.
[ ".net", "vb.net", "ms-word", "rtf" ]
12
6
20,154
4
0
2008-08-21T16:30:49.980000
2008-08-21T17:39:40.503000
20,463
20,485
What is the point of interfaces in PHP?
Interfaces allow you to create code that defines the methods of classes that implement it. You cannot however add any code to those methods. Abstract classes allow you to do the same thing, along with adding code to the method. Now if you can achieve the same goal with abstract classes, why do we even need the concept of interfaces? I've been told that it has to do with OO theory from C++ to Java, which is what PHP's OO stuff is based on. Is the concept useful in Java but not in PHP? Is it just a way to keep from having placeholders littered in the abstract class? Am I missing something?
The entire point of interfaces is to give you the flexibility to have your class be forced to implement multiple interfaces, but still not allow multiple inheritance. The issues with inheriting from multiple classes are many and varied and the wikipedia page on it sums them up pretty well. Interfaces are a compromise. Most of the problems with multiple inheritance don't apply to abstract base classes, so most modern languages these days disable multiple inheritance yet call abstract base classes interfaces and allows a class to "implement" as many of those as they want.
What is the point of interfaces in PHP? Interfaces allow you to create code that defines the methods of classes that implement it. You cannot however add any code to those methods. Abstract classes allow you to do the same thing, along with adding code to the method. Now if you can achieve the same goal with abstract classes, why do we even need the concept of interfaces? I've been told that it has to do with OO theory from C++ to Java, which is what PHP's OO stuff is based on. Is the concept useful in Java but not in PHP? Is it just a way to keep from having placeholders littered in the abstract class? Am I missing something?
TITLE: What is the point of interfaces in PHP? QUESTION: Interfaces allow you to create code that defines the methods of classes that implement it. You cannot however add any code to those methods. Abstract classes allow you to do the same thing, along with adding code to the method. Now if you can achieve the same goal with abstract classes, why do we even need the concept of interfaces? I've been told that it has to do with OO theory from C++ to Java, which is what PHP's OO stuff is based on. Is the concept useful in Java but not in PHP? Is it just a way to keep from having placeholders littered in the abstract class? Am I missing something? ANSWER: The entire point of interfaces is to give you the flexibility to have your class be forced to implement multiple interfaces, but still not allow multiple inheritance. The issues with inheriting from multiple classes are many and varied and the wikipedia page on it sums them up pretty well. Interfaces are a compromise. Most of the problems with multiple inheritance don't apply to abstract base classes, so most modern languages these days disable multiple inheritance yet call abstract base classes interfaces and allows a class to "implement" as many of those as they want.
[ "php", "oop", "interface", "theory" ]
244
148
102,239
15
0
2008-08-21T16:35:20.657000
2008-08-21T16:45:54.390000
20,465
26,691
.NET - Excel ListObject autosizing on databind
I'm developing an Excel 2007 add-in using Visual Studio Tools for Office (2008). I have one sheet with several ListObjects on it, which are being bound to datatables on startup. When they are bound, they autosize correctly. The problem comes when they are re-bound. I have a custom button on the ribbon bar which goes back out to the database and retrieves different information based on some criteria that the user inputs. This new data comes back and is re-bound to the ListObjects - however, this time they are not resized and I get an exception: ListObject cannot be bound because it cannot be resized to fit the data. The ListObject failed to add new rows. This can be caused because of inability to move objects below of the list object. Inner exception: "Insert method of Range class failed" Reason: Microsoft.Office.Tools.Excel.FailureReason.CouldNotResizeListObject I was not able to find anything very meaningful on this error on Google or MSDN. I have been trying to figure this out for a while, but to no avail. Basic code structure: //at startup DataTable tbl = //get from database listObj1.SetDataBinding(tbl); DataTable tbl2 = //get from database listObj2.SetDataBinding(tbl2); //in buttonClick event handler DataTable tbl = //get different info from database //have tried with and without unbinding old source listObj1.SetDataBinding(tbl); <-- exception here DataTable tbl2 = //get different info from database listObj2.SetDataBinding(tbl2); Note that this exception occurs even when the ListObject is shrinking, and not only when it grows.
If anyone else is having this problem, I have found the cause of this exception. ListObjects will automatically re-size on binding, as long as they do not affect any other objects on the sheet. Keep in mind that ListObjects can only affect the Ranges which they wrap around. In my case, the list object which was above the other one had fewer columns than the one below it. Let's say the top ListObject had 2 columns, and the bottom ListObject had 3 columns. When the top ListObject changed its number of rows, it had no ability to make any changes to the third column since it wasn't in it's underlying Range. This means that it couldn't shift any cells in the third column, and so the second ListObject couldn't be properly moved, resulting in my exception above. Changing the positions of the ListObjects to place the wider one above the smaller one works fine. Following the logic above, this now means that the wider ListObject can shift all of the columns of the second ListObject, and since there is nothing below the smaller one it can also shift any cells necessary. The reason I wasn't having any trouble on the initial binding is that both ListObjects were a single cell. Since this is not optimal in my case, I will probably use empty columns or try to play around with invisible columns if that's possible, but at least the cause is now clear.
.NET - Excel ListObject autosizing on databind I'm developing an Excel 2007 add-in using Visual Studio Tools for Office (2008). I have one sheet with several ListObjects on it, which are being bound to datatables on startup. When they are bound, they autosize correctly. The problem comes when they are re-bound. I have a custom button on the ribbon bar which goes back out to the database and retrieves different information based on some criteria that the user inputs. This new data comes back and is re-bound to the ListObjects - however, this time they are not resized and I get an exception: ListObject cannot be bound because it cannot be resized to fit the data. The ListObject failed to add new rows. This can be caused because of inability to move objects below of the list object. Inner exception: "Insert method of Range class failed" Reason: Microsoft.Office.Tools.Excel.FailureReason.CouldNotResizeListObject I was not able to find anything very meaningful on this error on Google or MSDN. I have been trying to figure this out for a while, but to no avail. Basic code structure: //at startup DataTable tbl = //get from database listObj1.SetDataBinding(tbl); DataTable tbl2 = //get from database listObj2.SetDataBinding(tbl2); //in buttonClick event handler DataTable tbl = //get different info from database //have tried with and without unbinding old source listObj1.SetDataBinding(tbl); <-- exception here DataTable tbl2 = //get different info from database listObj2.SetDataBinding(tbl2); Note that this exception occurs even when the ListObject is shrinking, and not only when it grows.
TITLE: .NET - Excel ListObject autosizing on databind QUESTION: I'm developing an Excel 2007 add-in using Visual Studio Tools for Office (2008). I have one sheet with several ListObjects on it, which are being bound to datatables on startup. When they are bound, they autosize correctly. The problem comes when they are re-bound. I have a custom button on the ribbon bar which goes back out to the database and retrieves different information based on some criteria that the user inputs. This new data comes back and is re-bound to the ListObjects - however, this time they are not resized and I get an exception: ListObject cannot be bound because it cannot be resized to fit the data. The ListObject failed to add new rows. This can be caused because of inability to move objects below of the list object. Inner exception: "Insert method of Range class failed" Reason: Microsoft.Office.Tools.Excel.FailureReason.CouldNotResizeListObject I was not able to find anything very meaningful on this error on Google or MSDN. I have been trying to figure this out for a while, but to no avail. Basic code structure: //at startup DataTable tbl = //get from database listObj1.SetDataBinding(tbl); DataTable tbl2 = //get from database listObj2.SetDataBinding(tbl2); //in buttonClick event handler DataTable tbl = //get different info from database //have tried with and without unbinding old source listObj1.SetDataBinding(tbl); <-- exception here DataTable tbl2 = //get different info from database listObj2.SetDataBinding(tbl2); Note that this exception occurs even when the ListObject is shrinking, and not only when it grows. ANSWER: If anyone else is having this problem, I have found the cause of this exception. ListObjects will automatically re-size on binding, as long as they do not affect any other objects on the sheet. Keep in mind that ListObjects can only affect the Ranges which they wrap around. In my case, the list object which was above the other one had fewer columns than the one below it. Let's say the top ListObject had 2 columns, and the bottom ListObject had 3 columns. When the top ListObject changed its number of rows, it had no ability to make any changes to the third column since it wasn't in it's underlying Range. This means that it couldn't shift any cells in the third column, and so the second ListObject couldn't be properly moved, resulting in my exception above. Changing the positions of the ListObjects to place the wider one above the smaller one works fine. Following the logic above, this now means that the wider ListObject can shift all of the columns of the second ListObject, and since there is nothing below the smaller one it can also shift any cells necessary. The reason I wasn't having any trouble on the initial binding is that both ListObjects were a single cell. Since this is not optimal in my case, I will probably use empty columns or try to play around with invisible columns if that's possible, but at least the cause is now clear.
[ "c#", ".net", "excel", "data-binding", "vsto" ]
7
5
3,319
3
0
2008-08-21T16:36:12.027000
2008-08-25T19:30:44.243000
20,467
20,495
Path Display in Label
Are there any automatic methods for trimming a path string in.NET? For example: C:\Documents and Settings\nick\My Documents\Tests\demo data\demo data.emx becomes C:\Documents...\demo data.emx It would be particularly cool if this were built into the Label class, and I seem to recall it is--can't find it though!
Use TextRenderer.DrawText with TextFormatFlags.PathEllipsis flag void label_Paint(object sender, PaintEventArgs e) { Label label = (Label)sender; TextRenderer.DrawText(e.Graphics, label.Text, label.Font, label.ClientRectangle, label.ForeColor, TextFormatFlags.PathEllipsis); } Your code is 95% there. The only problem is that the trimmed text is drawn on top of the text which is already on the label. Yes thanks, I was aware of that. My intention was only to demonstrate use of DrawText method. I didn't know whether you want to manually create event for each label or just override OnPaint() method in inherited label. Thanks for sharing your final solution though.
Path Display in Label Are there any automatic methods for trimming a path string in.NET? For example: C:\Documents and Settings\nick\My Documents\Tests\demo data\demo data.emx becomes C:\Documents...\demo data.emx It would be particularly cool if this were built into the Label class, and I seem to recall it is--can't find it though!
TITLE: Path Display in Label QUESTION: Are there any automatic methods for trimming a path string in.NET? For example: C:\Documents and Settings\nick\My Documents\Tests\demo data\demo data.emx becomes C:\Documents...\demo data.emx It would be particularly cool if this were built into the Label class, and I seem to recall it is--can't find it though! ANSWER: Use TextRenderer.DrawText with TextFormatFlags.PathEllipsis flag void label_Paint(object sender, PaintEventArgs e) { Label label = (Label)sender; TextRenderer.DrawText(e.Graphics, label.Text, label.Font, label.ClientRectangle, label.ForeColor, TextFormatFlags.PathEllipsis); } Your code is 95% there. The only problem is that the trimmed text is drawn on top of the text which is already on the label. Yes thanks, I was aware of that. My intention was only to demonstrate use of DrawText method. I didn't know whether you want to manually create event for each label or just override OnPaint() method in inherited label. Thanks for sharing your final solution though.
[ "c#", ".net", "winforms", "path" ]
6
9
3,567
6
0
2008-08-21T16:38:29.807000
2008-08-21T16:49:29.640000
20,484
20,538
Use a LIKE clause in part of an INNER JOIN
Can/Should I use a LIKE criteria as part of an INNER JOIN when building a stored procedure/query? I'm not sure I'm asking the right thing, so let me explain. I'm creating a procedure that is going to take a list of keywords to be searched for in a column that contains text. If I was sitting at the console, I'd execute it as such: SELECT Id, Name, Description FROM dbo.Card WHERE Description LIKE '%warrior%' OR Description LIKE '%fiend%' OR Description LIKE '%damage%' But a trick I picked up a little while go to do "strongly typed" list parsing in a stored procedure is to parse the list into a table variable/temporary table, converting it to the proper type and then doing an INNER JOIN against that table in my final result set. This works great when sending say a list of integer IDs to the procedure. I wind up having a final query that looks like this: SELECT Id, Name, Description FROM dbo.Card INNER JOIN @tblExclusiveCard ON dbo.Card.Id = @tblExclusiveCard.CardId I want to use this trick with a list of strings. But since I'm looking for a particular keyword, I am going to use the LIKE clause. So ideally I'm thinking I'd have my final query look like this: SELECT Id, Name, Description FROM dbo.Card INNER JOIN @tblKeyword ON dbo.Card.Description LIKE '%' + @tblKeyword.Value + '%' Is this possible/recommended? Is there a better way to do something like this? The reason I'm putting wildcards on both ends of the clause is because there are "archfiend", "beast-warrior", "direct-damage" and "battle-damage" terms that are used in the card texts. I'm getting the impression that depending on the performance, I can either use the query I specified or use a full-text keyword search to accomplish the same task? Other than having the server do a text index on the fields I want to text search, is there anything else I need to do?
Your first query will work but will require a full table scan because any index on that column will be ignored. You will also have to do some dynamic SQL to generate all your LIKE clauses. Try a full text search if your using SQL Server or check out one of the Lucene implementations. Joel talked about his success with it recently.
Use a LIKE clause in part of an INNER JOIN Can/Should I use a LIKE criteria as part of an INNER JOIN when building a stored procedure/query? I'm not sure I'm asking the right thing, so let me explain. I'm creating a procedure that is going to take a list of keywords to be searched for in a column that contains text. If I was sitting at the console, I'd execute it as such: SELECT Id, Name, Description FROM dbo.Card WHERE Description LIKE '%warrior%' OR Description LIKE '%fiend%' OR Description LIKE '%damage%' But a trick I picked up a little while go to do "strongly typed" list parsing in a stored procedure is to parse the list into a table variable/temporary table, converting it to the proper type and then doing an INNER JOIN against that table in my final result set. This works great when sending say a list of integer IDs to the procedure. I wind up having a final query that looks like this: SELECT Id, Name, Description FROM dbo.Card INNER JOIN @tblExclusiveCard ON dbo.Card.Id = @tblExclusiveCard.CardId I want to use this trick with a list of strings. But since I'm looking for a particular keyword, I am going to use the LIKE clause. So ideally I'm thinking I'd have my final query look like this: SELECT Id, Name, Description FROM dbo.Card INNER JOIN @tblKeyword ON dbo.Card.Description LIKE '%' + @tblKeyword.Value + '%' Is this possible/recommended? Is there a better way to do something like this? The reason I'm putting wildcards on both ends of the clause is because there are "archfiend", "beast-warrior", "direct-damage" and "battle-damage" terms that are used in the card texts. I'm getting the impression that depending on the performance, I can either use the query I specified or use a full-text keyword search to accomplish the same task? Other than having the server do a text index on the fields I want to text search, is there anything else I need to do?
TITLE: Use a LIKE clause in part of an INNER JOIN QUESTION: Can/Should I use a LIKE criteria as part of an INNER JOIN when building a stored procedure/query? I'm not sure I'm asking the right thing, so let me explain. I'm creating a procedure that is going to take a list of keywords to be searched for in a column that contains text. If I was sitting at the console, I'd execute it as such: SELECT Id, Name, Description FROM dbo.Card WHERE Description LIKE '%warrior%' OR Description LIKE '%fiend%' OR Description LIKE '%damage%' But a trick I picked up a little while go to do "strongly typed" list parsing in a stored procedure is to parse the list into a table variable/temporary table, converting it to the proper type and then doing an INNER JOIN against that table in my final result set. This works great when sending say a list of integer IDs to the procedure. I wind up having a final query that looks like this: SELECT Id, Name, Description FROM dbo.Card INNER JOIN @tblExclusiveCard ON dbo.Card.Id = @tblExclusiveCard.CardId I want to use this trick with a list of strings. But since I'm looking for a particular keyword, I am going to use the LIKE clause. So ideally I'm thinking I'd have my final query look like this: SELECT Id, Name, Description FROM dbo.Card INNER JOIN @tblKeyword ON dbo.Card.Description LIKE '%' + @tblKeyword.Value + '%' Is this possible/recommended? Is there a better way to do something like this? The reason I'm putting wildcards on both ends of the clause is because there are "archfiend", "beast-warrior", "direct-damage" and "battle-damage" terms that are used in the card texts. I'm getting the impression that depending on the performance, I can either use the query I specified or use a full-text keyword search to accomplish the same task? Other than having the server do a text index on the fields I want to text search, is there anything else I need to do? ANSWER: Your first query will work but will require a full table scan because any index on that column will be ignored. You will also have to do some dynamic SQL to generate all your LIKE clauses. Try a full text search if your using SQL Server or check out one of the Lucene implementations. Joel talked about his success with it recently.
[ "sql", "sql-server", "design-patterns" ]
20
5
107,644
10
0
2008-08-21T16:45:48.183000
2008-08-21T17:06:11.050000
20,510
20,645
Executing JavaScript from Flex: Is this javascript function dangerous?
I have a flex application that needs the ability to generate and execute JavaScript. When I say this, I mean I need to execute raw JavaScript that I create in my Flex application (not just an existing JavaScript method) I am currently doing this by exposing the following JavaScript method: function doScript(js){ eval(js);} I can then do something like this in Flex (note: I am doing something more substantial then an alert box in the real Flex app): ExternalInterface.call("doScript","alert('foo')); My question is does this impose any security risk, I am assuming it's not since the Flex and JasvaScript all run client side... Is there a better way to do this?
There's no need for the JavaScript function, the first argument to ExternalInterface can be any JavaScript code, it doesn't have to be a function name (the documentation says so, but it is wrong). Try this: ExternalInterface.call("alert('hello')");
Executing JavaScript from Flex: Is this javascript function dangerous? I have a flex application that needs the ability to generate and execute JavaScript. When I say this, I mean I need to execute raw JavaScript that I create in my Flex application (not just an existing JavaScript method) I am currently doing this by exposing the following JavaScript method: function doScript(js){ eval(js);} I can then do something like this in Flex (note: I am doing something more substantial then an alert box in the real Flex app): ExternalInterface.call("doScript","alert('foo')); My question is does this impose any security risk, I am assuming it's not since the Flex and JasvaScript all run client side... Is there a better way to do this?
TITLE: Executing JavaScript from Flex: Is this javascript function dangerous? QUESTION: I have a flex application that needs the ability to generate and execute JavaScript. When I say this, I mean I need to execute raw JavaScript that I create in my Flex application (not just an existing JavaScript method) I am currently doing this by exposing the following JavaScript method: function doScript(js){ eval(js);} I can then do something like this in Flex (note: I am doing something more substantial then an alert box in the real Flex app): ExternalInterface.call("doScript","alert('foo')); My question is does this impose any security risk, I am assuming it's not since the Flex and JasvaScript all run client side... Is there a better way to do this? ANSWER: There's no need for the JavaScript function, the first argument to ExternalInterface can be any JavaScript code, it doesn't have to be a function name (the documentation says so, but it is wrong). Try this: ExternalInterface.call("alert('hello')");
[ "javascript", "apache-flex", "exploit" ]
6
8
3,167
6
0
2008-08-21T16:55:09.813000
2008-08-21T17:43:48.543000
20,529
20,631
Useful Eclipse features?
I have been using Eclipse as an IDE for a short amount of time (about 3 months of full use) and almost every day I learn about some shortcut or feature that I had absolutely no idea about. For instance, just today I learned that Ctrl + 3 was the shortcut for a Quick Access window. I was wondering what your most useful/favorite Eclipse features are. With the IDE being so big, it would be helpful to learn about the more commonly used parts of the program.
My most commonly used features are ctrl + 1 quick-fix / spell-checker opening files ctrl + shift + t load class file by classname ctrl + shift + r load any file by filename matches are made on the start of the class/filename. start your search pattern with a * to search anywhere within the filename/classname. Formatting ctrl + shift + f Format source file (set up your formatting style in Window | preferences | java | code style | formatter) ctrl + shift + o Organise imports Generated code alt + s, r to generate getters and setters alt + s, v to insert method signatures for overidden methods from superclass or interface Refactorings alt + shift + l Extract text-selection as local variable (really handy in that it determines and inserts the type for you. alt + shift + m Extract text-selection as a method alt + shift + i inline selected method Running and debugging. alt + shift + x is a really handy prefix to run stuff in your current file. alt + shift + x, t run unit tests in current file alt + shift + x, j run main in current file alt + shift + x, r run on server There are more. The options are shown to you in the lower-right popup after hitting alt + shift + x. alt + shift + x can be switched for alt + shift + d in all the above examples to run in the debugger. Validation As of the recent Ganymede release, you can now switch of validation in specified files and folders. I've been waiting for this feature for ages. Go to Project | Properties | Validation click on the... button in the settings column of the validator you want to shut up Add a rule to the exclude group code navigation hold down ctrl to make all variables, methods and classnames hyperlinks to their definitions. alt + left to navigate back to where you clicked ctrl alt + right to go "forwards" again
Useful Eclipse features? I have been using Eclipse as an IDE for a short amount of time (about 3 months of full use) and almost every day I learn about some shortcut or feature that I had absolutely no idea about. For instance, just today I learned that Ctrl + 3 was the shortcut for a Quick Access window. I was wondering what your most useful/favorite Eclipse features are. With the IDE being so big, it would be helpful to learn about the more commonly used parts of the program.
TITLE: Useful Eclipse features? QUESTION: I have been using Eclipse as an IDE for a short amount of time (about 3 months of full use) and almost every day I learn about some shortcut or feature that I had absolutely no idea about. For instance, just today I learned that Ctrl + 3 was the shortcut for a Quick Access window. I was wondering what your most useful/favorite Eclipse features are. With the IDE being so big, it would be helpful to learn about the more commonly used parts of the program. ANSWER: My most commonly used features are ctrl + 1 quick-fix / spell-checker opening files ctrl + shift + t load class file by classname ctrl + shift + r load any file by filename matches are made on the start of the class/filename. start your search pattern with a * to search anywhere within the filename/classname. Formatting ctrl + shift + f Format source file (set up your formatting style in Window | preferences | java | code style | formatter) ctrl + shift + o Organise imports Generated code alt + s, r to generate getters and setters alt + s, v to insert method signatures for overidden methods from superclass or interface Refactorings alt + shift + l Extract text-selection as local variable (really handy in that it determines and inserts the type for you. alt + shift + m Extract text-selection as a method alt + shift + i inline selected method Running and debugging. alt + shift + x is a really handy prefix to run stuff in your current file. alt + shift + x, t run unit tests in current file alt + shift + x, j run main in current file alt + shift + x, r run on server There are more. The options are shown to you in the lower-right popup after hitting alt + shift + x. alt + shift + x can be switched for alt + shift + d in all the above examples to run in the debugger. Validation As of the recent Ganymede release, you can now switch of validation in specified files and folders. I've been waiting for this feature for ages. Go to Project | Properties | Validation click on the... button in the settings column of the validator you want to shut up Add a rule to the exclude group code navigation hold down ctrl to make all variables, methods and classnames hyperlinks to their definitions. alt + left to navigate back to where you clicked ctrl alt + right to go "forwards" again
[ "eclipse" ]
68
73
23,884
23
0
2008-08-21T17:01:20
2008-08-21T17:39:52.110000
20,533
20,543
List of macOS text editors and code editors
I searched for this and found Maudite's question about text editors but they were all for Windows. As you have no doubt guessed, I am trying to find out if there are any text/code editors for the Mac besides what I know of. I'll edit my post to include editors listed. Free Textwrangler Xcode Mac Vim Aquamacs and closer to the original EMacs JEdit Editra Eclipse NetBeans Kod TextMate2 - GPL Brackets Atom.io Commercial Textmate BBEdit SubEthaEdit Coda Sublime Text 2 Smultron WebStorm Peppermint Articles related to the subject Faceoff, which is the best text editor ever? Maceditors.com, mac editors features compared Thank you everybody that has added suggestions.
I haven't used it myself, but another free one that I've heard good thing about is Smultron. In my own research on this, I found this interesting article: Faceoff: Which Is The Best Mac Text Editor Ever?
List of macOS text editors and code editors I searched for this and found Maudite's question about text editors but they were all for Windows. As you have no doubt guessed, I am trying to find out if there are any text/code editors for the Mac besides what I know of. I'll edit my post to include editors listed. Free Textwrangler Xcode Mac Vim Aquamacs and closer to the original EMacs JEdit Editra Eclipse NetBeans Kod TextMate2 - GPL Brackets Atom.io Commercial Textmate BBEdit SubEthaEdit Coda Sublime Text 2 Smultron WebStorm Peppermint Articles related to the subject Faceoff, which is the best text editor ever? Maceditors.com, mac editors features compared Thank you everybody that has added suggestions.
TITLE: List of macOS text editors and code editors QUESTION: I searched for this and found Maudite's question about text editors but they were all for Windows. As you have no doubt guessed, I am trying to find out if there are any text/code editors for the Mac besides what I know of. I'll edit my post to include editors listed. Free Textwrangler Xcode Mac Vim Aquamacs and closer to the original EMacs JEdit Editra Eclipse NetBeans Kod TextMate2 - GPL Brackets Atom.io Commercial Textmate BBEdit SubEthaEdit Coda Sublime Text 2 Smultron WebStorm Peppermint Articles related to the subject Faceoff, which is the best text editor ever? Maceditors.com, mac editors features compared Thank you everybody that has added suggestions. ANSWER: I haven't used it myself, but another free one that I've heard good thing about is Smultron. In my own research on this, I found this interesting article: Faceoff: Which Is The Best Mac Text Editor Ever?
[ "macos", "editor" ]
176
18
253,314
39
0
2008-08-21T17:03:25.487000
2008-08-21T17:07:53.060000
20,575
20,589
Link from ASP.NET yellow error page directly to VS source code
When an ASP.NET application errors out and generates the yellow-screen display, I'd like to create some kind of link from the error page which would jump directly to the correct line of code in Visual Studio. I'm not sure how to approach this, or if there are any tools already in existence which accomplish it - but I'd love some feedback on where to start. In the event that generating a new error page is necessary, is it possible to replace the standard yellow screen across an entire webserver, rather than having to configure the customized error output for each application?
You would probably need to embed an ActiveX control in the page for something like that to be possible.
Link from ASP.NET yellow error page directly to VS source code When an ASP.NET application errors out and generates the yellow-screen display, I'd like to create some kind of link from the error page which would jump directly to the correct line of code in Visual Studio. I'm not sure how to approach this, or if there are any tools already in existence which accomplish it - but I'd love some feedback on where to start. In the event that generating a new error page is necessary, is it possible to replace the standard yellow screen across an entire webserver, rather than having to configure the customized error output for each application?
TITLE: Link from ASP.NET yellow error page directly to VS source code QUESTION: When an ASP.NET application errors out and generates the yellow-screen display, I'd like to create some kind of link from the error page which would jump directly to the correct line of code in Visual Studio. I'm not sure how to approach this, or if there are any tools already in existence which accomplish it - but I'd love some feedback on where to start. In the event that generating a new error page is necessary, is it possible to replace the standard yellow screen across an entire webserver, rather than having to configure the customized error output for each application? ANSWER: You would probably need to embed an ActiveX control in the page for something like that to be possible.
[ "asp.net", "yellow-screen-of-death" ]
1
1
404
6
0
2008-08-21T17:17:51.273000
2008-08-21T17:22:03.477000
20,586
20,737
Image UriSource and Data Binding
I'm trying to bind a list of custom objects to a WPF Image like this: But it doesn't work. This is the error I'm getting: "Property 'UriSource' or property 'StreamSource' must be set." What am I missing?
WPF has built-in converters for certain types. If you bind the Image's Source property to a string or Uri value, under the hood WPF will use an ImageSourceConverter to convert the value to an ImageSource. So would work if the ImageSource property was a string representation of a valid URI to an image. You can of course roll your own Binding converter: public class ImageConverter: IValueConverter { public object Convert( object value, Type targetType, object parameter, CultureInfo culture) { return new BitmapImage(new Uri(value.ToString())); } public object ConvertBack( object value, Type targetType, object parameter, CultureInfo culture) { throw new NotSupportedException(); } } and use it like this:
Image UriSource and Data Binding I'm trying to bind a list of custom objects to a WPF Image like this: But it doesn't work. This is the error I'm getting: "Property 'UriSource' or property 'StreamSource' must be set." What am I missing?
TITLE: Image UriSource and Data Binding QUESTION: I'm trying to bind a list of custom objects to a WPF Image like this: But it doesn't work. This is the error I'm getting: "Property 'UriSource' or property 'StreamSource' must be set." What am I missing? ANSWER: WPF has built-in converters for certain types. If you bind the Image's Source property to a string or Uri value, under the hood WPF will use an ImageSourceConverter to convert the value to an ImageSource. So would work if the ImageSource property was a string representation of a valid URI to an image. You can of course roll your own Binding converter: public class ImageConverter: IValueConverter { public object Convert( object value, Type targetType, object parameter, CultureInfo culture) { return new BitmapImage(new Uri(value.ToString())); } public object ConvertBack( object value, Type targetType, object parameter, CultureInfo culture) { throw new NotSupportedException(); } } and use it like this:
[ ".net", "wpf", "data-binding", "xaml" ]
69
85
142,706
6
0
2008-08-21T17:21:01.170000
2008-08-21T18:38:50.580000
20,597
20,622
FTP in NetBeans 6.1
Is there an FTP browser hiding away in NetBeans 6.1? The help manual doesn't even suggest FTP exists. All I've been able to find so far is a tree viewer in the Services panel (no edit controls) and the ability to upload projects, folders and specific files from the Projects/Files views. Is there anywhere to delete or rename or will I have to keep switching back to my browser? I can see from the previews that there's a nice FTP controller in 6.5 but I'm not desperate enough to completely convert to a beta (yet).
It looks like something was recently added to netbeans for php... http://blogs.oracle.com/netbeansphp/entry/ftp_support_added don't know if you can make use of that...
FTP in NetBeans 6.1 Is there an FTP browser hiding away in NetBeans 6.1? The help manual doesn't even suggest FTP exists. All I've been able to find so far is a tree viewer in the Services panel (no edit controls) and the ability to upload projects, folders and specific files from the Projects/Files views. Is there anywhere to delete or rename or will I have to keep switching back to my browser? I can see from the previews that there's a nice FTP controller in 6.5 but I'm not desperate enough to completely convert to a beta (yet).
TITLE: FTP in NetBeans 6.1 QUESTION: Is there an FTP browser hiding away in NetBeans 6.1? The help manual doesn't even suggest FTP exists. All I've been able to find so far is a tree viewer in the Services panel (no edit controls) and the ability to upload projects, folders and specific files from the Projects/Files views. Is there anywhere to delete or rename or will I have to keep switching back to my browser? I can see from the previews that there's a nice FTP controller in 6.5 but I'm not desperate enough to completely convert to a beta (yet). ANSWER: It looks like something was recently added to netbeans for php... http://blogs.oracle.com/netbeansphp/entry/ftp_support_added don't know if you can make use of that...
[ "netbeans", "ftp" ]
1
4
11,792
3
0
2008-08-21T17:26:18.803000
2008-08-21T17:37:48.150000
20,598
20,605
If I have a PHP string in the format YYYY-DD-MM and a timestamp in MySQL, is there a good way to convert between them?
I'm interested in doing comparisons between the date string and the MySQL timestamp. However, I'm not seeing an easy conversion. Am I overlooking something obvious?
Converting from timestamp to format: date('Y-m-d', $timestamp); Converting from formatted to timestamp: mktime(0, 0, 0, $month, $day, $year, $is_dst); See date and mktime for further documentation. When it comes to storing it's up to you whether to use the MySQL DATE format for stroing as a formatted date; as an integer for storing as a UNIX timestamp; or you can use MySQL's TIMESTAMP format which converts a numeric timestamp into a readable format. Check the MySQL Doc for TIMESTAMP info.
If I have a PHP string in the format YYYY-DD-MM and a timestamp in MySQL, is there a good way to convert between them? I'm interested in doing comparisons between the date string and the MySQL timestamp. However, I'm not seeing an easy conversion. Am I overlooking something obvious?
TITLE: If I have a PHP string in the format YYYY-DD-MM and a timestamp in MySQL, is there a good way to convert between them? QUESTION: I'm interested in doing comparisons between the date string and the MySQL timestamp. However, I'm not seeing an easy conversion. Am I overlooking something obvious? ANSWER: Converting from timestamp to format: date('Y-m-d', $timestamp); Converting from formatted to timestamp: mktime(0, 0, 0, $month, $day, $year, $is_dst); See date and mktime for further documentation. When it comes to storing it's up to you whether to use the MySQL DATE format for stroing as a formatted date; as an integer for storing as a UNIX timestamp; or you can use MySQL's TIMESTAMP format which converts a numeric timestamp into a readable format. Check the MySQL Doc for TIMESTAMP info.
[ "php", "mysql", "time", "timestamp", "date" ]
6
14
13,891
6
0
2008-08-21T17:26:23.060000
2008-08-21T17:29:34.113000
20,611
20,625
Removing nodes from an XmlDocument
The following code should find the appropriate project tag and remove it from the XmlDocument, however when I test it, it says: The node to be removed is not a child of this node. Does anyone know the proper way to do this? public void DeleteProject (string projectName) { string ccConfigPath = ConfigurationManager.AppSettings["ConfigPath"]; XmlDocument configDoc = new XmlDocument(); configDoc.Load(ccConfigPath); XmlNodeList projectNodes = configDoc.GetElementsByTagName("project"); for (int i = 0; i < projectNodes.Count; i++) { if (projectNodes[i].Attributes["name"]!= null) { if (projectName == projectNodes[i].Attributes["name"].InnerText) { configDoc.RemoveChild(projectNodes[i]); configDoc.Save(ccConfigPath); } } } } UPDATE Fixed. I did two things: XmlNode project = configDoc.SelectSingleNode("//project[@name='" + projectName + "']"); Replaced the For loop with an XPath query, which wasn't for fixing it, just because it was a better approach. The actual fix was: project.ParentNode.RemoveChild(project); Thanks Pat and Chuck for this suggestion.
Instead of configDoc.RemoveChild(projectNodes[i]); try projectNodes[i].parentNode.RemoveChild(projectNodes[i]);
Removing nodes from an XmlDocument The following code should find the appropriate project tag and remove it from the XmlDocument, however when I test it, it says: The node to be removed is not a child of this node. Does anyone know the proper way to do this? public void DeleteProject (string projectName) { string ccConfigPath = ConfigurationManager.AppSettings["ConfigPath"]; XmlDocument configDoc = new XmlDocument(); configDoc.Load(ccConfigPath); XmlNodeList projectNodes = configDoc.GetElementsByTagName("project"); for (int i = 0; i < projectNodes.Count; i++) { if (projectNodes[i].Attributes["name"]!= null) { if (projectName == projectNodes[i].Attributes["name"].InnerText) { configDoc.RemoveChild(projectNodes[i]); configDoc.Save(ccConfigPath); } } } } UPDATE Fixed. I did two things: XmlNode project = configDoc.SelectSingleNode("//project[@name='" + projectName + "']"); Replaced the For loop with an XPath query, which wasn't for fixing it, just because it was a better approach. The actual fix was: project.ParentNode.RemoveChild(project); Thanks Pat and Chuck for this suggestion.
TITLE: Removing nodes from an XmlDocument QUESTION: The following code should find the appropriate project tag and remove it from the XmlDocument, however when I test it, it says: The node to be removed is not a child of this node. Does anyone know the proper way to do this? public void DeleteProject (string projectName) { string ccConfigPath = ConfigurationManager.AppSettings["ConfigPath"]; XmlDocument configDoc = new XmlDocument(); configDoc.Load(ccConfigPath); XmlNodeList projectNodes = configDoc.GetElementsByTagName("project"); for (int i = 0; i < projectNodes.Count; i++) { if (projectNodes[i].Attributes["name"]!= null) { if (projectName == projectNodes[i].Attributes["name"].InnerText) { configDoc.RemoveChild(projectNodes[i]); configDoc.Save(ccConfigPath); } } } } UPDATE Fixed. I did two things: XmlNode project = configDoc.SelectSingleNode("//project[@name='" + projectName + "']"); Replaced the For loop with an XPath query, which wasn't for fixing it, just because it was a better approach. The actual fix was: project.ParentNode.RemoveChild(project); Thanks Pat and Chuck for this suggestion. ANSWER: Instead of configDoc.RemoveChild(projectNodes[i]); try projectNodes[i].parentNode.RemoveChild(projectNodes[i]);
[ "c#", ".net", "xml", "xmldocument" ]
51
74
99,263
6
0
2008-08-21T17:31:27.247000
2008-08-21T17:38:54.670000
20,627
20,637
why are downloads sometimes tagged md5, sha1 and other hash indicators?
I've seen this all over the place: Download here! SHA1 = 8e1ed2ce9e7e473d38a9dc7824a384a9ac34d7d0 What does it mean? How does a hash come into play as far as downloads and... What use can I make of it? Is this a legacy item where you used to have to verify some checksum after you downloaded the whole file?
It's a security measure. It allows you to verify that the file you just downloaded is the one that the author posted to the site. Note that using hashes from the same website you're getting the files from is not especially secure. Often a good place to get them from is a mailing list announcement where a PGP-signed email contains the link to the file and the hash. Since this answer has been ranked so highly compared to the others for some reason, I'm editing it to add the other major reason mentioned first by the other authors below, which is to verify the integrity of the file after transferring it over the network. So: Security - verify that the file that you downloaded was the one the author originally published Integrity - verify that the file wasn't damaged during transmission over the network.
why are downloads sometimes tagged md5, sha1 and other hash indicators? I've seen this all over the place: Download here! SHA1 = 8e1ed2ce9e7e473d38a9dc7824a384a9ac34d7d0 What does it mean? How does a hash come into play as far as downloads and... What use can I make of it? Is this a legacy item where you used to have to verify some checksum after you downloaded the whole file?
TITLE: why are downloads sometimes tagged md5, sha1 and other hash indicators? QUESTION: I've seen this all over the place: Download here! SHA1 = 8e1ed2ce9e7e473d38a9dc7824a384a9ac34d7d0 What does it mean? How does a hash come into play as far as downloads and... What use can I make of it? Is this a legacy item where you used to have to verify some checksum after you downloaded the whole file? ANSWER: It's a security measure. It allows you to verify that the file you just downloaded is the one that the author posted to the site. Note that using hashes from the same website you're getting the files from is not especially secure. Often a good place to get them from is a mailing list announcement where a PGP-signed email contains the link to the file and the hash. Since this answer has been ranked so highly compared to the others for some reason, I'm editing it to add the other major reason mentioned first by the other authors below, which is to verify the integrity of the file after transferring it over the network. So: Security - verify that the file that you downloaded was the one the author originally published Integrity - verify that the file wasn't damaged during transmission over the network.
[ "hash", "checksum", "download" ]
7
21
3,052
7
0
2008-08-21T17:39:03.390000
2008-08-21T17:41:36.347000
20,658
20,679
Determine if my PC supports HW Virtualization
How, in general, does one determine if a PC supports hardware virtualization? I use VirtualPC to set up parallel test environments and I'd enjoy a bit of a speed boost.
Download this: http://www.cpuid.com/cpuz.php Also check, http://en.wikipedia.org/wiki/X86_virtualization Edit: Additional, I know it's for XEN but the instructions are the same for all VMs that want hardware support. http://wiki.xensource.com/xenwiki/HVM_Compatible_Processors I can't try it from work, but I'm sure it can identify whether you've got the Intel VT or AMD-V instructions. Intel will have a "vmx" instruction and AMD will have a "svm". On linux you can check /proc/cpuinfo, "egrep '(vmx|svm)' /proc/cpuinfo"
Determine if my PC supports HW Virtualization How, in general, does one determine if a PC supports hardware virtualization? I use VirtualPC to set up parallel test environments and I'd enjoy a bit of a speed boost.
TITLE: Determine if my PC supports HW Virtualization QUESTION: How, in general, does one determine if a PC supports hardware virtualization? I use VirtualPC to set up parallel test environments and I'd enjoy a bit of a speed boost. ANSWER: Download this: http://www.cpuid.com/cpuz.php Also check, http://en.wikipedia.org/wiki/X86_virtualization Edit: Additional, I know it's for XEN but the instructions are the same for all VMs that want hardware support. http://wiki.xensource.com/xenwiki/HVM_Compatible_Processors I can't try it from work, but I'm sure it can identify whether you've got the Intel VT or AMD-V instructions. Intel will have a "vmx" instruction and AMD will have a "svm". On linux you can check /proc/cpuinfo, "egrep '(vmx|svm)' /proc/cpuinfo"
[ "virtualization", "virtual-pc" ]
6
11
14,439
8
0
2008-08-21T17:52:09.723000
2008-08-21T18:05:10.283000
20,663
20,698
Do you use AOP (Aspect Oriented Programming) in production software?
AOP is an interesting programming paradigm in my opinion. However, there haven't been discussions about it yet here on stackoverflow (at least I couldn't find them). What do you think about it in general? Do you use AOP in your projects? Or do you think it's rather a niche technology that won't be around for a long time or won't make it into the mainstream (like OOP did, at least in theory;))? If you do use AOP then please let us know which tools you use as well. Thanks!
Yes. Orthogonal concerns, like security, are best done with AOP-style interception. Whether that is done automatically (through something like a dependency injection container) or manually is unimportant to the end goal. One example: the "before/after" attributes in xUnit.net (an open source project I run) are a form of AOP-style method interception. You decorate your test methods with these attributes, and just before and after that test method runs, your code is called. It can be used for things like setting up a database and rolling back the results, changing the security context in which the test runs, etc. Another example: the filter attributes in ASP.NET MVC also act like specialized AOP-style method interceptors. One, for instance, allows you to say how unhandled errors should be treated, if they happen in your action method. Many dependency injection containers, including Castle Windsor and Unity, support this behavior either "in the box" or through the use of extensions.
Do you use AOP (Aspect Oriented Programming) in production software? AOP is an interesting programming paradigm in my opinion. However, there haven't been discussions about it yet here on stackoverflow (at least I couldn't find them). What do you think about it in general? Do you use AOP in your projects? Or do you think it's rather a niche technology that won't be around for a long time or won't make it into the mainstream (like OOP did, at least in theory;))? If you do use AOP then please let us know which tools you use as well. Thanks!
TITLE: Do you use AOP (Aspect Oriented Programming) in production software? QUESTION: AOP is an interesting programming paradigm in my opinion. However, there haven't been discussions about it yet here on stackoverflow (at least I couldn't find them). What do you think about it in general? Do you use AOP in your projects? Or do you think it's rather a niche technology that won't be around for a long time or won't make it into the mainstream (like OOP did, at least in theory;))? If you do use AOP then please let us know which tools you use as well. Thanks! ANSWER: Yes. Orthogonal concerns, like security, are best done with AOP-style interception. Whether that is done automatically (through something like a dependency injection container) or manually is unimportant to the end goal. One example: the "before/after" attributes in xUnit.net (an open source project I run) are a form of AOP-style method interception. You decorate your test methods with these attributes, and just before and after that test method runs, your code is called. It can be used for things like setting up a database and rolling back the results, changing the security context in which the test runs, etc. Another example: the filter attributes in ASP.NET MVC also act like specialized AOP-style method interceptors. One, for instance, allows you to say how unhandled errors should be treated, if they happen in your action method. Many dependency injection containers, including Castle Windsor and Unity, support this behavior either "in the box" or through the use of extensions.
[ "aop", "paradigms" ]
38
15
9,759
11
0
2008-08-21T17:56:10.307000
2008-08-21T18:14:55.037000
20,674
20,746
Is there a way to call a private Class method from an instance in Ruby?
Other than self.class.send:method, args..., of course. I'd like to make a rather complex method available at both the class and instance level without duplicating the code. UPDATE: @Jonathan Branam: that was my assumption, but I wanted to make sure nobody else had found a way around. Visibility in Ruby is very different from that in Java. You're also quite right that private doesn't work on class methods, though this will declare a private class method: class Foo class < NoMethodError: private method 'bar' called for Foo:Class
Here is a code snippet to go along with the question. Using "private" in a class definition does not apply to class methods. You need to use "private_class_method" as in the following example. class Foo def self.private_bar # Complex logic goes here puts "hi" end private_class_method:private_bar class < I don't see a way to get around this. The documentation says that you cannot specify the receive of a private method. Also you can only access a private method from the same instance. The class Foo is a different object than a given instance of Foo. Don't take my answer as final. I'm certainly not an expert, but I wanted to provide a code snippet so that others who attempt to answer will have properly private class methods.
Is there a way to call a private Class method from an instance in Ruby? Other than self.class.send:method, args..., of course. I'd like to make a rather complex method available at both the class and instance level without duplicating the code. UPDATE: @Jonathan Branam: that was my assumption, but I wanted to make sure nobody else had found a way around. Visibility in Ruby is very different from that in Java. You're also quite right that private doesn't work on class methods, though this will declare a private class method: class Foo class < NoMethodError: private method 'bar' called for Foo:Class
TITLE: Is there a way to call a private Class method from an instance in Ruby? QUESTION: Other than self.class.send:method, args..., of course. I'd like to make a rather complex method available at both the class and instance level without duplicating the code. UPDATE: @Jonathan Branam: that was my assumption, but I wanted to make sure nobody else had found a way around. Visibility in Ruby is very different from that in Java. You're also quite right that private doesn't work on class methods, though this will declare a private class method: class Foo class < NoMethodError: private method 'bar' called for Foo:Class ANSWER: Here is a code snippet to go along with the question. Using "private" in a class definition does not apply to class methods. You need to use "private_class_method" as in the following example. class Foo def self.private_bar # Complex logic goes here puts "hi" end private_class_method:private_bar class < I don't see a way to get around this. The documentation says that you cannot specify the receive of a private method. Also you can only access a private method from the same instance. The class Foo is a different object than a given instance of Foo. Don't take my answer as final. I'm certainly not an expert, but I wanted to provide a code snippet so that others who attempt to answer will have properly private class methods.
[ "ruby", "scope", "visibility", "class-method", "access-specifier" ]
18
12
20,125
8
0
2008-08-21T18:02:04.973000
2008-08-21T18:42:39.663000
20,675
20,678
ASP/VBScript - Int() vs CInt()
What is the difference in ASP/VBScript between Int() and CInt()?
Int() The Int function returns the integer part of a specified number. CInt() The CInt function converts an expression to type Integer. And the best answer comes from MSDN CInt differs from the Fix and Int functions, which truncate, rather than round, the fractional part of a number. When the fractional part is exactly 0.5, the CInt function always rounds it to the nearest even number. For example, 0.5 rounds to 0, and 1.5 rounds to 2.
ASP/VBScript - Int() vs CInt() What is the difference in ASP/VBScript between Int() and CInt()?
TITLE: ASP/VBScript - Int() vs CInt() QUESTION: What is the difference in ASP/VBScript between Int() and CInt()? ANSWER: Int() The Int function returns the integer part of a specified number. CInt() The CInt function converts an expression to type Integer. And the best answer comes from MSDN CInt differs from the Fix and Int functions, which truncate, rather than round, the fractional part of a number. When the fractional part is exactly 0.5, the CInt function always rounds it to the nearest even number. For example, 0.5 rounds to 0, and 1.5 rounds to 2.
[ "asp-classic", "vbscript" ]
25
40
60,576
4
0
2008-08-21T18:02:48.263000
2008-08-21T18:04:43.407000
20,684
20,694
Linq to SQL - Underlying Column Length
I've been using Linq to SQL for some time now and I find it to be really helpful and easy to use. With other ORM tools I've used in the past, the entity object filled from the database normally has a property indicating the length of the underlying data column in the database. This is helpful in databinding situations where you can set the MaxLength property on a textbox, for example, to limit the length of input entered by the user. I cannot find a way using Linq to SQL to obtain the length of an underlying data column. Does anyone know of a way to do this? Help please.
Using the LINQ ColumnAttribute to Get Field Lengths from your Database: http://www.codeproject.com/KB/cs/LinqColumnAttributeTricks.aspx
Linq to SQL - Underlying Column Length I've been using Linq to SQL for some time now and I find it to be really helpful and easy to use. With other ORM tools I've used in the past, the entity object filled from the database normally has a property indicating the length of the underlying data column in the database. This is helpful in databinding situations where you can set the MaxLength property on a textbox, for example, to limit the length of input entered by the user. I cannot find a way using Linq to SQL to obtain the length of an underlying data column. Does anyone know of a way to do this? Help please.
TITLE: Linq to SQL - Underlying Column Length QUESTION: I've been using Linq to SQL for some time now and I find it to be really helpful and easy to use. With other ORM tools I've used in the past, the entity object filled from the database normally has a property indicating the length of the underlying data column in the database. This is helpful in databinding situations where you can set the MaxLength property on a textbox, for example, to limit the length of input entered by the user. I cannot find a way using Linq to SQL to obtain the length of an underlying data column. Does anyone know of a way to do this? Help please. ANSWER: Using the LINQ ColumnAttribute to Get Field Lengths from your Database: http://www.codeproject.com/KB/cs/LinqColumnAttributeTricks.aspx
[ "linq-to-sql" ]
8
7
5,624
3
0
2008-08-21T18:07:33.710000
2008-08-21T18:11:20.003000
20,696
37,438
How do I declare a list of fixed length in specman?
In E (specman) I want to declare variables that are lists, and I want to fix their lengths. It's easy to do for a member of a struct: thread[2]: list of thread_t; while for a "regular" variable in a function the above doesn't work, and I have to do something like: var warned: list of bool; gen warned keeping { it.size() == 5; }; Is there a better way to declare a list of fixed size?
A hard keep like you have is only going to fix the size at initialization but elements could still be added or dropped later, are you trying to guard against this condition? The only way I can think of to guarantee that elements aren't added or dropped later is emitting an event synced on the size!= the predetermined amount: event list_size_changed is true (wanted.size()!= 5) @clk; The only other thing that I can offer is a bit of syntactic sugar for the hard keep: var warned: list of bool; keep warned.size() == 5;
How do I declare a list of fixed length in specman? In E (specman) I want to declare variables that are lists, and I want to fix their lengths. It's easy to do for a member of a struct: thread[2]: list of thread_t; while for a "regular" variable in a function the above doesn't work, and I have to do something like: var warned: list of bool; gen warned keeping { it.size() == 5; }; Is there a better way to declare a list of fixed size?
TITLE: How do I declare a list of fixed length in specman? QUESTION: In E (specman) I want to declare variables that are lists, and I want to fix their lengths. It's easy to do for a member of a struct: thread[2]: list of thread_t; while for a "regular" variable in a function the above doesn't work, and I have to do something like: var warned: list of bool; gen warned keeping { it.size() == 5; }; Is there a better way to declare a list of fixed size? ANSWER: A hard keep like you have is only going to fix the size at initialization but elements could still be added or dropped later, are you trying to guard against this condition? The only way I can think of to guarantee that elements aren't added or dropped later is emitting an event synced on the size!= the predetermined amount: event list_size_changed is true (wanted.size()!= 5) @clk; The only other thing that I can offer is a bit of syntactic sugar for the hard keep: var warned: list of bool; keep warned.size() == 5;
[ "specman" ]
1
4
2,075
2
0
2008-08-21T18:13:01.157000
2008-09-01T04:05:48.810000
20,718
20,904
Testing .NET code in partial trust environments
I want to test the behavior of a certain piece of.NET code in partial trust environments. What's the fastest way to set this up? Feel free to assume that I (and other readers) are total CAS noobs. @Nick: Thanks for the reply. Alas, the tool in question is explicitly for unmanaged code. I didn't say "managed" in my question, and should not have assumed that people would infer it from the ".NET" tag.
This is an excellent question, especially from a TDD point of view and validating code under different trust scenarios. I think the way I'd approach this would be something along the lines of - Create an AppDomain in my TDD code using the AppDomain.CreateDomain() overload that allows you to pass in a PermissionSet. The PermissionSet would be constructed to match the different trust scenarios you'd want to test against. Load the assembly containing logic under test into the app domain Create instances of types/call methods etc in app domain, trap security exceptions Something kinda like that. I've not had time to knock up a proof of concept yet.
Testing .NET code in partial trust environments I want to test the behavior of a certain piece of.NET code in partial trust environments. What's the fastest way to set this up? Feel free to assume that I (and other readers) are total CAS noobs. @Nick: Thanks for the reply. Alas, the tool in question is explicitly for unmanaged code. I didn't say "managed" in my question, and should not have assumed that people would infer it from the ".NET" tag.
TITLE: Testing .NET code in partial trust environments QUESTION: I want to test the behavior of a certain piece of.NET code in partial trust environments. What's the fastest way to set this up? Feel free to assume that I (and other readers) are total CAS noobs. @Nick: Thanks for the reply. Alas, the tool in question is explicitly for unmanaged code. I didn't say "managed" in my question, and should not have assumed that people would infer it from the ".NET" tag. ANSWER: This is an excellent question, especially from a TDD point of view and validating code under different trust scenarios. I think the way I'd approach this would be something along the lines of - Create an AppDomain in my TDD code using the AppDomain.CreateDomain() overload that allows you to pass in a PermissionSet. The PermissionSet would be constructed to match the different trust scenarios you'd want to test against. Load the assembly containing logic under test into the app domain Create instances of types/call methods etc in app domain, trap security exceptions Something kinda like that. I've not had time to knock up a proof of concept yet.
[ ".net", "code-access-security" ]
5
3
828
5
0
2008-08-21T18:29:42.847000
2008-08-21T19:31:28.097000
20,722
26,956
Version detection with Silverlight
How can I efficiently and effectively detect the version and, for that matter, any available information about the instance of Silverlight currently running on the browser?
The Silverlight control only has an IsVersionSupported function, which returns true / false when you give it a version number, e.g.: if(slPlugin.isVersionSupported("2.0")) { alert("I haz some flavour of Silverlight 2"); You can be as specific as you want when checking the build, since the version string can include all of the following: major - the major number minor - the minor number build - the build number revision - the revision number So we can check for a specific build number as follows: if(slPlugin.isVersionSupported("2.0.30523")) { alert("I haz Silverlight 2.0.30523, but could be any revision."); Silverlight 1.0 Beta included a control.settings.version property, which was replaced with the isVersionSupported() method. The idea is that you shouldn't be programming against specific versions of Silverlight. Rather, you should be checking if the client has at least verion 1.0, or 2.0, etc. That being said, you can get the Silverlight version number in Firefox by checking the Silverlight plugin description: alert(navigator.plugins["Silverlight Plug-In"].description); Shows '2.0.30523.8' on my computer. Note that it is possible to brute force it by iterating through all released version numbers. Presumably that's what BrowserHawk does - they'll report which version of Silverlight the client has installed.
Version detection with Silverlight How can I efficiently and effectively detect the version and, for that matter, any available information about the instance of Silverlight currently running on the browser?
TITLE: Version detection with Silverlight QUESTION: How can I efficiently and effectively detect the version and, for that matter, any available information about the instance of Silverlight currently running on the browser? ANSWER: The Silverlight control only has an IsVersionSupported function, which returns true / false when you give it a version number, e.g.: if(slPlugin.isVersionSupported("2.0")) { alert("I haz some flavour of Silverlight 2"); You can be as specific as you want when checking the build, since the version string can include all of the following: major - the major number minor - the minor number build - the build number revision - the revision number So we can check for a specific build number as follows: if(slPlugin.isVersionSupported("2.0.30523")) { alert("I haz Silverlight 2.0.30523, but could be any revision."); Silverlight 1.0 Beta included a control.settings.version property, which was replaced with the isVersionSupported() method. The idea is that you shouldn't be programming against specific versions of Silverlight. Rather, you should be checking if the client has at least verion 1.0, or 2.0, etc. That being said, you can get the Silverlight version number in Firefox by checking the Silverlight plugin description: alert(navigator.plugins["Silverlight Plug-In"].description); Shows '2.0.30523.8' on my computer. Note that it is possible to brute force it by iterating through all released version numbers. Presumably that's what BrowserHawk does - they'll report which version of Silverlight the client has installed.
[ "silverlight", "browser", "ria" ]
11
7
8,889
6
0
2008-08-21T18:30:49.863000
2008-08-25T21:31:54.170000
20,728
20,806
What's the best way to create ClickOnce deployments
Our team develops distributed winform apps. We use ClickOnce for deployment and are very pleased with it. However, we've found the pain point with ClickOnce is in creating the deployments. We have the standard dev/test/production environments and need to be able to create deployments for each of these that install and update separate from one another. Also, we want control over what assemblies get deployed. Just because an assembly was compiled doesn't mean we want it deployed. The obvious first choice for creating deployments is Visual Studio. However, VS really doesn't address the issues stated. The next in line is the SDK tool, Mage. Mage works OK but creating deployments is rather tedious and we don't want every developer having our code signing certificate and password. What we ended up doing was rolling our own deployment app that uses the command line version of Mage to create the ClickOnce manifest files. I'm satisfied with our current solution but is seems like there would be an industry-wide, accepted approach to this problem. Is there?
I would look at using msbuild. It has built in tasks for handling clickonce deployments. I included some references which will help you get started, if you want to go down this path. It is what I use and I have found it to fit my needs. With a good build process using msbuild, you should be able to accomplish squashing the pains you have felt. Here is detailed post on how ClickOnce manifest generation works with MsBuild.
What's the best way to create ClickOnce deployments Our team develops distributed winform apps. We use ClickOnce for deployment and are very pleased with it. However, we've found the pain point with ClickOnce is in creating the deployments. We have the standard dev/test/production environments and need to be able to create deployments for each of these that install and update separate from one another. Also, we want control over what assemblies get deployed. Just because an assembly was compiled doesn't mean we want it deployed. The obvious first choice for creating deployments is Visual Studio. However, VS really doesn't address the issues stated. The next in line is the SDK tool, Mage. Mage works OK but creating deployments is rather tedious and we don't want every developer having our code signing certificate and password. What we ended up doing was rolling our own deployment app that uses the command line version of Mage to create the ClickOnce manifest files. I'm satisfied with our current solution but is seems like there would be an industry-wide, accepted approach to this problem. Is there?
TITLE: What's the best way to create ClickOnce deployments QUESTION: Our team develops distributed winform apps. We use ClickOnce for deployment and are very pleased with it. However, we've found the pain point with ClickOnce is in creating the deployments. We have the standard dev/test/production environments and need to be able to create deployments for each of these that install and update separate from one another. Also, we want control over what assemblies get deployed. Just because an assembly was compiled doesn't mean we want it deployed. The obvious first choice for creating deployments is Visual Studio. However, VS really doesn't address the issues stated. The next in line is the SDK tool, Mage. Mage works OK but creating deployments is rather tedious and we don't want every developer having our code signing certificate and password. What we ended up doing was rolling our own deployment app that uses the command line version of Mage to create the ClickOnce manifest files. I'm satisfied with our current solution but is seems like there would be an industry-wide, accepted approach to this problem. Is there? ANSWER: I would look at using msbuild. It has built in tasks for handling clickonce deployments. I included some references which will help you get started, if you want to go down this path. It is what I use and I have found it to fit my needs. With a good build process using msbuild, you should be able to accomplish squashing the pains you have felt. Here is detailed post on how ClickOnce manifest generation works with MsBuild.
[ "winforms", "deployment", "clickonce" ]
14
14
2,828
2
0
2008-08-21T18:35:04.410000
2008-08-21T19:03:27.523000
20,731
20,792
How do you clear a stringstream variable?
I've tried several things already, std::stringstream m; m.empty(); m.clear(); both of which don't work.
For all the standard library types the member function empty() is a query, not a command, i.e. it means "are you empty?" not "please throw away your contents". The clear() member function is inherited from ios and is used to clear the error state of the stream, e.g. if a file stream has the error state set to eofbit (end-of-file), then calling clear() will set the error state back to goodbit (no error). For clearing the contents of a stringstream, using: m.str(""); is correct, although using: m.str(std::string()); is technically more efficient, because you avoid invoking the std::string constructor that takes const char*. But any compiler these days should be able to generate the same code in both cases - so I would just go with whatever is more readable.
How do you clear a stringstream variable? I've tried several things already, std::stringstream m; m.empty(); m.clear(); both of which don't work.
TITLE: How do you clear a stringstream variable? QUESTION: I've tried several things already, std::stringstream m; m.empty(); m.clear(); both of which don't work. ANSWER: For all the standard library types the member function empty() is a query, not a command, i.e. it means "are you empty?" not "please throw away your contents". The clear() member function is inherited from ios and is used to clear the error state of the stream, e.g. if a file stream has the error state set to eofbit (end-of-file), then calling clear() will set the error state back to goodbit (no error). For clearing the contents of a stringstream, using: m.str(""); is correct, although using: m.str(std::string()); is technically more efficient, because you avoid invoking the std::string constructor that takes const char*. But any compiler these days should be able to generate the same code in both cases - so I would just go with whatever is more readable.
[ "c++", "stringstream" ]
593
933
523,064
10
0
2008-08-21T18:35:57.997000
2008-08-21T19:00:25.143000
20,734
20,784
Red-Black Trees
I've seen binary trees and binary searching mentioned in several books I've read lately, but as I'm still at the beginning of my studies in Computer Science, I've yet to take a class that's really dealt with algorithms and data structures in a serious way. I've checked around the typical sources (Wikipedia, Google) and most descriptions of the usefulness and implementation of (in particular) Red-Black trees have come off as dense and difficult to understand. I'm sure for someone with the necessary background, it makes perfect sense, but at the moment it reads like a foreign language almost. So what makes binary trees useful in some of the common tasks you find yourself doing while programming? Beyond that, which trees do you prefer to use (please include a sample implementation) and why?
Red Black trees are good for creating well-balanced trees. The major problem with binary search trees is that you can make them unbalanced very easily. Imagine your first number is a 15. Then all the numbers after that are increasingly smaller than 15. You'll have a tree that is very heavy on the left side and has nothing on the right side. Red Black trees solve that by forcing your tree to be balanced whenever you insert or delete. It accomplishes this through a series of rotations between ancestor nodes and child nodes. The algorithm is actually pretty straightforward, although it is a bit long. I'd suggest picking up the CLRS (Cormen, Lieserson, Rivest and Stein) textbook, "Introduction to Algorithms" and reading up on RB Trees. The implementation is also not really so short so it's probably not really best to include it here. Nevertheless, trees are used extensively for high performance apps that need access to lots of data. They provide a very efficient way of finding nodes, with a relatively small overhead of insertion/deletion. Again, I'd suggest looking at CLRS to read up on how they're used. While BSTs may not be used explicitly - one example of the use of trees in general are in almost every single modern RDBMS. Similarly, your file system is almost certainly represented as some sort of tree structure, and files are likewise indexed that way. Trees power Google. Trees power just about every website on the internet.
Red-Black Trees I've seen binary trees and binary searching mentioned in several books I've read lately, but as I'm still at the beginning of my studies in Computer Science, I've yet to take a class that's really dealt with algorithms and data structures in a serious way. I've checked around the typical sources (Wikipedia, Google) and most descriptions of the usefulness and implementation of (in particular) Red-Black trees have come off as dense and difficult to understand. I'm sure for someone with the necessary background, it makes perfect sense, but at the moment it reads like a foreign language almost. So what makes binary trees useful in some of the common tasks you find yourself doing while programming? Beyond that, which trees do you prefer to use (please include a sample implementation) and why?
TITLE: Red-Black Trees QUESTION: I've seen binary trees and binary searching mentioned in several books I've read lately, but as I'm still at the beginning of my studies in Computer Science, I've yet to take a class that's really dealt with algorithms and data structures in a serious way. I've checked around the typical sources (Wikipedia, Google) and most descriptions of the usefulness and implementation of (in particular) Red-Black trees have come off as dense and difficult to understand. I'm sure for someone with the necessary background, it makes perfect sense, but at the moment it reads like a foreign language almost. So what makes binary trees useful in some of the common tasks you find yourself doing while programming? Beyond that, which trees do you prefer to use (please include a sample implementation) and why? ANSWER: Red Black trees are good for creating well-balanced trees. The major problem with binary search trees is that you can make them unbalanced very easily. Imagine your first number is a 15. Then all the numbers after that are increasingly smaller than 15. You'll have a tree that is very heavy on the left side and has nothing on the right side. Red Black trees solve that by forcing your tree to be balanced whenever you insert or delete. It accomplishes this through a series of rotations between ancestor nodes and child nodes. The algorithm is actually pretty straightforward, although it is a bit long. I'd suggest picking up the CLRS (Cormen, Lieserson, Rivest and Stein) textbook, "Introduction to Algorithms" and reading up on RB Trees. The implementation is also not really so short so it's probably not really best to include it here. Nevertheless, trees are used extensively for high performance apps that need access to lots of data. They provide a very efficient way of finding nodes, with a relatively small overhead of insertion/deletion. Again, I'd suggest looking at CLRS to read up on how they're used. While BSTs may not be used explicitly - one example of the use of trees in general are in almost every single modern RDBMS. Similarly, your file system is almost certainly represented as some sort of tree structure, and files are likewise indexed that way. Trees power Google. Trees power just about every website on the internet.
[ "algorithm", "binary-tree", "red-black-tree" ]
57
57
16,000
12
0
2008-08-21T18:37:15.620000
2008-08-21T18:56:16.917000
20,744
886,149
SQL Reporting Services viewer for webpage - can you move the View Report button?
Using the viewer control for display of SQL Reporting Services reports on web page (Microsoft.ReportViewer.WebForms), can you move the View Report button? It defaults to the very right side of the report, which means you have to scroll all the way across before the button is visible. Not a problem for reports that fit the window width, but on very wide reports that is quickly an issue.
It's kind of a hack, but you can move it in JavaScript. Just see what HTML the ReportViewer generates, and write the appropriate JavaScript code to move the button. I used JavaScript to hide the button (because we wanted our own View Report button). Any JavaScript code that manipulates the generated ReportViewer's HTML must come after the ReportViewer control in the.aspx page. Here's my code for hiding the button, to give you an idea of what you'd do: function getRepViewBtn() { return document.getElementsByName("ReportViewer1$ctl00$ctl00")[0]; } function hideViewReportButton() { // call this where needed var btn = getRepViewBtn(); btn.style.display = 'none'; }
SQL Reporting Services viewer for webpage - can you move the View Report button? Using the viewer control for display of SQL Reporting Services reports on web page (Microsoft.ReportViewer.WebForms), can you move the View Report button? It defaults to the very right side of the report, which means you have to scroll all the way across before the button is visible. Not a problem for reports that fit the window width, but on very wide reports that is quickly an issue.
TITLE: SQL Reporting Services viewer for webpage - can you move the View Report button? QUESTION: Using the viewer control for display of SQL Reporting Services reports on web page (Microsoft.ReportViewer.WebForms), can you move the View Report button? It defaults to the very right side of the report, which means you have to scroll all the way across before the button is visible. Not a problem for reports that fit the window width, but on very wide reports that is quickly an issue. ANSWER: It's kind of a hack, but you can move it in JavaScript. Just see what HTML the ReportViewer generates, and write the appropriate JavaScript code to move the button. I used JavaScript to hide the button (because we wanted our own View Report button). Any JavaScript code that manipulates the generated ReportViewer's HTML must come after the ReportViewer control in the.aspx page. Here's my code for hiding the button, to give you an idea of what you'd do: function getRepViewBtn() { return document.getElementsByName("ReportViewer1$ctl00$ctl00")[0]; } function hideViewReportButton() { // call this where needed var btn = getRepViewBtn(); btn.style.display = 'none'; }
[ "asp.net", "reporting-services", "reportviewer" ]
6
2
12,025
5
0
2008-08-21T18:42:14.377000
2009-05-20T04:37:34.663000
20,762
20,777
How do you remove invalid hexadecimal characters from an XML-based data source prior to constructing an XmlReader or XPathDocument that uses the data?
Is there any easy/general way to clean an XML based data source prior to using it in an XmlReader so that I can gracefully consume XML data that is non-conformant to the hexadecimal character restrictions placed on XML? Note: The solution needs to handle XML data sources that use character encodings other than UTF-8, e.g. by specifying the character encoding at the XML document declaration. Not mangling the character encoding of the source while stripping invalid hexadecimal characters has been a major sticking point. The removal of invalid hexadecimal characters should only remove hexadecimal encoded values, as you can often find href values in data that happens to contains a string that would be a string match for a hexadecimal character. Background: I need to consume an XML-based data source that conforms to a specific format (think Atom or RSS feeds), but want to be able to consume data sources that have been published which contain invalid hexadecimal characters per the XML specification. In.NET if you have a Stream that represents the XML data source, and then attempt to parse it using an XmlReader and/or XPathDocument, an exception is raised due to the inclusion of invalid hexadecimal characters in the XML data. My current attempt to resolve this issue is to parse the Stream as a string and use a regular expression to remove and/or replace the invalid hexadecimal characters, but I am looking for a more performant solution.
It may not be perfect (emphasis added since people missing this disclaimer), but what I've done in that case is below. You can adjust to use with a stream. /// /// Removes control characters and other non-UTF-8 characters /// /// The string to process /// A string with no control characters or entities above 0x00FD public static string RemoveTroublesomeCharacters(string inString) { if (inString == null) return null; StringBuilder newString = new StringBuilder(); char ch; for (int i = 0; i < inString.Length; i++) { ch = inString[i]; // remove any characters outside the valid UTF-8 range as well as all control characters // except tabs and new lines //if ((ch < 0x00FD && ch > 0x001F) || ch == '\t' || ch == '\n' || ch == '\r') //if using.NET version prior to 4, use above logic if (XmlConvert.IsXmlChar(ch)) //this method is new in.NET 4 { newString.Append(ch); } } return newString.ToString(); }
How do you remove invalid hexadecimal characters from an XML-based data source prior to constructing an XmlReader or XPathDocument that uses the data? Is there any easy/general way to clean an XML based data source prior to using it in an XmlReader so that I can gracefully consume XML data that is non-conformant to the hexadecimal character restrictions placed on XML? Note: The solution needs to handle XML data sources that use character encodings other than UTF-8, e.g. by specifying the character encoding at the XML document declaration. Not mangling the character encoding of the source while stripping invalid hexadecimal characters has been a major sticking point. The removal of invalid hexadecimal characters should only remove hexadecimal encoded values, as you can often find href values in data that happens to contains a string that would be a string match for a hexadecimal character. Background: I need to consume an XML-based data source that conforms to a specific format (think Atom or RSS feeds), but want to be able to consume data sources that have been published which contain invalid hexadecimal characters per the XML specification. In.NET if you have a Stream that represents the XML data source, and then attempt to parse it using an XmlReader and/or XPathDocument, an exception is raised due to the inclusion of invalid hexadecimal characters in the XML data. My current attempt to resolve this issue is to parse the Stream as a string and use a regular expression to remove and/or replace the invalid hexadecimal characters, but I am looking for a more performant solution.
TITLE: How do you remove invalid hexadecimal characters from an XML-based data source prior to constructing an XmlReader or XPathDocument that uses the data? QUESTION: Is there any easy/general way to clean an XML based data source prior to using it in an XmlReader so that I can gracefully consume XML data that is non-conformant to the hexadecimal character restrictions placed on XML? Note: The solution needs to handle XML data sources that use character encodings other than UTF-8, e.g. by specifying the character encoding at the XML document declaration. Not mangling the character encoding of the source while stripping invalid hexadecimal characters has been a major sticking point. The removal of invalid hexadecimal characters should only remove hexadecimal encoded values, as you can often find href values in data that happens to contains a string that would be a string match for a hexadecimal character. Background: I need to consume an XML-based data source that conforms to a specific format (think Atom or RSS feeds), but want to be able to consume data sources that have been published which contain invalid hexadecimal characters per the XML specification. In.NET if you have a Stream that represents the XML data source, and then attempt to parse it using an XmlReader and/or XPathDocument, an exception is raised due to the inclusion of invalid hexadecimal characters in the XML data. My current attempt to resolve this issue is to parse the Stream as a string and use a regular expression to remove and/or replace the invalid hexadecimal characters, but I am looking for a more performant solution. ANSWER: It may not be perfect (emphasis added since people missing this disclaimer), but what I've done in that case is below. You can adjust to use with a stream. /// /// Removes control characters and other non-UTF-8 characters /// /// The string to process /// A string with no control characters or entities above 0x00FD public static string RemoveTroublesomeCharacters(string inString) { if (inString == null) return null; StringBuilder newString = new StringBuilder(); char ch; for (int i = 0; i < inString.Length; i++) { ch = inString[i]; // remove any characters outside the valid UTF-8 range as well as all control characters // except tabs and new lines //if ((ch < 0x00FD && ch > 0x001F) || ch == '\t' || ch == '\n' || ch == '\r') //if using.NET version prior to 4, use above logic if (XmlConvert.IsXmlChar(ch)) //this method is new in.NET 4 { newString.Append(ch); } } return newString.ToString(); }
[ "c#", "xml", "validation", "encoding" ]
75
78
106,226
14
0
2008-08-21T18:47:49.263000
2008-08-21T18:50:58.553000
20,765
20,793
XRef Relationships in dbml
So I have a database schema like this: Users UserId RoleUserXRef RoleUserId RoleId UserId Roles RoleId Name With foreign keys defined between User & RoleUserXRef and RoleUserXRef & Role. Basically, I have a one to many relationship between users and roles. How would I model this in dbml, such that the generated User class has a list of Roles that the user has assigned to them?
Creating a many-to-many releationship via simple DBML manipulation is not supported currently. You can extend the partial class to manually create properties, if you really want that sort of functionality "built in".
XRef Relationships in dbml So I have a database schema like this: Users UserId RoleUserXRef RoleUserId RoleId UserId Roles RoleId Name With foreign keys defined between User & RoleUserXRef and RoleUserXRef & Role. Basically, I have a one to many relationship between users and roles. How would I model this in dbml, such that the generated User class has a list of Roles that the user has assigned to them?
TITLE: XRef Relationships in dbml QUESTION: So I have a database schema like this: Users UserId RoleUserXRef RoleUserId RoleId UserId Roles RoleId Name With foreign keys defined between User & RoleUserXRef and RoleUserXRef & Role. Basically, I have a one to many relationship between users and roles. How would I model this in dbml, such that the generated User class has a list of Roles that the user has assigned to them? ANSWER: Creating a many-to-many releationship via simple DBML manipulation is not supported currently. You can extend the partial class to manually create properties, if you really want that sort of functionality "built in".
[ "oop", "linq-to-sql", "many-to-many" ]
1
1
422
1
0
2008-08-21T18:49:01.990000
2008-08-21T19:00:29.777000
20,778
20,779
How do you convert binary data to Strings and back in Java?
I have binary data in a file that I can read into a byte array and process with no problem. Now I need to send parts of the data over a network connection as elements in an XML document. My problem is that when I convert the data from an array of bytes to a String and back to an array of bytes, the data is getting corrupted. I've tested this on one machine to isolate the problem to the String conversion, so I now know that it isn't getting corrupted by the XML parser or the network transport. What I've got right now is byte[] buffer =...; // read from file // a few lines that prove I can process the data successfully String element = new String(buffer); byte[] newBuffer = element.getBytes(); // a few lines that try to process newBuffer and fail because it is not the same data anymore Does anyone know how to convert binary to String and back without data loss? Answered: Thanks Sam. I feel like an idiot. I had this answered yesterday because my SAX parser was complaining. For some reason when I ran into this seemingly separate issue, it didn't occur to me that it was a new symptom of the same problem. EDIT: Just for the sake of completeness, I used the Base64 class from the Apache Commons Codec package to solve this problem.
If you encode it in base64, this will turn any data into ascii safe text, but base64 encoded data is larger than the orignal data
How do you convert binary data to Strings and back in Java? I have binary data in a file that I can read into a byte array and process with no problem. Now I need to send parts of the data over a network connection as elements in an XML document. My problem is that when I convert the data from an array of bytes to a String and back to an array of bytes, the data is getting corrupted. I've tested this on one machine to isolate the problem to the String conversion, so I now know that it isn't getting corrupted by the XML parser or the network transport. What I've got right now is byte[] buffer =...; // read from file // a few lines that prove I can process the data successfully String element = new String(buffer); byte[] newBuffer = element.getBytes(); // a few lines that try to process newBuffer and fail because it is not the same data anymore Does anyone know how to convert binary to String and back without data loss? Answered: Thanks Sam. I feel like an idiot. I had this answered yesterday because my SAX parser was complaining. For some reason when I ran into this seemingly separate issue, it didn't occur to me that it was a new symptom of the same problem. EDIT: Just for the sake of completeness, I used the Base64 class from the Apache Commons Codec package to solve this problem.
TITLE: How do you convert binary data to Strings and back in Java? QUESTION: I have binary data in a file that I can read into a byte array and process with no problem. Now I need to send parts of the data over a network connection as elements in an XML document. My problem is that when I convert the data from an array of bytes to a String and back to an array of bytes, the data is getting corrupted. I've tested this on one machine to isolate the problem to the String conversion, so I now know that it isn't getting corrupted by the XML parser or the network transport. What I've got right now is byte[] buffer =...; // read from file // a few lines that prove I can process the data successfully String element = new String(buffer); byte[] newBuffer = element.getBytes(); // a few lines that try to process newBuffer and fail because it is not the same data anymore Does anyone know how to convert binary to String and back without data loss? Answered: Thanks Sam. I feel like an idiot. I had this answered yesterday because my SAX parser was complaining. For some reason when I ran into this seemingly separate issue, it didn't occur to me that it was a new symptom of the same problem. EDIT: Just for the sake of completeness, I used the Base64 class from the Apache Commons Codec package to solve this problem. ANSWER: If you encode it in base64, this will turn any data into ascii safe text, but base64 encoded data is larger than the orignal data
[ "java", "serialization" ]
29
21
105,948
4
0
2008-08-21T18:51:52.933000
2008-08-21T18:54:06.487000
20,782
23,056
Call Project Server Interface web method from an msi installer
I'm using a Visual Studio web setup project to install an application that extends the functionality of Project Server. I want to call a method from the PSI ( Project Server Interface ) from one of the custom actions of my setup project, but every time a get a "401 Unauthorized access" error. What should I do to be able to access the PSI? The same code, when used from a Console Application, works without any issues.
It sounds like in the console situation you are running with your current user credentials, which have access to the PSI. When running from the web, it's running with the creds of the IIS application instance. I think you'd either need to set up delegation to pass the session creds to the IIS application, or use some static creds for your IIS app that have access to the PSI.
Call Project Server Interface web method from an msi installer I'm using a Visual Studio web setup project to install an application that extends the functionality of Project Server. I want to call a method from the PSI ( Project Server Interface ) from one of the custom actions of my setup project, but every time a get a "401 Unauthorized access" error. What should I do to be able to access the PSI? The same code, when used from a Console Application, works without any issues.
TITLE: Call Project Server Interface web method from an msi installer QUESTION: I'm using a Visual Studio web setup project to install an application that extends the functionality of Project Server. I want to call a method from the PSI ( Project Server Interface ) from one of the custom actions of my setup project, but every time a get a "401 Unauthorized access" error. What should I do to be able to access the PSI? The same code, when used from a Console Application, works without any issues. ANSWER: It sounds like in the console situation you are running with your current user credentials, which have access to the PSI. When running from the web, it's running with the creds of the IIS application instance. I think you'd either need to set up delegation to pass the session creds to the IIS application, or use some static creds for your IIS app that have access to the PSI.
[ "windows-installer", "methods", "action" ]
2
3
532
2
0
2008-08-21T18:55:15.907000
2008-08-22T18:04:40.247000
20,787
20,813
When to use STL bitsets instead of separate variables?
In what situation would it be more appropriate for me to use a bitset (STL container) to manage a set of flags rather than having them declared as a number of separate (bool) variables? Will I get a significant performance gain if I used a bitset for 50 flags rather than using 50 separate bool variables?
Well, 50 bools as a bitset will take 7 bytes, while 50 bools as bools will take 50 bytes. These days that's not really a big deal, so using bools is probably fine. However, one place a bitset might be useful is if you need to pass those bools around a lot, especially if you need to return the set from a function. Using a bitset you have less data that has to be moved around on the stack for returns. Then again, you could just use refs instead and have even less data to pass around.:)
When to use STL bitsets instead of separate variables? In what situation would it be more appropriate for me to use a bitset (STL container) to manage a set of flags rather than having them declared as a number of separate (bool) variables? Will I get a significant performance gain if I used a bitset for 50 flags rather than using 50 separate bool variables?
TITLE: When to use STL bitsets instead of separate variables? QUESTION: In what situation would it be more appropriate for me to use a bitset (STL container) to manage a set of flags rather than having them declared as a number of separate (bool) variables? Will I get a significant performance gain if I used a bitset for 50 flags rather than using 50 separate bool variables? ANSWER: Well, 50 bools as a bitset will take 7 bytes, while 50 bools as bools will take 50 bytes. These days that's not really a big deal, so using bools is probably fine. However, one place a bitset might be useful is if you need to pass those bools around a lot, especially if you need to return the set from a function. Using a bitset you have less data that has to be moved around on the stack for returns. Then again, you could just use refs instead and have even less data to pass around.:)
[ "c++", "performance", "bitsets" ]
16
10
10,206
4
0
2008-08-21T18:57:59.830000
2008-08-21T19:05:30.763000
20,791
22,173
How do I set up a test cert for an SSL connection in .NET?
I would like to create an SSL connection for generic TCP communication. I think I figured out how to do it in the code, using the info here: http://msdn.microsoft.com/en-us/library/system.net.security.sslstream.aspx What I'm having trouble with is creating a cert so I can test this out. I tried makecert.exe testCert, and that created a cert, but apparently it doesn't have a private key associated with it. So what I'm looking for is the simplest procedure to create a cert and get the connection to work.
I haven't found a simple way to do this yet, but I found this site helpful a few months back. O'Reilly also published a book called Network Security Hacks (available on Safari) that has a section starting at Hack #45 on creating your own certificate authority.
How do I set up a test cert for an SSL connection in .NET? I would like to create an SSL connection for generic TCP communication. I think I figured out how to do it in the code, using the info here: http://msdn.microsoft.com/en-us/library/system.net.security.sslstream.aspx What I'm having trouble with is creating a cert so I can test this out. I tried makecert.exe testCert, and that created a cert, but apparently it doesn't have a private key associated with it. So what I'm looking for is the simplest procedure to create a cert and get the connection to work.
TITLE: How do I set up a test cert for an SSL connection in .NET? QUESTION: I would like to create an SSL connection for generic TCP communication. I think I figured out how to do it in the code, using the info here: http://msdn.microsoft.com/en-us/library/system.net.security.sslstream.aspx What I'm having trouble with is creating a cert so I can test this out. I tried makecert.exe testCert, and that created a cert, but apparently it doesn't have a private key associated with it. So what I'm looking for is the simplest procedure to create a cert and get the connection to work. ANSWER: I haven't found a simple way to do this yet, but I found this site helpful a few months back. O'Reilly also published a book called Network Security Hacks (available on Safari) that has a section starting at Hack #45 on creating your own certificate authority.
[ ".net" ]
5
2
378
3
0
2008-08-21T19:00:04.287000
2008-08-22T12:11:27.273000
20,794
26,957
Find broken symlinks with Python
If I call os.stat() on a broken symlink, python throws an OSError exception. This makes it useful for finding them. However, there are a few other reasons that os.stat() might throw a similar exception. Is there a more precise way of detecting broken symlinks with Python under Linux?
A common Python saying is that it's easier to ask forgiveness than permission. While I'm not a fan of this statement in real life, it does apply in a lot of cases. Usually you want to avoid code that chains two system calls on the same file, because you never know what will happen to the file in between your two calls in your code. A typical mistake is to write something like: if os.path.exists(path): os.unlink(path) The second call (os.unlink) may fail if something else deleted it after your if test, raise an Exception, and stop the rest of your function from executing. (You might think this doesn't happen in real life, but we just fished another bug like that out of our codebase last week - and it was the kind of bug that left a few programmers scratching their head and claiming 'Heisenbug' for the last few months) So, in your particular case, I would probably do: try: os.stat(path) except OSError, e: if e.errno == errno.ENOENT: print 'path %s does not exist or is a broken symlink' % path else: raise e The annoyance here is that stat returns the same error code for a symlink that just isn't there and a broken symlink. So, I guess you have no choice than to break the atomicity, and do something like if not os.path.exists(os.readlink(path)): print 'path %s is a broken symlink' % path
Find broken symlinks with Python If I call os.stat() on a broken symlink, python throws an OSError exception. This makes it useful for finding them. However, there are a few other reasons that os.stat() might throw a similar exception. Is there a more precise way of detecting broken symlinks with Python under Linux?
TITLE: Find broken symlinks with Python QUESTION: If I call os.stat() on a broken symlink, python throws an OSError exception. This makes it useful for finding them. However, there are a few other reasons that os.stat() might throw a similar exception. Is there a more precise way of detecting broken symlinks with Python under Linux? ANSWER: A common Python saying is that it's easier to ask forgiveness than permission. While I'm not a fan of this statement in real life, it does apply in a lot of cases. Usually you want to avoid code that chains two system calls on the same file, because you never know what will happen to the file in between your two calls in your code. A typical mistake is to write something like: if os.path.exists(path): os.unlink(path) The second call (os.unlink) may fail if something else deleted it after your if test, raise an Exception, and stop the rest of your function from executing. (You might think this doesn't happen in real life, but we just fished another bug like that out of our codebase last week - and it was the kind of bug that left a few programmers scratching their head and claiming 'Heisenbug' for the last few months) So, in your particular case, I would probably do: try: os.stat(path) except OSError, e: if e.errno == errno.ENOENT: print 'path %s does not exist or is a broken symlink' % path else: raise e The annoyance here is that stat returns the same error code for a symlink that just isn't there and a broken symlink. So, I guess you have no choice than to break the atomicity, and do something like if not os.path.exists(os.readlink(path)): print 'path %s is a broken symlink' % path
[ "python", "linux", "symlink" ]
34
34
30,709
9
0
2008-08-21T19:00:52.053000
2008-08-25T21:32:20.550000
20,797
20,949
How to split a byte array
I have a byte array in memory, read from a file. I would like to split the byte array at a certain point (index) without having to just create a new byte array and copy each byte at a time, increasing the in memory foot print of the operation. What I would like is something like this: byte[] largeBytes = [1,2,3,4,5,6,7,8,9]; byte[] smallPortion; smallPortion = split(largeBytes, 3); smallPortion would equal 1,2,3,4 largeBytes would equal 5,6,7,8,9
This is how I would do that: using System; using System.Collections; using System.Collections.Generic; class ArrayView: IEnumerable { private readonly T[] array; private readonly int offset, count; public ArrayView(T[] array, int offset, int count) { this.array = array; this.offset = offset; this.count = count; } public int Length { get { return count; } } public T this[int index] { get { if (index < 0 || index >= this.count) throw new IndexOutOfRangeException(); else return this.array[offset + index]; } set { if (index < 0 || index >= this.count) throw new IndexOutOfRangeException(); else this.array[offset + index] = value; } } public IEnumerator GetEnumerator() { for (int i = offset; i < offset + count; i++) yield return array[i]; } IEnumerator IEnumerable.GetEnumerator() { IEnumerator enumerator = this.GetEnumerator(); while (enumerator.MoveNext()) { yield return enumerator.Current; } } } class Program { static void Main(string[] args) { byte[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; ArrayView p1 = new ArrayView (arr, 0, 5); ArrayView p2 = new ArrayView (arr, 5, 5); Console.WriteLine("First array:"); foreach (byte b in p1) { Console.Write(b); } Console.Write("\n"); Console.WriteLine("Second array:"); foreach (byte b in p2) { Console.Write(b); } Console.ReadKey(); } }
How to split a byte array I have a byte array in memory, read from a file. I would like to split the byte array at a certain point (index) without having to just create a new byte array and copy each byte at a time, increasing the in memory foot print of the operation. What I would like is something like this: byte[] largeBytes = [1,2,3,4,5,6,7,8,9]; byte[] smallPortion; smallPortion = split(largeBytes, 3); smallPortion would equal 1,2,3,4 largeBytes would equal 5,6,7,8,9
TITLE: How to split a byte array QUESTION: I have a byte array in memory, read from a file. I would like to split the byte array at a certain point (index) without having to just create a new byte array and copy each byte at a time, increasing the in memory foot print of the operation. What I would like is something like this: byte[] largeBytes = [1,2,3,4,5,6,7,8,9]; byte[] smallPortion; smallPortion = split(largeBytes, 3); smallPortion would equal 1,2,3,4 largeBytes would equal 5,6,7,8,9 ANSWER: This is how I would do that: using System; using System.Collections; using System.Collections.Generic; class ArrayView: IEnumerable { private readonly T[] array; private readonly int offset, count; public ArrayView(T[] array, int offset, int count) { this.array = array; this.offset = offset; this.count = count; } public int Length { get { return count; } } public T this[int index] { get { if (index < 0 || index >= this.count) throw new IndexOutOfRangeException(); else return this.array[offset + index]; } set { if (index < 0 || index >= this.count) throw new IndexOutOfRangeException(); else this.array[offset + index] = value; } } public IEnumerator GetEnumerator() { for (int i = offset; i < offset + count; i++) yield return array[i]; } IEnumerator IEnumerable.GetEnumerator() { IEnumerator enumerator = this.GetEnumerator(); while (enumerator.MoveNext()) { yield return enumerator.Current; } } } class Program { static void Main(string[] args) { byte[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; ArrayView p1 = new ArrayView (arr, 0, 5); ArrayView p2 = new ArrayView (arr, 5, 5); Console.WriteLine("First array:"); foreach (byte b in p1) { Console.Write(b); } Console.Write("\n"); Console.WriteLine("Second array:"); foreach (byte b in p2) { Console.Write(b); } Console.ReadKey(); } }
[ "c#", "arrays", "split" ]
38
15
77,920
8
0
2008-08-21T19:01:28.043000
2008-08-21T19:47:39.070000
20,811
36,983
Automate Syncing Oracle Tables With MySQL Tables
The university I work at uses Oracle for the database system. We currently have programs we run at night to download what we need into some local Access tables for our testing needs. Access is getting to small for this now and we need something bigger. Also, the nightly jobs require constant maintance to keep working (because of network issues, table changes, bad code:) ) and I would like to eliminate them to free us up for more important things. I am most familiar with MySQL so I setup a test MySQL server. What is the best way to automate copying the needed tables from Oracle to MySQL? Edit: I accepted the answer. I don't like the answer but it seems to be correct based on further research and the lack of other answers provided. Thanks to all for pondering my question and answering it.
I don't think there is really anything that is going to do this. If you could setup a local Oracle database, then most likely you could as oracle has various means of keeping two databases "in sync", provided they are both Oracle. If you must use mysql, then likely you are going to just have to write something to sync the data, this is of course always going to run in the same problems you currently have with the access "database". You could setup something with HSODBC and triggers, but I've found HSODBC to be very memory hungry This is only going to add more load to your DB, which you say is already heavily loaded during the day. If the main thing you are doing is wanting a local Test copy of your oracle database, you would be best to setup syncing with a local version of oracle, as far as I can tell from the licenses, oracle is free for development copies ( I have seen some posts to the contrary, but if you find that is the case, you could always use something like Oracle XE)
Automate Syncing Oracle Tables With MySQL Tables The university I work at uses Oracle for the database system. We currently have programs we run at night to download what we need into some local Access tables for our testing needs. Access is getting to small for this now and we need something bigger. Also, the nightly jobs require constant maintance to keep working (because of network issues, table changes, bad code:) ) and I would like to eliminate them to free us up for more important things. I am most familiar with MySQL so I setup a test MySQL server. What is the best way to automate copying the needed tables from Oracle to MySQL? Edit: I accepted the answer. I don't like the answer but it seems to be correct based on further research and the lack of other answers provided. Thanks to all for pondering my question and answering it.
TITLE: Automate Syncing Oracle Tables With MySQL Tables QUESTION: The university I work at uses Oracle for the database system. We currently have programs we run at night to download what we need into some local Access tables for our testing needs. Access is getting to small for this now and we need something bigger. Also, the nightly jobs require constant maintance to keep working (because of network issues, table changes, bad code:) ) and I would like to eliminate them to free us up for more important things. I am most familiar with MySQL so I setup a test MySQL server. What is the best way to automate copying the needed tables from Oracle to MySQL? Edit: I accepted the answer. I don't like the answer but it seems to be correct based on further research and the lack of other answers provided. Thanks to all for pondering my question and answering it. ANSWER: I don't think there is really anything that is going to do this. If you could setup a local Oracle database, then most likely you could as oracle has various means of keeping two databases "in sync", provided they are both Oracle. If you must use mysql, then likely you are going to just have to write something to sync the data, this is of course always going to run in the same problems you currently have with the access "database". You could setup something with HSODBC and triggers, but I've found HSODBC to be very memory hungry This is only going to add more load to your DB, which you say is already heavily loaded during the day. If the main thing you are doing is wanting a local Test copy of your oracle database, you would be best to setup syncing with a local version of oracle, as far as I can tell from the licenses, oracle is free for development copies ( I have seen some posts to the contrary, but if you find that is the case, you could always use something like Oracle XE)
[ "mysql", "database", "oracle" ]
0
1
7,037
4
0
2008-08-21T19:05:20.890000
2008-08-31T17:24:19.227000
20,821
97,553
SQL 2005 Reporting Services custom report item (CRI) - what are the limits?
Reading MSDN (and other sources) about custom report items (CRI) for reporting services 2005. It looks like I'm limited to generating a bitmap. Not even with some mapping overlay for detecting mouse clicks on it. Is there away to go around this? There are two things I would like to do: Embed HTML directly into the report, to format dynamic text. Embed flash (swf) control in the report. This could be done with HTML if the previous point is possible. But maybe there is another way Any suggestions? What am I missing?
You didn't missing anything. For me, like you mentioned, the main disadvantage is, that with a CRI you can only render images. You don't get any scalable text or something similar. If you want include swf, you need to render it as static image.
SQL 2005 Reporting Services custom report item (CRI) - what are the limits? Reading MSDN (and other sources) about custom report items (CRI) for reporting services 2005. It looks like I'm limited to generating a bitmap. Not even with some mapping overlay for detecting mouse clicks on it. Is there away to go around this? There are two things I would like to do: Embed HTML directly into the report, to format dynamic text. Embed flash (swf) control in the report. This could be done with HTML if the previous point is possible. But maybe there is another way Any suggestions? What am I missing?
TITLE: SQL 2005 Reporting Services custom report item (CRI) - what are the limits? QUESTION: Reading MSDN (and other sources) about custom report items (CRI) for reporting services 2005. It looks like I'm limited to generating a bitmap. Not even with some mapping overlay for detecting mouse clicks on it. Is there away to go around this? There are two things I would like to do: Embed HTML directly into the report, to format dynamic text. Embed flash (swf) control in the report. This could be done with HTML if the previous point is possible. But maybe there is another way Any suggestions? What am I missing? ANSWER: You didn't missing anything. For me, like you mentioned, the main disadvantage is, that with a CRI you can only render images. You don't get any scalable text or something similar. If you want include swf, you need to render it as static image.
[ "reporting-services", "reportingservices-2005" ]
4
1
2,724
3
0
2008-08-21T19:08:01.430000
2008-09-18T22:14:09.813000
20,840
20,890
SQL Server - Dirty Reads Pros & Cons
Why should I or shouldn't I use dirty reads: set transaction isolation level read uncommitted in SQL Server?
From MSDN: When this option is set, it is possible to read uncommitted or dirty data; values in the data can be changed and rows can appear or disappear in the data set before the end of the transaction. Simply put, when you are using this isolation level, and you are performing multiple queries on an active table as part of one transaction, there is no guarantee that the information returned to you within different parts of the transaction will remain the same. You could query the same data twice within one transaction and get different results (this might happen in the case where a different user was updating the same data in the midst of your transaction). This can obviously have severe ramifications for parts of your application that rely on data integrity.
SQL Server - Dirty Reads Pros & Cons Why should I or shouldn't I use dirty reads: set transaction isolation level read uncommitted in SQL Server?
TITLE: SQL Server - Dirty Reads Pros & Cons QUESTION: Why should I or shouldn't I use dirty reads: set transaction isolation level read uncommitted in SQL Server? ANSWER: From MSDN: When this option is set, it is possible to read uncommitted or dirty data; values in the data can be changed and rows can appear or disappear in the data set before the end of the transaction. Simply put, when you are using this isolation level, and you are performing multiple queries on an active table as part of one transaction, there is no guarantee that the information returned to you within different parts of the transaction will remain the same. You could query the same data twice within one transaction and get different results (this might happen in the case where a different user was updating the same data in the midst of your transaction). This can obviously have severe ramifications for parts of your application that rely on data integrity.
[ "sql", "sql-server" ]
9
15
34,054
4
0
2008-08-21T19:12:59.013000
2008-08-21T19:28:31.847000
20,850
36,907
How to stop NTFS volume auto-mounting on OS X?
I'm a bit newbieish when it comes to the deeper parts of OSX configuration and am having to put up with a fairly irritating niggle which while I can put up with it, I know under Windows I could have sorted in minutes. Basically, I have an external disk with two volumes: One is an HFS+ volume which I use for TimeMachine backups. The other, an NTFS volume that I use for general file copying etc on Mac and Windows boxes. So what happens is that whenever I plug in the disk into my Mac USB, OSX goes off and mounts both volumes and shows an icon on the desktop for each. The thing is that to remove the disk you have to eject the volume and in this case do it for both volumes, which causes an annoying warning dialog to be shown every time. What I'd prefer is some way to prevent the NTFS volume from auto-mounting altogether. I've done some hefty googling and here's a list of things I've tried so far: I've tried going through options in Disk Utility I've tried setting AutoMount to No in /etc/hostconfig but that is a bit too global for my liking. I've also tried the suggested approach to putting settings in fstab but it appears the OSX (10.5) is ignoring these settings. Any other suggestions would be welcomed. Just a little dissapointed that I can't just tick a box somewhere (or untick). EDIT: Thanks heaps to hop for the answer it worked a treat. For the record it turns out that it wasn't OSX not picking up the settings I actually had "msdos" instead of "ntfs" in the fs type column.
The following entry in /etc/fstab will do what you want, even on 10.5 (Leopard): LABEL=VolumeName none ntfs noauto If the file is not already there, just create it. Do not use /etc/fstab.hd! No reloading of diskarbitrationd needed. If this still doesn't work for you, maybe you can find a hint in the syslog.
How to stop NTFS volume auto-mounting on OS X? I'm a bit newbieish when it comes to the deeper parts of OSX configuration and am having to put up with a fairly irritating niggle which while I can put up with it, I know under Windows I could have sorted in minutes. Basically, I have an external disk with two volumes: One is an HFS+ volume which I use for TimeMachine backups. The other, an NTFS volume that I use for general file copying etc on Mac and Windows boxes. So what happens is that whenever I plug in the disk into my Mac USB, OSX goes off and mounts both volumes and shows an icon on the desktop for each. The thing is that to remove the disk you have to eject the volume and in this case do it for both volumes, which causes an annoying warning dialog to be shown every time. What I'd prefer is some way to prevent the NTFS volume from auto-mounting altogether. I've done some hefty googling and here's a list of things I've tried so far: I've tried going through options in Disk Utility I've tried setting AutoMount to No in /etc/hostconfig but that is a bit too global for my liking. I've also tried the suggested approach to putting settings in fstab but it appears the OSX (10.5) is ignoring these settings. Any other suggestions would be welcomed. Just a little dissapointed that I can't just tick a box somewhere (or untick). EDIT: Thanks heaps to hop for the answer it worked a treat. For the record it turns out that it wasn't OSX not picking up the settings I actually had "msdos" instead of "ntfs" in the fs type column.
TITLE: How to stop NTFS volume auto-mounting on OS X? QUESTION: I'm a bit newbieish when it comes to the deeper parts of OSX configuration and am having to put up with a fairly irritating niggle which while I can put up with it, I know under Windows I could have sorted in minutes. Basically, I have an external disk with two volumes: One is an HFS+ volume which I use for TimeMachine backups. The other, an NTFS volume that I use for general file copying etc on Mac and Windows boxes. So what happens is that whenever I plug in the disk into my Mac USB, OSX goes off and mounts both volumes and shows an icon on the desktop for each. The thing is that to remove the disk you have to eject the volume and in this case do it for both volumes, which causes an annoying warning dialog to be shown every time. What I'd prefer is some way to prevent the NTFS volume from auto-mounting altogether. I've done some hefty googling and here's a list of things I've tried so far: I've tried going through options in Disk Utility I've tried setting AutoMount to No in /etc/hostconfig but that is a bit too global for my liking. I've also tried the suggested approach to putting settings in fstab but it appears the OSX (10.5) is ignoring these settings. Any other suggestions would be welcomed. Just a little dissapointed that I can't just tick a box somewhere (or untick). EDIT: Thanks heaps to hop for the answer it worked a treat. For the record it turns out that it wasn't OSX not picking up the settings I actually had "msdos" instead of "ntfs" in the fs type column. ANSWER: The following entry in /etc/fstab will do what you want, even on 10.5 (Leopard): LABEL=VolumeName none ntfs noauto If the file is not already there, just create it. Do not use /etc/fstab.hd! No reloading of diskarbitrationd needed. If this still doesn't work for you, maybe you can find a hint in the syslog.
[ "macos", "hardware" ]
2
3
5,604
2
0
2008-08-21T19:16:27.803000
2008-08-31T15:17:14.290000
20,856
20,871
Recommended SQL database design for tags or tagging
I've heard of a few ways to implement tagging; using a mapping table between TagID and ItemID (makes sense to me, but does it scale?), adding a fixed number of possible TagID columns to ItemID (seems like a bad idea), Keeping tags in a text column that's comma separated (sounds crazy but could work). I've even heard someone recommend a sparse matrix, but then how do the tag names grow gracefully? Am I missing a best practice for tags?
Three tables (one for storing all items, one for all tags, and one for the relation between the two), properly indexed, with foreign keys set running on a proper database, should work well and scale properly. Table: Item Columns: ItemID, Title, Content Table: Tag Columns: TagID, Title Table: ItemTag Columns: ItemID, TagID
Recommended SQL database design for tags or tagging I've heard of a few ways to implement tagging; using a mapping table between TagID and ItemID (makes sense to me, but does it scale?), adding a fixed number of possible TagID columns to ItemID (seems like a bad idea), Keeping tags in a text column that's comma separated (sounds crazy but could work). I've even heard someone recommend a sparse matrix, but then how do the tag names grow gracefully? Am I missing a best practice for tags?
TITLE: Recommended SQL database design for tags or tagging QUESTION: I've heard of a few ways to implement tagging; using a mapping table between TagID and ItemID (makes sense to me, but does it scale?), adding a fixed number of possible TagID columns to ItemID (seems like a bad idea), Keeping tags in a text column that's comma separated (sounds crazy but could work). I've even heard someone recommend a sparse matrix, but then how do the tag names grow gracefully? Am I missing a best practice for tags? ANSWER: Three tables (one for storing all items, one for all tags, and one for the relation between the two), properly indexed, with foreign keys set running on a proper database, should work well and scale properly. Table: Item Columns: ItemID, Title, Content Table: Tag Columns: TagID, Title Table: ItemTag Columns: ItemID, TagID
[ "sql", "database-design", "tags", "data-modeling", "tagging" ]
343
476
141,337
6
1
2008-08-21T19:18:05.773000
2008-08-21T19:22:44.013000
20,861
20,982
Automated Web Service Testing
I would like to do some integration testing of a web service from within NUnit or MBUnit. I haven't delved into this too deeply yet, but I am pretty sure I will need to spin up WebDev.WebServer.exe within the "unit test" to do this. (I know it's not really a unit test). Yes, I can test the underlying objects the web service uses on their own (which I am), but what I am interested in testing in this cases is that the proxies are all working and handled as expected, etc. Any advice?
I found this post and this one which have some solutions on how to start up WebDev.WebServer.exe from within a unit test. Looks like I'll need to do something along these lines. Until I get that going, I found that what works is to simply run the web service project within VS, let the WebDev server start up that way, and then run the unit tests. Not ideal, but it's OK for now.
Automated Web Service Testing I would like to do some integration testing of a web service from within NUnit or MBUnit. I haven't delved into this too deeply yet, but I am pretty sure I will need to spin up WebDev.WebServer.exe within the "unit test" to do this. (I know it's not really a unit test). Yes, I can test the underlying objects the web service uses on their own (which I am), but what I am interested in testing in this cases is that the proxies are all working and handled as expected, etc. Any advice?
TITLE: Automated Web Service Testing QUESTION: I would like to do some integration testing of a web service from within NUnit or MBUnit. I haven't delved into this too deeply yet, but I am pretty sure I will need to spin up WebDev.WebServer.exe within the "unit test" to do this. (I know it's not really a unit test). Yes, I can test the underlying objects the web service uses on their own (which I am), but what I am interested in testing in this cases is that the proxies are all working and handled as expected, etc. Any advice? ANSWER: I found this post and this one which have some solutions on how to start up WebDev.WebServer.exe from within a unit test. Looks like I'll need to do something along these lines. Until I get that going, I found that what works is to simply run the web service project within VS, let the WebDev server start up that way, and then run the unit tests. Not ideal, but it's OK for now.
[ "web-services", "unit-testing", "integration-testing" ]
5
1
6,620
6
0
2008-08-21T19:19:47.173000
2008-08-21T19:57:33.963000
20,876
20,895
Best way to perform dynamic subquery in MS Reporting Services?
I'm new to SQL Server Reporting Services, and was wondering the best way to do the following: Query to get a list of popular IDs Subquery on each item to get properties from another table Ideally, the final report columns would look like this: [ID] [property1] [property2] [SELECT COUNT(*) FROM AnotherTable WHERE ForeignID=ID] There may be ways to construct a giant SQL query to do this all in one go, but I'd prefer to compartmentalize it. Is the recommended approach to write a VB function to perform the subquery for each row? Thanks for any help.
I would recommend using a SubReport. You would place the SubReport in a table cell.
Best way to perform dynamic subquery in MS Reporting Services? I'm new to SQL Server Reporting Services, and was wondering the best way to do the following: Query to get a list of popular IDs Subquery on each item to get properties from another table Ideally, the final report columns would look like this: [ID] [property1] [property2] [SELECT COUNT(*) FROM AnotherTable WHERE ForeignID=ID] There may be ways to construct a giant SQL query to do this all in one go, but I'd prefer to compartmentalize it. Is the recommended approach to write a VB function to perform the subquery for each row? Thanks for any help.
TITLE: Best way to perform dynamic subquery in MS Reporting Services? QUESTION: I'm new to SQL Server Reporting Services, and was wondering the best way to do the following: Query to get a list of popular IDs Subquery on each item to get properties from another table Ideally, the final report columns would look like this: [ID] [property1] [property2] [SELECT COUNT(*) FROM AnotherTable WHERE ForeignID=ID] There may be ways to construct a giant SQL query to do this all in one go, but I'd prefer to compartmentalize it. Is the recommended approach to write a VB function to perform the subquery for each row? Thanks for any help. ANSWER: I would recommend using a SubReport. You would place the SubReport in a table cell.
[ "sql", "sql-server", "reporting-services", "service", "reporting" ]
0
2
10,915
3
0
2008-08-21T19:25:33.680000
2008-08-21T19:28:49.757000
20,880
20,901
Java JPanel redraw issues
I have a Java swing application with a panel that contains three JComboBoxe s that do not draw properly. The combox boxes just show up as the down arrow on the right side, but without the label of the currently selected value. The boxes will redraw correctly if the window is resized either bigger or smaller by even one pixel. All of my googling has pointed to calling revalidate() on the JPanel to fix this, but that hasn't worked for me. Calling updateUI() on the JPanel has changed it from always displaying incorrectly to displaying incorrectly half of the time. Has anyone else seen this and found a different way to force a redraw of the combo boxes?
Can you give us some more information on how you add the combo boxes to the JPanel? This is a pretty common thing to do in Swing so I doubt that it's a JVM issue but I guess anything is possible. Specifically, I would double check to make sure you're not accessing the GUI from any background threads. In this case, maybe you're reading the choices from a DB or something and updating the JComboBox from a background thread, which is a big no-no in Swing. See SwingUtils.invokeLater().
Java JPanel redraw issues I have a Java swing application with a panel that contains three JComboBoxe s that do not draw properly. The combox boxes just show up as the down arrow on the right side, but without the label of the currently selected value. The boxes will redraw correctly if the window is resized either bigger or smaller by even one pixel. All of my googling has pointed to calling revalidate() on the JPanel to fix this, but that hasn't worked for me. Calling updateUI() on the JPanel has changed it from always displaying incorrectly to displaying incorrectly half of the time. Has anyone else seen this and found a different way to force a redraw of the combo boxes?
TITLE: Java JPanel redraw issues QUESTION: I have a Java swing application with a panel that contains three JComboBoxe s that do not draw properly. The combox boxes just show up as the down arrow on the right side, but without the label of the currently selected value. The boxes will redraw correctly if the window is resized either bigger or smaller by even one pixel. All of my googling has pointed to calling revalidate() on the JPanel to fix this, but that hasn't worked for me. Calling updateUI() on the JPanel has changed it from always displaying incorrectly to displaying incorrectly half of the time. Has anyone else seen this and found a different way to force a redraw of the combo boxes? ANSWER: Can you give us some more information on how you add the combo boxes to the JPanel? This is a pretty common thing to do in Swing so I doubt that it's a JVM issue but I guess anything is possible. Specifically, I would double check to make sure you're not accessing the GUI from any background threads. In this case, maybe you're reading the choices from a DB or something and updating the JComboBox from a background thread, which is a big no-no in Swing. See SwingUtils.invokeLater().
[ "java", "swing", "jpanel" ]
8
6
3,448
1
0
2008-08-21T19:26:44.003000
2008-08-21T19:30:02.547000
20,882
20,894
How do I interpret 'netstat -a' output
Some things look strange to me: What is the distinction between 0.0.0.0, 127.0.0.1, and [::]? How should each part of the foreign address be read (part1:part2)? What does a state Time_Wait, Close_Wait mean? etc. Could someone give a quick overview of how to interpret these results?
0.0.0.0 usually refers to stuff listening on all interfaces. 127.0.0.1 = localhost (only your local interface) I'm not sure about [::] TIME_WAIT means both sides have agreed to close and TCP must now wait a prescribed time before taking the connection down. CLOSE_WAIT means the remote system has finished sending and your system has yet to say it's finished.
How do I interpret 'netstat -a' output Some things look strange to me: What is the distinction between 0.0.0.0, 127.0.0.1, and [::]? How should each part of the foreign address be read (part1:part2)? What does a state Time_Wait, Close_Wait mean? etc. Could someone give a quick overview of how to interpret these results?
TITLE: How do I interpret 'netstat -a' output QUESTION: Some things look strange to me: What is the distinction between 0.0.0.0, 127.0.0.1, and [::]? How should each part of the foreign address be read (part1:part2)? What does a state Time_Wait, Close_Wait mean? etc. Could someone give a quick overview of how to interpret these results? ANSWER: 0.0.0.0 usually refers to stuff listening on all interfaces. 127.0.0.1 = localhost (only your local interface) I'm not sure about [::] TIME_WAIT means both sides have agreed to close and TCP must now wait a prescribed time before taking the connection down. CLOSE_WAIT means the remote system has finished sending and your system has yet to say it's finished.
[ "networking", "netstat" ]
30
19
70,023
7
0
2008-08-21T19:26:48.967000
2008-08-21T19:28:47.400000
20,899
25,178
My VMware ESX server console volume went readonly. How can I save my VMs?
Two RAID volumes, VMware kernel/console running on a RAID1, vmdks live on a RAID5. Entering a login at the console just results in SCSI errors, no password prompt. Praise be, the VMs are actually still running. We're thinking, though, that upon reboot the kernel may not start again and the VMs will be down. We have database and disk backups of the VMs, but not backups of the vmdks themselves. What are my options? Our current best idea is Use VMware Converter to create live vmdks from the running VMs, as if it was a P2V migration. Reboot host server and run RAID diagnostics, figure out what in the "h" happened Attempt to start ESX again, possibly after rebuilding its RAID volume Possibly have to re-install ESX on its volume and re-attach VMs If that doesn't work, attach the "live" vmdks created in step 1 to a different VM host.
It was the backplane. Both drives of the RAID1 and one drive of the RAID5 were inaccessible. Incredibly, the VMware hypervisor continued to run for three days from memory with no access to its host disk, keeping the VMs it managed alive. At step 3 above we diagnosed the hardware problem and replaced the RAID controller, cables, and backplane. After restart, we re-initialized the RAID by instructing the controller to query the drives for their configurations. Both were degraded and both were repaired successfully. At step 4, it was not necessary to reinstall ESX; although, at bootup, it did not want to register the VMs. We had to dig up some buried management stuff to instruct the kernel to resignature the VMs. (Search VM docs for "resignature.") I believe that our fallback plan would have worked, the VMware Converter images of the VMs that were running "orphaned" were tested and ran fine with no data loss. I highly recommend performing a VMware Converter imaging of any VM that gets into this state, after shutting down as many services as possible and getting the VM into as read-only a state as possible. Loading a vmdk either elsewhere or on the original host as a repair is usually going to be WAY faster than rebuilding a server from the ground up with backups.
My VMware ESX server console volume went readonly. How can I save my VMs? Two RAID volumes, VMware kernel/console running on a RAID1, vmdks live on a RAID5. Entering a login at the console just results in SCSI errors, no password prompt. Praise be, the VMs are actually still running. We're thinking, though, that upon reboot the kernel may not start again and the VMs will be down. We have database and disk backups of the VMs, but not backups of the vmdks themselves. What are my options? Our current best idea is Use VMware Converter to create live vmdks from the running VMs, as if it was a P2V migration. Reboot host server and run RAID diagnostics, figure out what in the "h" happened Attempt to start ESX again, possibly after rebuilding its RAID volume Possibly have to re-install ESX on its volume and re-attach VMs If that doesn't work, attach the "live" vmdks created in step 1 to a different VM host.
TITLE: My VMware ESX server console volume went readonly. How can I save my VMs? QUESTION: Two RAID volumes, VMware kernel/console running on a RAID1, vmdks live on a RAID5. Entering a login at the console just results in SCSI errors, no password prompt. Praise be, the VMs are actually still running. We're thinking, though, that upon reboot the kernel may not start again and the VMs will be down. We have database and disk backups of the VMs, but not backups of the vmdks themselves. What are my options? Our current best idea is Use VMware Converter to create live vmdks from the running VMs, as if it was a P2V migration. Reboot host server and run RAID diagnostics, figure out what in the "h" happened Attempt to start ESX again, possibly after rebuilding its RAID volume Possibly have to re-install ESX on its volume and re-attach VMs If that doesn't work, attach the "live" vmdks created in step 1 to a different VM host. ANSWER: It was the backplane. Both drives of the RAID1 and one drive of the RAID5 were inaccessible. Incredibly, the VMware hypervisor continued to run for three days from memory with no access to its host disk, keeping the VMs it managed alive. At step 3 above we diagnosed the hardware problem and replaced the RAID controller, cables, and backplane. After restart, we re-initialized the RAID by instructing the controller to query the drives for their configurations. Both were degraded and both were repaired successfully. At step 4, it was not necessary to reinstall ESX; although, at bootup, it did not want to register the VMs. We had to dig up some buried management stuff to instruct the kernel to resignature the VMs. (Search VM docs for "resignature.") I believe that our fallback plan would have worked, the VMware Converter images of the VMs that were running "orphaned" were tested and ran fine with no data loss. I highly recommend performing a VMware Converter imaging of any VM that gets into this state, after shutting down as many services as possible and getting the VM into as read-only a state as possible. Loading a vmdk either elsewhere or on the original host as a repair is usually going to be WAY faster than rebuilding a server from the ground up with backups.
[ "vmware", "recovery", "esx" ]
0
1
1,165
1
0
2008-08-21T19:29:47.600000
2008-08-24T16:49:19.787000
20,910
21,035
Silverlight vs Flex
My company develops several types of applications. A lot of our business comes from doing multimedia-type apps, typically done in Flash. However, now that side of the house is starting to migrate towards doing Flex development. Most of our other development is done using.NET. I'm trying to make a push towards doing Silverlight development instead, since it would take better advantage of the.NET developers on staff. I prefer the Silverlight platform over the Flex platform for the simple fact that Silverlight is all.NET code. We have more.NET developers on staff than Flash/Flex developers, and most of our Flash/Flex developers are graphic artists (not real programmers). Only reason they push towards Flex right now is because it seems like the logical step from Flash. I've done development using both, and I honestly believe Silverlight is easier to work with. But I'm trying to convince people who are only Flash developers. So here's my question: If I'm going to go into a meeting to praise Silverlight, why would a company want to go with Silverlight instead of Flex? Other than the obvious "not everyone has Silverlight", what are the pros and cons for each?
I think you should look at Silverlight as a long-term play, just as Microsoft seems to be doing. There's an obvious balance on when to use Silverlight vs. Flash when you're concerned about reach and install base, but here are some reasons Silverlight is a good direction to move in: Second mover advantage - Just as Microsoft built a "better Java" with.NET, they're able to look at how you'd design a RIA plugin from scratch, today. They have the advantage of knowing how people use the web today, something the inventors of Flash could never have accurately guessed. Flash can add features, but they can't realistically chuck the platform and start over. Developer familiarity - While Silverlight is a new model, it's not entirely unfamiliar to developers. They'll "get" the way Silverlight works a lot more quickly than they'll understand firing up a new development environment with a new scripting language and new event paradigms. Being rid of the timeline model in Flash - Flash was originally built for keyframe based animations, and while there are ways to abstract this away, it's at the core of how Flash works. Silverlight ditches that for an application-centric model. ScottGu - ScottGu is fired up about Silverlight. Nuff said. Cool new features - While Silverlight still has some catching up to do with Flash on some obvious features (like webcam / mic integration, or 3d / graphics acceleration), there are some slick new technologies built in to Silverlight - Deep Zoom is one example. I'm seeing more "revolutionary" technologies on the Silverlight side, while Flash seems to be in maintenance mode at this point.
Silverlight vs Flex My company develops several types of applications. A lot of our business comes from doing multimedia-type apps, typically done in Flash. However, now that side of the house is starting to migrate towards doing Flex development. Most of our other development is done using.NET. I'm trying to make a push towards doing Silverlight development instead, since it would take better advantage of the.NET developers on staff. I prefer the Silverlight platform over the Flex platform for the simple fact that Silverlight is all.NET code. We have more.NET developers on staff than Flash/Flex developers, and most of our Flash/Flex developers are graphic artists (not real programmers). Only reason they push towards Flex right now is because it seems like the logical step from Flash. I've done development using both, and I honestly believe Silverlight is easier to work with. But I'm trying to convince people who are only Flash developers. So here's my question: If I'm going to go into a meeting to praise Silverlight, why would a company want to go with Silverlight instead of Flex? Other than the obvious "not everyone has Silverlight", what are the pros and cons for each?
TITLE: Silverlight vs Flex QUESTION: My company develops several types of applications. A lot of our business comes from doing multimedia-type apps, typically done in Flash. However, now that side of the house is starting to migrate towards doing Flex development. Most of our other development is done using.NET. I'm trying to make a push towards doing Silverlight development instead, since it would take better advantage of the.NET developers on staff. I prefer the Silverlight platform over the Flex platform for the simple fact that Silverlight is all.NET code. We have more.NET developers on staff than Flash/Flex developers, and most of our Flash/Flex developers are graphic artists (not real programmers). Only reason they push towards Flex right now is because it seems like the logical step from Flash. I've done development using both, and I honestly believe Silverlight is easier to work with. But I'm trying to convince people who are only Flash developers. So here's my question: If I'm going to go into a meeting to praise Silverlight, why would a company want to go with Silverlight instead of Flex? Other than the obvious "not everyone has Silverlight", what are the pros and cons for each? ANSWER: I think you should look at Silverlight as a long-term play, just as Microsoft seems to be doing. There's an obvious balance on when to use Silverlight vs. Flash when you're concerned about reach and install base, but here are some reasons Silverlight is a good direction to move in: Second mover advantage - Just as Microsoft built a "better Java" with.NET, they're able to look at how you'd design a RIA plugin from scratch, today. They have the advantage of knowing how people use the web today, something the inventors of Flash could never have accurately guessed. Flash can add features, but they can't realistically chuck the platform and start over. Developer familiarity - While Silverlight is a new model, it's not entirely unfamiliar to developers. They'll "get" the way Silverlight works a lot more quickly than they'll understand firing up a new development environment with a new scripting language and new event paradigms. Being rid of the timeline model in Flash - Flash was originally built for keyframe based animations, and while there are ways to abstract this away, it's at the core of how Flash works. Silverlight ditches that for an application-centric model. ScottGu - ScottGu is fired up about Silverlight. Nuff said. Cool new features - While Silverlight still has some catching up to do with Flash on some obvious features (like webcam / mic integration, or 3d / graphics acceleration), there are some slick new technologies built in to Silverlight - Deep Zoom is one example. I'm seeing more "revolutionary" technologies on the Silverlight side, while Flash seems to be in maintenance mode at this point.
[ ".net", "apache-flex", "flash", "silverlight" ]
70
52
15,491
22
0
2008-08-21T19:34:00.010000
2008-08-21T20:11:17.267000
20,912
20,994
Symantec Backup Exec 11d RALUS Communications Error
I'm trying to do a file system backup of a RedHat Enterprise Linux v4 server using Symantec Backup Exec 11d (Rev 7170). The backup server is Windows Server 2003. I can browse the target server to create a selection list, and when I do a test run it completes successfully. However, when I run a real backup, the job fails immediately during the "processing" phase with the error: e000fe30 - A communications failure has occured. I've tried opening ports (10000, 1025-9999), etc. But no joy. Any ideas?
Sure sounds like firewall issues. Try stopping iptables, and running again. Also, RALUS can dump a log file - which may give some more to go on. I use the older UNIX agent myself, which uses port 6101 IIRC - but I believe that the newer client uses tcp/10000 for control and 1024-65535 for transfer. Last resort is to fire up a network sniffer.;)
Symantec Backup Exec 11d RALUS Communications Error I'm trying to do a file system backup of a RedHat Enterprise Linux v4 server using Symantec Backup Exec 11d (Rev 7170). The backup server is Windows Server 2003. I can browse the target server to create a selection list, and when I do a test run it completes successfully. However, when I run a real backup, the job fails immediately during the "processing" phase with the error: e000fe30 - A communications failure has occured. I've tried opening ports (10000, 1025-9999), etc. But no joy. Any ideas?
TITLE: Symantec Backup Exec 11d RALUS Communications Error QUESTION: I'm trying to do a file system backup of a RedHat Enterprise Linux v4 server using Symantec Backup Exec 11d (Rev 7170). The backup server is Windows Server 2003. I can browse the target server to create a selection list, and when I do a test run it completes successfully. However, when I run a real backup, the job fails immediately during the "processing" phase with the error: e000fe30 - A communications failure has occured. I've tried opening ports (10000, 1025-9999), etc. But no joy. Any ideas? ANSWER: Sure sounds like firewall issues. Try stopping iptables, and running again. Also, RALUS can dump a log file - which may give some more to go on. I use the older UNIX agent myself, which uses port 6101 IIRC - but I believe that the newer client uses tcp/10000 for control and 1024-65535 for transfer. Last resort is to fire up a network sniffer.;)
[ "backup", "redhat", "backupexec", "symantec" ]
0
1
1,719
2
0
2008-08-21T19:34:47.060000
2008-08-21T19:59:57.280000
20,923
21,001
VBScript/IIS - How do I automatically set ASP.NET version for a particular website
I need to script the creation of app pools and websites on IIS 6.0. I have been able to create these using adsutil.vbs and iisweb.vbs, but don't know how to set the version of ASP.NET for the sites I have just created to 2.0.50727.0. Ideally I would like to adsutil.vbs to update the metabase. How do I do this?
@ Chris beat me to the punch on the ADSI way You can do this using the aspnet_regiis.exe tool. There is one of these tools per version of ASP.NET installed on the machine. You could shell out to - This configures ASP.NET 1.1 %windir%\microsoft.net\framework\v1.1.4322\aspnet_regiis -s W3SVC/[iisnumber]/ROOT This configures ASP.NET 2.0 %windir%\microsoft.net\framework\v2.0.50727\aspnet_regiis -s W3SVC/[iisnumber]/ROOT You probably already know this, but if you have multiple 1.1 and 2.0 sites on your machine, just remember to switch the website you're changing ASP.NET versions on to compatible app pool. ASP.NET 1.1 and 2.0 sites don't mix in the same app pool.
VBScript/IIS - How do I automatically set ASP.NET version for a particular website I need to script the creation of app pools and websites on IIS 6.0. I have been able to create these using adsutil.vbs and iisweb.vbs, but don't know how to set the version of ASP.NET for the sites I have just created to 2.0.50727.0. Ideally I would like to adsutil.vbs to update the metabase. How do I do this?
TITLE: VBScript/IIS - How do I automatically set ASP.NET version for a particular website QUESTION: I need to script the creation of app pools and websites on IIS 6.0. I have been able to create these using adsutil.vbs and iisweb.vbs, but don't know how to set the version of ASP.NET for the sites I have just created to 2.0.50727.0. Ideally I would like to adsutil.vbs to update the metabase. How do I do this? ANSWER: @ Chris beat me to the punch on the ADSI way You can do this using the aspnet_regiis.exe tool. There is one of these tools per version of ASP.NET installed on the machine. You could shell out to - This configures ASP.NET 1.1 %windir%\microsoft.net\framework\v1.1.4322\aspnet_regiis -s W3SVC/[iisnumber]/ROOT This configures ASP.NET 2.0 %windir%\microsoft.net\framework\v2.0.50727\aspnet_regiis -s W3SVC/[iisnumber]/ROOT You probably already know this, but if you have multiple 1.1 and 2.0 sites on your machine, just remember to switch the website you're changing ASP.NET versions on to compatible app pool. ASP.NET 1.1 and 2.0 sites don't mix in the same app pool.
[ "asp.net", "iis", "vbscript", "system-administration", "administration" ]
2
6
5,561
2
0
2008-08-21T19:39:44.130000
2008-08-21T20:01:43.327000
20,926
20,944
Nesting HTML- anchor tags
Today I was working on a tab navigation for a webpage. I tried the Sliding Doors approach which worked fine. Then I realized that I must include an option to delete a tab (usually a small X in the right corner of each tab). I wanted to use a nested anchor, which didn't work because it is not allowed. Then I saw the tab- navigation at Pageflakes, which was actually working (including nested hyperlinks). Why?
They must be doing some really crazy stuff with JavaScript to get it to work (notice how neither the parent nor the nested anchor tags have a name or href attribute - all functionality is done through the class name and JS). Here is what the html looks like: Click & Type Page Name X
Nesting HTML- anchor tags Today I was working on a tab navigation for a webpage. I tried the Sliding Doors approach which worked fine. Then I realized that I must include an option to delete a tab (usually a small X in the right corner of each tab). I wanted to use a nested anchor, which didn't work because it is not allowed. Then I saw the tab- navigation at Pageflakes, which was actually working (including nested hyperlinks). Why?
TITLE: Nesting HTML- anchor tags QUESTION: Today I was working on a tab navigation for a webpage. I tried the Sliding Doors approach which worked fine. Then I realized that I must include an option to delete a tab (usually a small X in the right corner of each tab). I wanted to use a nested anchor, which didn't work because it is not allowed. Then I saw the tab- navigation at Pageflakes, which was actually working (including nested hyperlinks). Why? ANSWER: They must be doing some really crazy stuff with JavaScript to get it to work (notice how neither the parent nor the nested anchor tags have a name or href attribute - all functionality is done through the class name and JS). Here is what the html looks like: Click & Type Page Name X
[ "html", "tabs", "anchor" ]
12
9
15,894
5
0
2008-08-21T19:41:07.217000
2008-08-21T19:46:12.197000
20,927
20,983
Updating an auto_now DateTimeField in a parent model in Django
I've got two models: Message and Attachment. Each attachment is attached to a specific message, using a ForeignKey on the Attachment model. Both models have an auto_now DateTimeField called updated. I'm trying to make it so that when any attachment is saved, it also sets the updated field on the associated message to now. Here's my code: def save(self): super(Attachment, self).save() self.message.updated = self.updated Will this work, and if you can explain it to me, why? If not, how would I accomplish this?
You would also need to then save the message. Then it that should work.
Updating an auto_now DateTimeField in a parent model in Django I've got two models: Message and Attachment. Each attachment is attached to a specific message, using a ForeignKey on the Attachment model. Both models have an auto_now DateTimeField called updated. I'm trying to make it so that when any attachment is saved, it also sets the updated field on the associated message to now. Here's my code: def save(self): super(Attachment, self).save() self.message.updated = self.updated Will this work, and if you can explain it to me, why? If not, how would I accomplish this?
TITLE: Updating an auto_now DateTimeField in a parent model in Django QUESTION: I've got two models: Message and Attachment. Each attachment is attached to a specific message, using a ForeignKey on the Attachment model. Both models have an auto_now DateTimeField called updated. I'm trying to make it so that when any attachment is saved, it also sets the updated field on the associated message to now. Here's my code: def save(self): super(Attachment, self).save() self.message.updated = self.updated Will this work, and if you can explain it to me, why? If not, how would I accomplish this? ANSWER: You would also need to then save the message. Then it that should work.
[ "python", "database", "django", "orm" ]
14
12
2,636
3
0
2008-08-21T19:41:57.870000
2008-08-21T19:57:36.410000
20,952
704,817
Is there a way to get a System.Configuration.Configuration instance based on arbitrary xml?
I'm trying to unit test a custom ConfigurationSection I've written, and I'd like to load some arbitrary configuration XML into a System.Configuration.Configuration for each test (rather than put the test configuration xml in the Tests.dll.config file. That is, I'd like to do something like this: Configuration testConfig = new Configuration("... "); MyCustomConfigSection section = testConfig.GetSection("mycustomconfigsection"); Assert.That(section!= null); However, it looks like ConfigurationManager will only give you Configuration instances that are associated with an EXE file or a machine config. Is there a way to load arbitrary XML into a Configuration instance?
There is actually a way I've discovered.... You need to define a new class inheriting from your original configuration section as follows: public class MyXmlCustomConfigSection: MyCustomConfigSection { public MyXmlCustomConfigSection (string configXml) { XmlTextReader reader = new XmlTextReader(new StringReader(configXml)); DeserializeSection(reader); } } You can then instantiate your ConfigurationSection object as follows: string configXml = "... "; MyCustomConfigSection config = new MyXmlCustomConfigSection(configXml); Hope it helps someone:-)
Is there a way to get a System.Configuration.Configuration instance based on arbitrary xml? I'm trying to unit test a custom ConfigurationSection I've written, and I'd like to load some arbitrary configuration XML into a System.Configuration.Configuration for each test (rather than put the test configuration xml in the Tests.dll.config file. That is, I'd like to do something like this: Configuration testConfig = new Configuration("... "); MyCustomConfigSection section = testConfig.GetSection("mycustomconfigsection"); Assert.That(section!= null); However, it looks like ConfigurationManager will only give you Configuration instances that are associated with an EXE file or a machine config. Is there a way to load arbitrary XML into a Configuration instance?
TITLE: Is there a way to get a System.Configuration.Configuration instance based on arbitrary xml? QUESTION: I'm trying to unit test a custom ConfigurationSection I've written, and I'd like to load some arbitrary configuration XML into a System.Configuration.Configuration for each test (rather than put the test configuration xml in the Tests.dll.config file. That is, I'd like to do something like this: Configuration testConfig = new Configuration("... "); MyCustomConfigSection section = testConfig.GetSection("mycustomconfigsection"); Assert.That(section!= null); However, it looks like ConfigurationManager will only give you Configuration instances that are associated with an EXE file or a machine config. Is there a way to load arbitrary XML into a Configuration instance? ANSWER: There is actually a way I've discovered.... You need to define a new class inheriting from your original configuration section as follows: public class MyXmlCustomConfigSection: MyCustomConfigSection { public MyXmlCustomConfigSection (string configXml) { XmlTextReader reader = new XmlTextReader(new StringReader(configXml)); DeserializeSection(reader); } } You can then instantiate your ConfigurationSection object as follows: string configXml = "... "; MyCustomConfigSection config = new MyXmlCustomConfigSection(configXml); Hope it helps someone:-)
[ "c#", ".net", "testing", "configuration", "configurationmanager" ]
14
18
4,319
3
0
2008-08-21T19:49:31.050000
2009-04-01T09:47:59.623000
20,959
20,974
Determine Loaded Assemblies
How can I determine all of the assemblies that my.NET desktop application has loaded? I'd like to put them in the about box so I can query customers over the phone to determine what version of XYZ they have on their PC. It would be nice to see both managed and unmanaged assemblies. I realize the list will get long but I plan to slap an incremental search on it.
using System; using System.Reflection; using System.Windows.Forms; public class MyAppDomain { public static void Main(string[] args) { AppDomain ad = AppDomain.CurrentDomain; Assembly[] loadedAssemblies = ad.GetAssemblies(); Console.WriteLine("Here are the assemblies loaded in this appdomain\n"); foreach(Assembly a in loadedAssemblies) { Console.WriteLine(a.FullName); } } }
Determine Loaded Assemblies How can I determine all of the assemblies that my.NET desktop application has loaded? I'd like to put them in the about box so I can query customers over the phone to determine what version of XYZ they have on their PC. It would be nice to see both managed and unmanaged assemblies. I realize the list will get long but I plan to slap an incremental search on it.
TITLE: Determine Loaded Assemblies QUESTION: How can I determine all of the assemblies that my.NET desktop application has loaded? I'd like to put them in the about box so I can query customers over the phone to determine what version of XYZ they have on their PC. It would be nice to see both managed and unmanaged assemblies. I realize the list will get long but I plan to slap an incremental search on it. ANSWER: using System; using System.Reflection; using System.Windows.Forms; public class MyAppDomain { public static void Main(string[] args) { AppDomain ad = AppDomain.CurrentDomain; Assembly[] loadedAssemblies = ad.GetAssemblies(); Console.WriteLine("Here are the assemblies loaded in this appdomain\n"); foreach(Assembly a in loadedAssemblies) { Console.WriteLine(a.FullName); } } }
[ ".net", "winforms", "dll", "assemblies" ]
10
12
4,872
5
0
2008-08-21T19:50:44.167000
2008-08-21T19:55:15.573000
20,993
21,031
Storing logged in user details
When creating a web application, and lets say you have a User object denoting a single user, what do you think is the best way to store that the user has logged in? Two ways I've thought about have been: Stored the user database id in a session variable Stored the entire user object in a session variable Any better suggestions, any issues with using the above ways? Perhaps security issues or memory issues, etc, etc.
I recommend storing the id rather than the object. The downside is that you have to hit the database every time you want to get that user's information. However, unless every millisecond counts in your page, the performance shouldn't be an issue. Here are two advantages: If the user's information changes somehow, then you won't be storing out-of-date information in your session. For example, if a user is granted extra privileges by an admin, then those will be immediately available without the user needing to log out and then log back in. If your session information is stored on the hard drive, then you can only store serializable data. So if your User object ever contains anything like a database connection, open socket, file descriptor, etc then this will not be stored properly and may not be cleaned up properly either. In most cases these concerns won't be an issue and either approach would be fine.
Storing logged in user details When creating a web application, and lets say you have a User object denoting a single user, what do you think is the best way to store that the user has logged in? Two ways I've thought about have been: Stored the user database id in a session variable Stored the entire user object in a session variable Any better suggestions, any issues with using the above ways? Perhaps security issues or memory issues, etc, etc.
TITLE: Storing logged in user details QUESTION: When creating a web application, and lets say you have a User object denoting a single user, what do you think is the best way to store that the user has logged in? Two ways I've thought about have been: Stored the user database id in a session variable Stored the entire user object in a session variable Any better suggestions, any issues with using the above ways? Perhaps security issues or memory issues, etc, etc. ANSWER: I recommend storing the id rather than the object. The downside is that you have to hit the database every time you want to get that user's information. However, unless every millisecond counts in your page, the performance shouldn't be an issue. Here are two advantages: If the user's information changes somehow, then you won't be storing out-of-date information in your session. For example, if a user is granted extra privileges by an admin, then those will be immediately available without the user needing to log out and then log back in. If your session information is stored on the hard drive, then you can only store serializable data. So if your User object ever contains anything like a database connection, open socket, file descriptor, etc then this will not be stored properly and may not be cleaned up properly either. In most cases these concerns won't be an issue and either approach would be fine.
[ "web-applications" ]
9
12
4,135
8
0
2008-08-21T19:59:57.217000
2008-08-21T20:09:47.333000
20,998
21,074
Cannot Add a Sql Server Login
When I try to create a SQL Server Login by saying CREATE LOGIN [ourdomain\SQLAccessGroup] FROM WINDOWS; I get this error The server principal 'ourdomain\SQLAccessGroup' already exists. However, when I try this code DROP LOGIN [ourdomain\SQLAccessGroup] I get this error Cannot drop the login 'ourdomain\SQLAccessGroup', because it does not exist or you do not have permission. The user that I am executing this code as is a sysadmin. Additionally, the user ourdomain\SQLAccessGroup does not show up in this query select * from sys.server_principals Does anyone have any ideas?
We are still struggling to understand the HOW of this issue, but it seems that [ourdomain\SQLAccessGroup] was aliased by a consultant to a different user name (this is part of an MS CRM installation). We finally were able to use some logic and some good old SID comparisons to determine who was playing the imposter game. Our hint came when I tried to add the login as a user to the database (since it supposedly already existed) and got this error: The login already has an account under a different user name. So, I started to examine each DB user and was able to figure out the culprit. I eventually tracked it down and was able to rename the user and login so that the CRM install would work. I wonder if I can bill them $165.00 an hour for my time...:-)
Cannot Add a Sql Server Login When I try to create a SQL Server Login by saying CREATE LOGIN [ourdomain\SQLAccessGroup] FROM WINDOWS; I get this error The server principal 'ourdomain\SQLAccessGroup' already exists. However, when I try this code DROP LOGIN [ourdomain\SQLAccessGroup] I get this error Cannot drop the login 'ourdomain\SQLAccessGroup', because it does not exist or you do not have permission. The user that I am executing this code as is a sysadmin. Additionally, the user ourdomain\SQLAccessGroup does not show up in this query select * from sys.server_principals Does anyone have any ideas?
TITLE: Cannot Add a Sql Server Login QUESTION: When I try to create a SQL Server Login by saying CREATE LOGIN [ourdomain\SQLAccessGroup] FROM WINDOWS; I get this error The server principal 'ourdomain\SQLAccessGroup' already exists. However, when I try this code DROP LOGIN [ourdomain\SQLAccessGroup] I get this error Cannot drop the login 'ourdomain\SQLAccessGroup', because it does not exist or you do not have permission. The user that I am executing this code as is a sysadmin. Additionally, the user ourdomain\SQLAccessGroup does not show up in this query select * from sys.server_principals Does anyone have any ideas? ANSWER: We are still struggling to understand the HOW of this issue, but it seems that [ourdomain\SQLAccessGroup] was aliased by a consultant to a different user name (this is part of an MS CRM installation). We finally were able to use some logic and some good old SID comparisons to determine who was playing the imposter game. Our hint came when I tried to add the login as a user to the database (since it supposedly already existed) and got this error: The login already has an account under a different user name. So, I started to examine each DB user and was able to figure out the culprit. I eventually tracked it down and was able to rename the user and login so that the CRM install would work. I wonder if I can bill them $165.00 an hour for my time...:-)
[ "sql-server", "sql-server-2005", "administration" ]
11
8
23,969
5
0
2008-08-21T20:00:59.430000
2008-08-21T20:27:04.047000
21,052
21,056
"using" namespace equivalent in ASP.NET markup
When I'm working with DataBound controls in ASP.NET 2.0 such as a Repeater, I know the fastest way to retrieve a property of a bound object (instead of using Reflection with the Eval() function) is to cast the DataItem object to the type it is and then use that object natively, like the following: <%#((MyType)Container.DataItem).PropertyOfMyType%> The problem is, if this type is in a namespace (which is the case 99.99% of the time) then this single statement because a lot longer due to the fact that the ASP page has no concept of class scope so all of my types need to be fully qualified. <%#((RootNamespace.SubNamespace1.SubNamspace2.SubNamespace3.MyType)Container.DataItem).PropertyOfMyType%> Is there any kind of using directive or some equivalent I could place somewhere in an ASP.NET page so I don't need to use the full namespace every time?
I believe you can add something like: <%@ Import Namespace="RootNamespace.SubNamespace1" %> At the top of the page.
"using" namespace equivalent in ASP.NET markup When I'm working with DataBound controls in ASP.NET 2.0 such as a Repeater, I know the fastest way to retrieve a property of a bound object (instead of using Reflection with the Eval() function) is to cast the DataItem object to the type it is and then use that object natively, like the following: <%#((MyType)Container.DataItem).PropertyOfMyType%> The problem is, if this type is in a namespace (which is the case 99.99% of the time) then this single statement because a lot longer due to the fact that the ASP page has no concept of class scope so all of my types need to be fully qualified. <%#((RootNamespace.SubNamespace1.SubNamspace2.SubNamespace3.MyType)Container.DataItem).PropertyOfMyType%> Is there any kind of using directive or some equivalent I could place somewhere in an ASP.NET page so I don't need to use the full namespace every time?
TITLE: "using" namespace equivalent in ASP.NET markup QUESTION: When I'm working with DataBound controls in ASP.NET 2.0 such as a Repeater, I know the fastest way to retrieve a property of a bound object (instead of using Reflection with the Eval() function) is to cast the DataItem object to the type it is and then use that object natively, like the following: <%#((MyType)Container.DataItem).PropertyOfMyType%> The problem is, if this type is in a namespace (which is the case 99.99% of the time) then this single statement because a lot longer due to the fact that the ASP page has no concept of class scope so all of my types need to be fully qualified. <%#((RootNamespace.SubNamespace1.SubNamspace2.SubNamespace3.MyType)Container.DataItem).PropertyOfMyType%> Is there any kind of using directive or some equivalent I could place somewhere in an ASP.NET page so I don't need to use the full namespace every time? ANSWER: I believe you can add something like: <%@ Import Namespace="RootNamespace.SubNamespace1" %> At the top of the page.
[ "asp.net" ]
27
65
17,909
2
0
2008-08-21T20:20:22.393000
2008-08-21T20:21:58.803000
21,060
21,466
Is there any way to configure windows to not change the focus?
I'm tired of being in the middle of typing something, having a pop-up with a question appear, and hitting enter before reading it... (it also happens with some windows that are not pop-ups) Do you know if there's some setting I could touch for this not to happen?
It suppose to be a registry change that helps with this type of situations (mentioned in this Coding Horror post about the subject of "focus stealing"). I try it, it doesn't work with all popups but helps with some of them, causing the offending application to flash in the taskbar instead of gain focus.
Is there any way to configure windows to not change the focus? I'm tired of being in the middle of typing something, having a pop-up with a question appear, and hitting enter before reading it... (it also happens with some windows that are not pop-ups) Do you know if there's some setting I could touch for this not to happen?
TITLE: Is there any way to configure windows to not change the focus? QUESTION: I'm tired of being in the middle of typing something, having a pop-up with a question appear, and hitting enter before reading it... (it also happens with some windows that are not pop-ups) Do you know if there's some setting I could touch for this not to happen? ANSWER: It suppose to be a registry change that helps with this type of situations (mentioned in this Coding Horror post about the subject of "focus stealing"). I try it, it doesn't work with all popups but helps with some of them, causing the offending application to flash in the taskbar instead of gain focus.
[ "windows", "configuration" ]
1
0
148
3
0
2008-08-21T20:22:50.283000
2008-08-21T23:54:07.730000
21,078
21,093
Most efficient way to concatenate strings?
What's the most efficient way to concatenate strings?
The StringBuilder.Append() method is much better than using the + operator. But I've found that, when executing 1000 concatenations or less, String.Join() is even more efficient than StringBuilder. StringBuilder sb = new StringBuilder(); sb.Append(someString); The only problem with String.Join is that you have to concatenate the strings with a common delimiter. Edit: as @ryanversaw pointed out, you can make the delimiter string.Empty. string key = String.Join("_", new String[] { "Customers_Contacts", customerID, database, SessionID });
Most efficient way to concatenate strings? What's the most efficient way to concatenate strings?
TITLE: Most efficient way to concatenate strings? QUESTION: What's the most efficient way to concatenate strings? ANSWER: The StringBuilder.Append() method is much better than using the + operator. But I've found that, when executing 1000 concatenations or less, String.Join() is even more efficient than StringBuilder. StringBuilder sb = new StringBuilder(); sb.Append(someString); The only problem with String.Join is that you have to concatenate the strings with a common delimiter. Edit: as @ryanversaw pointed out, you can make the delimiter string.Empty. string key = String.Join("_", new String[] { "Customers_Contacts", customerID, database, SessionID });
[ "c#", ".net", "string", "performance", "optimization" ]
351
174
274,700
18
0
2008-08-21T20:27:15.497000
2008-08-21T20:30:36.677000
21,091
96,690
Do you use MDA/MDD/MDSD, any kind of model-driven approach? Will it be the future?
Programming languages had several (r)evolutionary steps in their history. Some people argue that model-driven approaches will be The Next Big Thing. There are tools like openArchitectureWare, AndroMDA, Sculptor/Fornax Platform etc. that promise incredible productivity boosts. However, I made the experience that it is either rather easy in the beginning to get started but as well to get stuck at some point when you try something that was unanticipated or pretty hard to find enough information that tells you how to start your project because there may be a lot of things to consider. I think an important insight to get anything out of model-driven something is to understand that the model is not necessarily a set of nice pictures or tree model or UML, but may as well be a textual description (e.g. a state machine, business rules etc.). What do you think and what does your experience tell you? Is there a future for model-driven development (or whatever you may want to call it)? Update: There does not seem to be a lot of interest in this topic. Please let me know, if you have any (good or bad) experience with model-driven approaches or why you think it's not interesting at all.
I think, it will take time, till the tools get more refined, more people gain experience with MDD. At the moment if you want to get something out of MDD you have to invest quite a lot, so its use remains limited. Looking at openArchitectureWare for example: While it is quite robust and basic documentation exists, documentation on the inner workings are missing and there are still problems with scalability, that are undocumented - maybe that will get better when Xtext and Xpand get rewritten. But despise those limitations the generation itself is quite easy with oAW, you can navigate your models like a charm in Xtend and Xpand and by combining several workflows into bigger workflows, you can also do very complex things. If needed you can resort to Java, so you have a very big flexibility in what you can do with your models. Writing your own DSL with Xtext in oAW, too, is quickly done, yet you get your meta-model, a parser and a very nice editor basically for free. Also you can get your models basically from everywhere, e.g. a component that can convert a database into a meta-model and corresponding models can be written without big effort. So I would say, MDD is still building up, as tools and experience with it increases. It can already used successfully, if you have the necessary expertise and are ready to push it within your company. In the end, I think, it is a very good thing, because a lot of glue code (aka copy paste) can and should be generated. Doing that with MDD is a very nice and structured way of doing this, that facilitates reusability, in my opinion.
Do you use MDA/MDD/MDSD, any kind of model-driven approach? Will it be the future? Programming languages had several (r)evolutionary steps in their history. Some people argue that model-driven approaches will be The Next Big Thing. There are tools like openArchitectureWare, AndroMDA, Sculptor/Fornax Platform etc. that promise incredible productivity boosts. However, I made the experience that it is either rather easy in the beginning to get started but as well to get stuck at some point when you try something that was unanticipated or pretty hard to find enough information that tells you how to start your project because there may be a lot of things to consider. I think an important insight to get anything out of model-driven something is to understand that the model is not necessarily a set of nice pictures or tree model or UML, but may as well be a textual description (e.g. a state machine, business rules etc.). What do you think and what does your experience tell you? Is there a future for model-driven development (or whatever you may want to call it)? Update: There does not seem to be a lot of interest in this topic. Please let me know, if you have any (good or bad) experience with model-driven approaches or why you think it's not interesting at all.
TITLE: Do you use MDA/MDD/MDSD, any kind of model-driven approach? Will it be the future? QUESTION: Programming languages had several (r)evolutionary steps in their history. Some people argue that model-driven approaches will be The Next Big Thing. There are tools like openArchitectureWare, AndroMDA, Sculptor/Fornax Platform etc. that promise incredible productivity boosts. However, I made the experience that it is either rather easy in the beginning to get started but as well to get stuck at some point when you try something that was unanticipated or pretty hard to find enough information that tells you how to start your project because there may be a lot of things to consider. I think an important insight to get anything out of model-driven something is to understand that the model is not necessarily a set of nice pictures or tree model or UML, but may as well be a textual description (e.g. a state machine, business rules etc.). What do you think and what does your experience tell you? Is there a future for model-driven development (or whatever you may want to call it)? Update: There does not seem to be a lot of interest in this topic. Please let me know, if you have any (good or bad) experience with model-driven approaches or why you think it's not interesting at all. ANSWER: I think, it will take time, till the tools get more refined, more people gain experience with MDD. At the moment if you want to get something out of MDD you have to invest quite a lot, so its use remains limited. Looking at openArchitectureWare for example: While it is quite robust and basic documentation exists, documentation on the inner workings are missing and there are still problems with scalability, that are undocumented - maybe that will get better when Xtext and Xpand get rewritten. But despise those limitations the generation itself is quite easy with oAW, you can navigate your models like a charm in Xtend and Xpand and by combining several workflows into bigger workflows, you can also do very complex things. If needed you can resort to Java, so you have a very big flexibility in what you can do with your models. Writing your own DSL with Xtext in oAW, too, is quickly done, yet you get your meta-model, a parser and a very nice editor basically for free. Also you can get your models basically from everywhere, e.g. a component that can convert a database into a meta-model and corresponding models can be written without big effort. So I would say, MDD is still building up, as tools and experience with it increases. It can already used successfully, if you have the necessary expertise and are ready to push it within your company. In the end, I think, it is a very good thing, because a lot of glue code (aka copy paste) can and should be generated. Doing that with MDD is a very nice and structured way of doing this, that facilitates reusability, in my opinion.
[ "paradigms", "model-driven" ]
7
3
1,428
9
0
2008-08-21T20:29:48.143000
2008-09-18T20:39:25.220000
21,133
21,189
Simplest way to profile a PHP script
What's the easiest way to profile a PHP script? I'd love tacking something on that shows me a dump of all function calls and how long they took but I'm also OK with putting something around specific functions. I tried experimenting with the microtime function: $then = microtime(); myFunc(); $now = microtime(); echo sprintf("Elapsed: %f", $now-$then); but that sometimes gives me negative results. Plus it's a lot of trouble to sprinkle that all over my code.
The PECL APD extension is used as follows: After, parse the generated file using pprofp. Example output: Trace for /home/dan/testapd.php Total Elapsed Time = 0.00 Total System Time = 0.00 Total User Time = 0.00 Real User System secs/ cumm %Time (excl/cumm) (excl/cumm) (excl/cumm) Calls call s/call Memory Usage Name -------------------------------------------------------------------------------------- 100.0 0.00 0.00 0.00 0.00 0.00 0.00 1 0.0000 0.0009 0 main 56.9 0.00 0.00 0.00 0.00 0.00 0.00 1 0.0005 0.0005 0 apd_set_pprof_trace 28.0 0.00 0.00 0.00 0.00 0.00 0.00 10 0.0000 0.0000 0 preg_replace 14.3 0.00 0.00 0.00 0.00 0.00 0.00 10 0.0000 0.0000 0 str_replace Warning: the latest release of APD is dated 2004, the extension is no longer maintained and has various compability issues (see comments).
Simplest way to profile a PHP script What's the easiest way to profile a PHP script? I'd love tacking something on that shows me a dump of all function calls and how long they took but I'm also OK with putting something around specific functions. I tried experimenting with the microtime function: $then = microtime(); myFunc(); $now = microtime(); echo sprintf("Elapsed: %f", $now-$then); but that sometimes gives me negative results. Plus it's a lot of trouble to sprinkle that all over my code.
TITLE: Simplest way to profile a PHP script QUESTION: What's the easiest way to profile a PHP script? I'd love tacking something on that shows me a dump of all function calls and how long they took but I'm also OK with putting something around specific functions. I tried experimenting with the microtime function: $then = microtime(); myFunc(); $now = microtime(); echo sprintf("Elapsed: %f", $now-$then); but that sometimes gives me negative results. Plus it's a lot of trouble to sprinkle that all over my code. ANSWER: The PECL APD extension is used as follows: After, parse the generated file using pprofp. Example output: Trace for /home/dan/testapd.php Total Elapsed Time = 0.00 Total System Time = 0.00 Total User Time = 0.00 Real User System secs/ cumm %Time (excl/cumm) (excl/cumm) (excl/cumm) Calls call s/call Memory Usage Name -------------------------------------------------------------------------------------- 100.0 0.00 0.00 0.00 0.00 0.00 0.00 1 0.0000 0.0009 0 main 56.9 0.00 0.00 0.00 0.00 0.00 0.00 1 0.0005 0.0005 0 apd_set_pprof_trace 28.0 0.00 0.00 0.00 0.00 0.00 0.00 10 0.0000 0.0000 0 preg_replace 14.3 0.00 0.00 0.00 0.00 0.00 0.00 10 0.0000 0.0000 0 str_replace Warning: the latest release of APD is dated 2004, the extension is no longer maintained and has various compability issues (see comments).
[ "php", "profiling" ]
323
108
218,463
14
0
2008-08-21T20:40:38.117000
2008-08-21T21:04:17.157000
21,137
23,481
Adding NUnit to the options for ASP.NET MVC test framework
I have nUnit installed. I have VS2008 Team Edition installed. I have ASP.Net MVC Preview 4 (Codeplex) installed. How do I make Visual Studio show me nUnit as a testing framework when creating a new MVC project? At this point I still only have the Microsoft Testing Framework as a choice. Update: I installed nUnit 2.5, but still with no success. From what I've found Googling, it would seem I need to create templates for the test projects in order for them to be displayed in the "Create Unit Test Project". I would have thought that templates be readily available for nUnit, xUnit, MBUnit, et. al. Also, it looks like I need to created registry entries. Anybody have any additional information? Update: I determined the answer to this through research and it's posted below.
After a bunch of research and experimentation, I've found the answer. For the record, the current release of nUnit 2.5 Alpha does not seem to contain templates for test projects in Visual Studio 2008. I followed the directions here which describe how to create your own project templates and then add appropriate registry entries that allow your templates to appear in the drop-down box in the Create Unit Test Project dialog box of an MVC project. From a high level, what you have to do is: Create a project Export it as a template (which results in a single ZIP archive) Copy it from the local user's template folder to the Visual Studio main template test folder Execute devenv.exe /setup Run regedit and create a few registry entries. So much for the testing framework selection being easy! Although, to be fair MVC is not even beta yet. After all that, I did get the framework of choice (NUnit) to show up in the drop down box. However, there was still a bit left to be desired: Although the test project gets properly created, it did not automatically have a project reference to the main MVC project. When using Visual Studio Unit Test as the test project, it automatically does this. I tried to open the ZIP file produced and edit the MyTemplate.vssettings file as well as the.csproj project file in order to correct the aforementioned issue as well as tweak the names of things so they'd appear more user friendly. This for some reason does not work. The ZIP file produced can not be updated via WinZip or Win-Rar -- each indicates the archive is corrupt. Each can extract the contents, though. So, I tried updating the extracted files and then recreating the ZIP file. Visual Studio did not like it. So, I should probably read this as well which discusses making project templates for Visual Studio (also referenced in the blog post I linked to above.) I admit to being disappointed though; from all the talk about MVC playing well with other testing frameworks, etc, I thought that it'd be easier to register a 3rd party framework.
Adding NUnit to the options for ASP.NET MVC test framework I have nUnit installed. I have VS2008 Team Edition installed. I have ASP.Net MVC Preview 4 (Codeplex) installed. How do I make Visual Studio show me nUnit as a testing framework when creating a new MVC project? At this point I still only have the Microsoft Testing Framework as a choice. Update: I installed nUnit 2.5, but still with no success. From what I've found Googling, it would seem I need to create templates for the test projects in order for them to be displayed in the "Create Unit Test Project". I would have thought that templates be readily available for nUnit, xUnit, MBUnit, et. al. Also, it looks like I need to created registry entries. Anybody have any additional information? Update: I determined the answer to this through research and it's posted below.
TITLE: Adding NUnit to the options for ASP.NET MVC test framework QUESTION: I have nUnit installed. I have VS2008 Team Edition installed. I have ASP.Net MVC Preview 4 (Codeplex) installed. How do I make Visual Studio show me nUnit as a testing framework when creating a new MVC project? At this point I still only have the Microsoft Testing Framework as a choice. Update: I installed nUnit 2.5, but still with no success. From what I've found Googling, it would seem I need to create templates for the test projects in order for them to be displayed in the "Create Unit Test Project". I would have thought that templates be readily available for nUnit, xUnit, MBUnit, et. al. Also, it looks like I need to created registry entries. Anybody have any additional information? Update: I determined the answer to this through research and it's posted below. ANSWER: After a bunch of research and experimentation, I've found the answer. For the record, the current release of nUnit 2.5 Alpha does not seem to contain templates for test projects in Visual Studio 2008. I followed the directions here which describe how to create your own project templates and then add appropriate registry entries that allow your templates to appear in the drop-down box in the Create Unit Test Project dialog box of an MVC project. From a high level, what you have to do is: Create a project Export it as a template (which results in a single ZIP archive) Copy it from the local user's template folder to the Visual Studio main template test folder Execute devenv.exe /setup Run regedit and create a few registry entries. So much for the testing framework selection being easy! Although, to be fair MVC is not even beta yet. After all that, I did get the framework of choice (NUnit) to show up in the drop down box. However, there was still a bit left to be desired: Although the test project gets properly created, it did not automatically have a project reference to the main MVC project. When using Visual Studio Unit Test as the test project, it automatically does this. I tried to open the ZIP file produced and edit the MyTemplate.vssettings file as well as the.csproj project file in order to correct the aforementioned issue as well as tweak the names of things so they'd appear more user friendly. This for some reason does not work. The ZIP file produced can not be updated via WinZip or Win-Rar -- each indicates the archive is corrupt. Each can extract the contents, though. So, I tried updating the extracted files and then recreating the ZIP file. Visual Studio did not like it. So, I should probably read this as well which discusses making project templates for Visual Studio (also referenced in the blog post I linked to above.) I admit to being disappointed though; from all the talk about MVC playing well with other testing frameworks, etc, I thought that it'd be easier to register a 3rd party framework.
[ "asp.net", "asp.net-mvc", "visual-studio", "unit-testing", "nunit" ]
31
19
8,114
4
0
2008-08-21T20:43:29.220000
2008-08-22T21:02:27.777000
21,184
21,389
How do I use Linq for paging a generic collection?
I've got a System.Generic.Collections.List(Of MyCustomClass) type object. Given integer varaibles pagesize and pagenumber, how can I query only any single page of MyCustomClass objects?
If you have your linq-query that contains all the rows you want to display, this code can be used: var pageNum = 3; var pageSize = 20; query = query.Skip((pageNum - 1) * pageSize).Take(pageSize); You can also make an extension method on the object to be able to write query.Page(2,50) to get the first 50 records of page 2. If that is want you want, the information is on the solid code blog.
How do I use Linq for paging a generic collection? I've got a System.Generic.Collections.List(Of MyCustomClass) type object. Given integer varaibles pagesize and pagenumber, how can I query only any single page of MyCustomClass objects?
TITLE: How do I use Linq for paging a generic collection? QUESTION: I've got a System.Generic.Collections.List(Of MyCustomClass) type object. Given integer varaibles pagesize and pagenumber, how can I query only any single page of MyCustomClass objects? ANSWER: If you have your linq-query that contains all the rows you want to display, this code can be used: var pageNum = 3; var pageSize = 20; query = query.Skip((pageNum - 1) * pageSize).Take(pageSize); You can also make an extension method on the object to be able to write query.Page(2,50) to get the first 50 records of page 2. If that is want you want, the information is on the solid code blog.
[ ".net", "linq", ".net-3.5", "paging" ]
15
30
8,375
2
0
2008-08-21T21:03:39.920000
2008-08-21T23:02:29.273000
21,207
24,499
db4o experiences?
I'm currently trying out db4o (the java version) and I pretty much like what I see. But I cannot help wondering how it does perform in a real live (web-)environment. Does anyone have any experiences (good or bad) to share about running db4o?
We run DB40.NET version in a large client/server project. Our experiences is that you can potentially get much better performance than typical relational databases. However, you really have to tweak your objects to get this kind of performance. For example, if you've got a list containing a lot of objects, DB4O activation of these lists is slow. There are a number of ways to get around this problem, for example, by inverting the relationship. Another pain is activation. When you retrieve or delete an object from DB4O, by default it will activate the whole object tree. For example, loading a Foo will load Foo.Bar.Baz.Bat, etc until there's nothing left to load. While this is nice from a programming standpoint, performance will slow down the more nesting in your objects. To improve performance, you can tell DB4O how many levels deep to activate. This is time-consuming to do if you've got a lot of objects. Another area of pain was text searching. DB4O's text searching is far, far slower than SQL full text indexing. (They'll tell you this outright on their site.) The good news is, it's easy to setup a text searching engine on top of DB4O. On our project, we've hooked up Lucene.NET to index the text fields we want. Some APIs don't seem to work, such as the GetField APIs useful in applying database upgrades. (For example, you've renamed a property and you want to upgrade your existing objects in the database, you need to use these "reflection" APIs to find objects in the database. Other APIs, such as the [Index] attribute don't work in the stable 6.4 version, and you must instead specify indexes using the Configure().Index("someField"), which is not strongly typed. We've witnessed performance degrade the larger your database. We have a 1GB database right now and things are still fast, but not nearly as fast as when we started with a tiny database. We've found another issue where Db4O.GetByID will close the database if the ID doesn't exist anymore in the database. We've found the Native Query syntax (the most natural, language-integrated syntax for queries) is far, far slower than the less-friendly SODA queries. So instead of typing: // C# syntax for "Find all MyFoos with Bar == 23". // (Note the Java syntax is more verbose using the Predicate class.) IList results = db4o.Query (input => input.Bar == 23); Instead of that nice query code, you have to an ugly SODA query which is string-based and not strongly-typed. For.NET folks, they've recently introduced a LINQ-to-DB4O provider, which provides for the best syntax yet. However, it's yet to be seen whether performance will be up-to-par with the ugly SODA queries. DB4O support has been decent: we've talked to them on the phone a number of times and have received helpful info. Their user forums are next to worthless, however, almost all questions go unanswered. Their JIRA bug tracker receives a lot of attention, so if you've got a nagging bug, file it on JIRA on it often will get fixed. (We've had 2 bugs that have been fixed, and another one that got patched in a half-assed way.) If all this hasn't scared you off, let me say that we're very happy with DB4O, despite the problems we've encountered. The performance we've got has blown away some O/RM frameworks we tried. I recommend it. update July 2015 Keep in mind, this answer was written back in 2008. While I appreciate the upvotes, the world has changed since then, and this information may not be as reliable as it was when it was written.
db4o experiences? I'm currently trying out db4o (the java version) and I pretty much like what I see. But I cannot help wondering how it does perform in a real live (web-)environment. Does anyone have any experiences (good or bad) to share about running db4o?
TITLE: db4o experiences? QUESTION: I'm currently trying out db4o (the java version) and I pretty much like what I see. But I cannot help wondering how it does perform in a real live (web-)environment. Does anyone have any experiences (good or bad) to share about running db4o? ANSWER: We run DB40.NET version in a large client/server project. Our experiences is that you can potentially get much better performance than typical relational databases. However, you really have to tweak your objects to get this kind of performance. For example, if you've got a list containing a lot of objects, DB4O activation of these lists is slow. There are a number of ways to get around this problem, for example, by inverting the relationship. Another pain is activation. When you retrieve or delete an object from DB4O, by default it will activate the whole object tree. For example, loading a Foo will load Foo.Bar.Baz.Bat, etc until there's nothing left to load. While this is nice from a programming standpoint, performance will slow down the more nesting in your objects. To improve performance, you can tell DB4O how many levels deep to activate. This is time-consuming to do if you've got a lot of objects. Another area of pain was text searching. DB4O's text searching is far, far slower than SQL full text indexing. (They'll tell you this outright on their site.) The good news is, it's easy to setup a text searching engine on top of DB4O. On our project, we've hooked up Lucene.NET to index the text fields we want. Some APIs don't seem to work, such as the GetField APIs useful in applying database upgrades. (For example, you've renamed a property and you want to upgrade your existing objects in the database, you need to use these "reflection" APIs to find objects in the database. Other APIs, such as the [Index] attribute don't work in the stable 6.4 version, and you must instead specify indexes using the Configure().Index("someField"), which is not strongly typed. We've witnessed performance degrade the larger your database. We have a 1GB database right now and things are still fast, but not nearly as fast as when we started with a tiny database. We've found another issue where Db4O.GetByID will close the database if the ID doesn't exist anymore in the database. We've found the Native Query syntax (the most natural, language-integrated syntax for queries) is far, far slower than the less-friendly SODA queries. So instead of typing: // C# syntax for "Find all MyFoos with Bar == 23". // (Note the Java syntax is more verbose using the Predicate class.) IList results = db4o.Query (input => input.Bar == 23); Instead of that nice query code, you have to an ugly SODA query which is string-based and not strongly-typed. For.NET folks, they've recently introduced a LINQ-to-DB4O provider, which provides for the best syntax yet. However, it's yet to be seen whether performance will be up-to-par with the ugly SODA queries. DB4O support has been decent: we've talked to them on the phone a number of times and have received helpful info. Their user forums are next to worthless, however, almost all questions go unanswered. Their JIRA bug tracker receives a lot of attention, so if you've got a nagging bug, file it on JIRA on it often will get fixed. (We've had 2 bugs that have been fixed, and another one that got patched in a half-assed way.) If all this hasn't scared you off, let me say that we're very happy with DB4O, despite the problems we've encountered. The performance we've got has blown away some O/RM frameworks we tried. I recommend it. update July 2015 Keep in mind, this answer was written back in 2008. While I appreciate the upvotes, the world has changed since then, and this information may not be as reliable as it was when it was written.
[ "java", "db4o" ]
32
56
6,837
4
0
2008-08-21T21:12:01.600000
2008-08-23T19:03:18.913000
21,229
21,414
Visual Web Developer (Express): Setting Document Root for Dev Environment
I'm developing a site in Visual Web Dev Express, and when I run/debug, I'd like to be able to set my application's document root so that I can use safer paths, like "/css/style.css' instead of "css/style.css". How would I accomplish this?
Click on the web site node in the solution explorer. Press F4 to see the properties window. Change the virtual path from /projectname to / Bear in mind that this has an impact on how you expect the application/web site to be deployed. If it is ever used outside the root of a web server, the URL paths will be incorrect.
Visual Web Developer (Express): Setting Document Root for Dev Environment I'm developing a site in Visual Web Dev Express, and when I run/debug, I'd like to be able to set my application's document root so that I can use safer paths, like "/css/style.css' instead of "css/style.css". How would I accomplish this?
TITLE: Visual Web Developer (Express): Setting Document Root for Dev Environment QUESTION: I'm developing a site in Visual Web Dev Express, and when I run/debug, I'd like to be able to set my application's document root so that I can use safer paths, like "/css/style.css' instead of "css/style.css". How would I accomplish this? ANSWER: Click on the web site node in the solution explorer. Press F4 to see the properties window. Change the virtual path from /projectname to / Bear in mind that this has an impact on how you expect the application/web site to be deployed. If it is ever used outside the root of a web server, the URL paths will be incorrect.
[ "c#", "asp.net", "visual-web-developer", "server-configuration" ]
1
5
1,329
3
0
2008-08-21T21:28:20.123000
2008-08-21T23:18:56.317000
21,243
21,434
Anyone have a link to a technical discussion of anything akin to the Facebook news feed system?
I'm looking for a presentation, PDF, blog post, or whitepaper discussing the technical details of how to filter down and display massive amounts of information for individual users in an intelligent (possibly machine learning) kind of way. I've had coworkers hear presentations on the Facebook news feed but I can't find anything published anywhere that goes into the dirty details. Searches seem to just turn up the controversy of the system. Maybe I'm not searching for the right keywords... @AlexCuse I'm trying to build something similar to Facebook's system. I have large amounts of data and I need to filter it down to something manageable to present to the user. I cannot use another website due to the scale of what I've got to work at. Also I just want a technical discussion of how to implement it, not examples of people who have an implementation.
Are you looking for something along the lines of distributed pub/sub with content based filtering? If so, you may want to look into Siena and some of the associated papers such as Design and Evaluation of a Wide-Area Event Notification Service
Anyone have a link to a technical discussion of anything akin to the Facebook news feed system? I'm looking for a presentation, PDF, blog post, or whitepaper discussing the technical details of how to filter down and display massive amounts of information for individual users in an intelligent (possibly machine learning) kind of way. I've had coworkers hear presentations on the Facebook news feed but I can't find anything published anywhere that goes into the dirty details. Searches seem to just turn up the controversy of the system. Maybe I'm not searching for the right keywords... @AlexCuse I'm trying to build something similar to Facebook's system. I have large amounts of data and I need to filter it down to something manageable to present to the user. I cannot use another website due to the scale of what I've got to work at. Also I just want a technical discussion of how to implement it, not examples of people who have an implementation.
TITLE: Anyone have a link to a technical discussion of anything akin to the Facebook news feed system? QUESTION: I'm looking for a presentation, PDF, blog post, or whitepaper discussing the technical details of how to filter down and display massive amounts of information for individual users in an intelligent (possibly machine learning) kind of way. I've had coworkers hear presentations on the Facebook news feed but I can't find anything published anywhere that goes into the dirty details. Searches seem to just turn up the controversy of the system. Maybe I'm not searching for the right keywords... @AlexCuse I'm trying to build something similar to Facebook's system. I have large amounts of data and I need to filter it down to something manageable to present to the user. I cannot use another website due to the scale of what I've got to work at. Also I just want a technical discussion of how to implement it, not examples of people who have an implementation. ANSWER: Are you looking for something along the lines of distributed pub/sub with content based filtering? If so, you may want to look into Siena and some of the associated papers such as Design and Evaluation of a Wide-Area Event Notification Service
[ "facebook" ]
0
4
285
1
0
2008-08-21T21:38:43.190000
2008-08-21T23:33:31.103000
21,262
21,270
How do I create a mapping table in SQL Server Management Studio?
I'm learning about table design in SQL and I'm wonder how to create a mapping table in order to establish a many-to-many relationship between two other tables? I think the mapping table needs two primary keys - but I can't see how to create that as it appears there can only be 1 primary key column? I'm using the Database Diagrams feature to create my tables and relationships.
The easiest way is to simply select both fields by selecting the first field, and then while holding down the Ctrl key selecting the second field. Then clicking the key icon to set them both as the primary key.
How do I create a mapping table in SQL Server Management Studio? I'm learning about table design in SQL and I'm wonder how to create a mapping table in order to establish a many-to-many relationship between two other tables? I think the mapping table needs two primary keys - but I can't see how to create that as it appears there can only be 1 primary key column? I'm using the Database Diagrams feature to create my tables and relationships.
TITLE: How do I create a mapping table in SQL Server Management Studio? QUESTION: I'm learning about table design in SQL and I'm wonder how to create a mapping table in order to establish a many-to-many relationship between two other tables? I think the mapping table needs two primary keys - but I can't see how to create that as it appears there can only be 1 primary key column? I'm using the Database Diagrams feature to create my tables and relationships. ANSWER: The easiest way is to simply select both fields by selecting the first field, and then while holding down the Ctrl key selecting the second field. Then clicking the key icon to set them both as the primary key.
[ "sql-server", "sql-server-2005", "entity-relationship" ]
3
6
6,931
1
0
2008-08-21T21:46:07.413000
2008-08-21T21:49:38.840000
21,265
21,277
Comparing IEEE floats and doubles for equality
What is the best method for comparing IEEE floats and doubles for equality? I have heard of several methods, but I wanted to see what the community thought.
The best approach I think is to compare ULPs. bool is_nan(float f) { return (*reinterpret_cast (&f) & 0x7f800000) == 0x7f800000 && (*reinterpret_cast (&f) & 0x007fffff)!= 0; } bool is_finite(float f) { return (*reinterpret_cast (&f) & 0x7f800000)!= 0x7f800000; } // if this symbol is defined, NaNs are never equal to anything (as is normal in IEEE floating point) // if this symbol is not defined, NaNs are hugely different from regular numbers, but might be equal to each other #define UNEQUAL_NANS 1 // if this symbol is defined, infinites are never equal to finite numbers (as they're unimaginably greater) // if this symbol is not defined, infinities are 1 ULP away from +/- FLT_MAX #define INFINITE_INFINITIES 1 // test whether two IEEE floats are within a specified number of representable values of each other // This depends on the fact that IEEE floats are properly ordered when treated as signed magnitude integers bool equal_float(float lhs, float rhs, unsigned __int32 max_ulp_difference) { #ifdef UNEQUAL_NANS if(is_nan(lhs) || is_nan(rhs)) { return false; } #endif #ifdef INFINITE_INFINITIES if((is_finite(lhs) &&!is_finite(rhs)) || (!is_finite(lhs) && is_finite(rhs))) { return false; } #endif signed __int32 left(*reinterpret_cast (&lhs)); // transform signed magnitude ints into 2s complement signed ints if(left < 0) { left = 0x80000000 - left; } signed __int32 right(*reinterpret_cast (&rhs)); // transform signed magnitude ints into 2s complement signed ints if(right < 0) { right = 0x80000000 - right; } if(static_cast (std::abs(left - right)) <= max_ulp_difference) { return true; } return false; } A similar technique can be used for doubles. The trick is to convert the floats so that they're ordered (as if integers) and then just see how different they are. I have no idea why this damn thing is screwing up my underscores. Edit: Oh, perhaps that is just an artefact of the preview. That's OK then.
Comparing IEEE floats and doubles for equality What is the best method for comparing IEEE floats and doubles for equality? I have heard of several methods, but I wanted to see what the community thought.
TITLE: Comparing IEEE floats and doubles for equality QUESTION: What is the best method for comparing IEEE floats and doubles for equality? I have heard of several methods, but I wanted to see what the community thought. ANSWER: The best approach I think is to compare ULPs. bool is_nan(float f) { return (*reinterpret_cast (&f) & 0x7f800000) == 0x7f800000 && (*reinterpret_cast (&f) & 0x007fffff)!= 0; } bool is_finite(float f) { return (*reinterpret_cast (&f) & 0x7f800000)!= 0x7f800000; } // if this symbol is defined, NaNs are never equal to anything (as is normal in IEEE floating point) // if this symbol is not defined, NaNs are hugely different from regular numbers, but might be equal to each other #define UNEQUAL_NANS 1 // if this symbol is defined, infinites are never equal to finite numbers (as they're unimaginably greater) // if this symbol is not defined, infinities are 1 ULP away from +/- FLT_MAX #define INFINITE_INFINITIES 1 // test whether two IEEE floats are within a specified number of representable values of each other // This depends on the fact that IEEE floats are properly ordered when treated as signed magnitude integers bool equal_float(float lhs, float rhs, unsigned __int32 max_ulp_difference) { #ifdef UNEQUAL_NANS if(is_nan(lhs) || is_nan(rhs)) { return false; } #endif #ifdef INFINITE_INFINITIES if((is_finite(lhs) &&!is_finite(rhs)) || (!is_finite(lhs) && is_finite(rhs))) { return false; } #endif signed __int32 left(*reinterpret_cast (&lhs)); // transform signed magnitude ints into 2s complement signed ints if(left < 0) { left = 0x80000000 - left; } signed __int32 right(*reinterpret_cast (&rhs)); // transform signed magnitude ints into 2s complement signed ints if(right < 0) { right = 0x80000000 - right; } if(static_cast (std::abs(left - right)) <= max_ulp_difference) { return true; } return false; } A similar technique can be used for doubles. The trick is to convert the floats so that they're ordered (as if integers) and then just see how different they are. I have no idea why this damn thing is screwing up my underscores. Edit: Oh, perhaps that is just an artefact of the preview. That's OK then.
[ "variables", "floating-point", "inequality" ]
9
7
5,877
15
0
2008-08-21T21:47:24.230000
2008-08-21T21:53:18.350000
21,274
21,285
What is the easiest-to-use web "rich text editor"
I am looking for a text editor to be used in a web page. Where users can format the text and get a WYSIWYG experience. Doesn't need to be too fancy. But has to be easy to use and integrate into the page. Has to generate HTML as output. Support AJAX (one I checked works only with standard form submit) and has to be small in terms of download to the user's browser.
Well it depends what platform you are on if you are looking for server-side functionality as well, but the defacto badass WYSIWYg in my opinion is FCKeditor. I have worked with this personally in numerous environments (both professional and hobby level) and have always been impressed. It's certainly worth a look. I believe it is employed by open source projects such as SubText as well. Perhaps, Jon Galloway can add to this if he reads this question. Or Phil if he is currently a user.
What is the easiest-to-use web "rich text editor" I am looking for a text editor to be used in a web page. Where users can format the text and get a WYSIWYG experience. Doesn't need to be too fancy. But has to be easy to use and integrate into the page. Has to generate HTML as output. Support AJAX (one I checked works only with standard form submit) and has to be small in terms of download to the user's browser.
TITLE: What is the easiest-to-use web "rich text editor" QUESTION: I am looking for a text editor to be used in a web page. Where users can format the text and get a WYSIWYG experience. Doesn't need to be too fancy. But has to be easy to use and integrate into the page. Has to generate HTML as output. Support AJAX (one I checked works only with standard form submit) and has to be small in terms of download to the user's browser. ANSWER: Well it depends what platform you are on if you are looking for server-side functionality as well, but the defacto badass WYSIWYg in my opinion is FCKeditor. I have worked with this personally in numerous environments (both professional and hobby level) and have always been impressed. It's certainly worth a look. I believe it is employed by open source projects such as SubText as well. Perhaps, Jon Galloway can add to this if he reads this question. Or Phil if he is currently a user.
[ "html", "editor" ]
14
11
1,750
9
0
2008-08-21T21:52:17.820000
2008-08-21T21:55:59.607000
21,280
21,292
Am I missing something about LINQ?
I seem to be missing something about LINQ. To me, it looks like it's taking some of the elements of SQL that I like the least and moving them into the C# language and using them for other things. I mean, I could see the benefit of using SQL-like statements on things other than databases. But if I wanted to write SQL, well, why not just write SQL and keep it out of C#? What am I missing here?
LINQ is not about SQL. LINQ is about being apply functional programming paradigmns on objects. LINQ to SQL is an ORM built ontop of the LINQ foundation, but LINQ is much more. I don't use LINQ to SQL, yet I use LINQ all the time. Take the task of finding the intersection of two lists: Before LINQ, this tasks requires writing a nested foreach that iterates the small list once for every item in the big list O(N*M), and takes about 10 lines of code. foreach (int number in list1) { foreach (int number2 in list2) { if (number2 == number) { returnList.add(number2); } } } Using LINQ, it does the same thing in one line of code: var results = list1.Intersect(list2); You'll notice that doesn't look like LINQ, yet it is. You don't need to use the expression syntax if you don't want to.
Am I missing something about LINQ? I seem to be missing something about LINQ. To me, it looks like it's taking some of the elements of SQL that I like the least and moving them into the C# language and using them for other things. I mean, I could see the benefit of using SQL-like statements on things other than databases. But if I wanted to write SQL, well, why not just write SQL and keep it out of C#? What am I missing here?
TITLE: Am I missing something about LINQ? QUESTION: I seem to be missing something about LINQ. To me, it looks like it's taking some of the elements of SQL that I like the least and moving them into the C# language and using them for other things. I mean, I could see the benefit of using SQL-like statements on things other than databases. But if I wanted to write SQL, well, why not just write SQL and keep it out of C#? What am I missing here? ANSWER: LINQ is not about SQL. LINQ is about being apply functional programming paradigmns on objects. LINQ to SQL is an ORM built ontop of the LINQ foundation, but LINQ is much more. I don't use LINQ to SQL, yet I use LINQ all the time. Take the task of finding the intersection of two lists: Before LINQ, this tasks requires writing a nested foreach that iterates the small list once for every item in the big list O(N*M), and takes about 10 lines of code. foreach (int number in list1) { foreach (int number2 in list2) { if (number2 == number) { returnList.add(number2); } } } Using LINQ, it does the same thing in one line of code: var results = list1.Intersect(list2); You'll notice that doesn't look like LINQ, yet it is. You don't need to use the expression syntax if you don't want to.
[ "c#", "sql", "linq" ]
20
40
1,916
6
0
2008-08-21T21:54:56.317000
2008-08-21T21:59:00.457000
21,288
21,348
Which .NET Dependency Injection frameworks are worth looking into?
Which C#/.NET Dependency Injection frameworks are worth looking into? And what can you say about their complexity and speed.
edit (not by the author): There is a comprehensive list of IoC frameworks available at https://github.com/quozd/awesome-dotnet/blob/master/README.md#ioc: Castle Windsor - Castle Windsor is best of breed, mature Inversion of Control container available for.NET and Silverlight Unity - Lightweight extensible dependency injection container with support for constructor, property, and method call injection Autofac - An addictive.NET IoC container DryIoc - Simple, fast all fully featured IoC container. Ninject - The ninja of.NET dependency injectors Spring.Net - Spring.NET is an open source application framework that makes building enterprise.NET applications easier Lamar - A fast IoC container heavily optimized for usage within ASP.NET Core and other.NET server side applications. LightInject - A ultra lightweight IoC container Simple Injector - Simple Injector is an easy-to-use Dependency Injection (DI) library for.NET 4+ that supports Silverlight 4+, Windows Phone 8, Windows 8 including Universal apps and Mono. Microsoft.Extensions.DependencyInjection - The default IoC container for ASP.NET Core applications. Scrutor - Assembly scanning extensions for Microsoft.Extensions.DependencyInjection. VS MEF - Managed Extensibility Framework (MEF) implementation used by Visual Studio. TinyIoC - An easy to use, hassle free, Inversion of Control Container for small projects, libraries and beginners alike. Stashbox - A lightweight, fast and portable dependency injection framework for.NET based solutions. Original answer follows. I suppose I might be being a bit picky here but it's important to note that DI (Dependency Injection) is a programming pattern and is facilitated by, but does not require, an IoC (Inversion of Control) framework. IoC frameworks just make DI much easier and they provide a host of other benefits over and above DI. That being said, I'm sure that's what you were asking. About IoC Frameworks; I used to use Spring.Net and CastleWindsor a lot, but the real pain in the behind was all that pesky XML config you had to write! They're pretty much all moving this way now, so I have been using StructureMap for the last year or so, and since it has moved to a fluent config using strongly typed generics and a registry, my pain barrier in using IoC has dropped to below zero! I get an absolute kick out of knowing now that my IoC config is checked at compile-time (for the most part) and I have had nothing but joy with StructureMap and its speed. I won't say that the others were slow at runtime, but they were more difficult for me to setup and frustration often won the day. Update I've been using Ninject on my latest project and it has been an absolute pleasure to use. Words fail me a bit here, but (as we say in the UK) this framework is 'the Dogs'. I would highly recommend it for any green fields projects where you want to be up and running quickly. I got all I needed from a fantastic set of Ninject screencasts by Justin Etheredge. I can't see that retro-fitting Ninject into existing code being a problem at all, but then the same could be said of StructureMap in my experience. It'll be a tough choice going forward between those two, but I'd rather have competition than stagnation and there's a decent amount of healthy competition out there. Other IoC screencasts can also be found here on Dimecasts.
Which .NET Dependency Injection frameworks are worth looking into? Which C#/.NET Dependency Injection frameworks are worth looking into? And what can you say about their complexity and speed.
TITLE: Which .NET Dependency Injection frameworks are worth looking into? QUESTION: Which C#/.NET Dependency Injection frameworks are worth looking into? And what can you say about their complexity and speed. ANSWER: edit (not by the author): There is a comprehensive list of IoC frameworks available at https://github.com/quozd/awesome-dotnet/blob/master/README.md#ioc: Castle Windsor - Castle Windsor is best of breed, mature Inversion of Control container available for.NET and Silverlight Unity - Lightweight extensible dependency injection container with support for constructor, property, and method call injection Autofac - An addictive.NET IoC container DryIoc - Simple, fast all fully featured IoC container. Ninject - The ninja of.NET dependency injectors Spring.Net - Spring.NET is an open source application framework that makes building enterprise.NET applications easier Lamar - A fast IoC container heavily optimized for usage within ASP.NET Core and other.NET server side applications. LightInject - A ultra lightweight IoC container Simple Injector - Simple Injector is an easy-to-use Dependency Injection (DI) library for.NET 4+ that supports Silverlight 4+, Windows Phone 8, Windows 8 including Universal apps and Mono. Microsoft.Extensions.DependencyInjection - The default IoC container for ASP.NET Core applications. Scrutor - Assembly scanning extensions for Microsoft.Extensions.DependencyInjection. VS MEF - Managed Extensibility Framework (MEF) implementation used by Visual Studio. TinyIoC - An easy to use, hassle free, Inversion of Control Container for small projects, libraries and beginners alike. Stashbox - A lightweight, fast and portable dependency injection framework for.NET based solutions. Original answer follows. I suppose I might be being a bit picky here but it's important to note that DI (Dependency Injection) is a programming pattern and is facilitated by, but does not require, an IoC (Inversion of Control) framework. IoC frameworks just make DI much easier and they provide a host of other benefits over and above DI. That being said, I'm sure that's what you were asking. About IoC Frameworks; I used to use Spring.Net and CastleWindsor a lot, but the real pain in the behind was all that pesky XML config you had to write! They're pretty much all moving this way now, so I have been using StructureMap for the last year or so, and since it has moved to a fluent config using strongly typed generics and a registry, my pain barrier in using IoC has dropped to below zero! I get an absolute kick out of knowing now that my IoC config is checked at compile-time (for the most part) and I have had nothing but joy with StructureMap and its speed. I won't say that the others were slow at runtime, but they were more difficult for me to setup and frustration often won the day. Update I've been using Ninject on my latest project and it has been an absolute pleasure to use. Words fail me a bit here, but (as we say in the UK) this framework is 'the Dogs'. I would highly recommend it for any green fields projects where you want to be up and running quickly. I got all I needed from a fantastic set of Ninject screencasts by Justin Etheredge. I can't see that retro-fitting Ninject into existing code being a problem at all, but then the same could be said of StructureMap in my experience. It'll be a tough choice going forward between those two, but I'd rather have competition than stagnation and there's a decent amount of healthy competition out there. Other IoC screencasts can also be found here on Dimecasts.
[ "c#", ".net", "dependency-injection", "inversion-of-control" ]
405
359
178,925
12
0
2008-08-21T21:56:23.210000
2008-08-21T22:29:16
21,294
242,607
Dynamically load a JavaScript file
How can you reliably and dynamically load a JavaScript file? This will can be used to implement a module or component that when 'initialized' the component will dynamically load all needed JavaScript library scripts on demand. The client that uses the component isn't required to load all the library script files (and manually insert
You may create a script element dynamically, using Prototypes: new Element("script", {src: "myBigCodeLibrary.js", type: "text/javascript"}); The problem here is that we do not know when the external script file is fully loaded. We often want our dependant code on the very next line and like to write something like: if (iNeedSomeMore) { Script.load("myBigCodeLibrary.js"); // includes code for myFancyMethod(); myFancyMethod(); // cool, no need for callbacks! } There is a smart way to inject script dependencies without the need of callbacks. You simply have to pull the script via a synchronous AJAX request and eval the script on global level. If you use Prototype the Script.load method looks like this: var Script = { _loadedScripts: [], include: function(script) { // include script only once if (this._loadedScripts.include(script)) { return false; } // request file synchronous var code = new Ajax.Request(script, { asynchronous: false, method: "GET", evalJS: false, evalJSON: false }).transport.responseText; // eval code on global level if (Prototype.Browser.IE) { window.execScript(code); } else if (Prototype.Browser.WebKit) { $$("head").first().insert(Object.extend( new Element("script", { type: "text/javascript" }), { text: code } )); } else { window.eval(code); } // remember included script this._loadedScripts.push(script); } };
Dynamically load a JavaScript file How can you reliably and dynamically load a JavaScript file? This will can be used to implement a module or component that when 'initialized' the component will dynamically load all needed JavaScript library scripts on demand. The client that uses the component isn't required to load all the library script files (and manually insert
TITLE: Dynamically load a JavaScript file QUESTION: How can you reliably and dynamically load a JavaScript file? This will can be used to implement a module or component that when 'initialized' the component will dynamically load all needed JavaScript library scripts on demand. The client that uses the component isn't required to load all the library script files (and manually insert ANSWER: You may create a script element dynamically, using Prototypes: new Element("script", {src: "myBigCodeLibrary.js", type: "text/javascript"}); The problem here is that we do not know when the external script file is fully loaded. We often want our dependant code on the very next line and like to write something like: if (iNeedSomeMore) { Script.load("myBigCodeLibrary.js"); // includes code for myFancyMethod(); myFancyMethod(); // cool, no need for callbacks! } There is a smart way to inject script dependencies without the need of callbacks. You simply have to pull the script via a synchronous AJAX request and eval the script on global level. If you use Prototype the Script.load method looks like this: var Script = { _loadedScripts: [], include: function(script) { // include script only once if (this._loadedScripts.include(script)) { return false; } // request file synchronous var code = new Ajax.Request(script, { asynchronous: false, method: "GET", evalJS: false, evalJSON: false }).transport.responseText; // eval code on global level if (Prototype.Browser.IE) { window.execScript(code); } else if (Prototype.Browser.WebKit) { $$("head").first().insert(Object.extend( new Element("script", { type: "text/javascript" }), { text: code } )); } else { window.eval(code); } // remember included script this._loadedScripts.push(script); } };
[ "javascript", "file", "import", "include" ]
195
89
220,811
29
0
2008-08-21T21:59:31.080000
2008-10-28T09:02:37.437000
21,303
21,322
In C++ can constructor and destructor be inline functions?
VC++ makes functions which are implemented within the class declaration inline functions. If I declare a class Foo as follows, then are the CONSTRUCTOR and DESTRUCTOR inline functions? class Foo { int* p; public: Foo() { p = new char[0x00100000]; } ~Foo() { delete [] p; } }; { Foo f; (f); }
Defining the body of the constructor INSIDE the class has the same effect as placing the function OUTSIDE the class with the "inline" keyword. In both cases it's a hint to the compiler. An "inline" function doesn't necessarily mean the function will be inlined. That depends on the complexity of the function and other rules.
In C++ can constructor and destructor be inline functions? VC++ makes functions which are implemented within the class declaration inline functions. If I declare a class Foo as follows, then are the CONSTRUCTOR and DESTRUCTOR inline functions? class Foo { int* p; public: Foo() { p = new char[0x00100000]; } ~Foo() { delete [] p; } }; { Foo f; (f); }
TITLE: In C++ can constructor and destructor be inline functions? QUESTION: VC++ makes functions which are implemented within the class declaration inline functions. If I declare a class Foo as follows, then are the CONSTRUCTOR and DESTRUCTOR inline functions? class Foo { int* p; public: Foo() { p = new char[0x00100000]; } ~Foo() { delete [] p; } }; { Foo f; (f); } ANSWER: Defining the body of the constructor INSIDE the class has the same effect as placing the function OUTSIDE the class with the "inline" keyword. In both cases it's a hint to the compiler. An "inline" function doesn't necessarily mean the function will be inlined. That depends on the complexity of the function and other rules.
[ "c++", "constructor", "destructor" ]
87
92
101,689
5
0
2008-08-21T22:02:58.310000
2008-08-21T22:10:59.647000
21,353
21,366
Batch file to "Script" a Database
Is it possible to somehow use a.bat file to script the schema and/or content of a SQL Server database? I can do this via the wizard, but would like to streamline the creation of this file for source control purposes. I would like to avoid the use of 3rd party tools, just limiting myself to the tools that come with SQL Server.
There is a free tool called SubCommander that is a part of the open source SubSonic software. I have successfully used this tool myself to create both schema and data "dumps" each night. You can script out your schema and data (and then version it in your favorite source control system) using SubCommander. Simply use the command "version" and tell SubCommander where to put the data: sonic.exe version /out Scripts This will output a script file (.sql) to the local scripts directory of your project You can also try using the Microsoft SQL Server Database Publishing wizard, although i am not sure that you can use it in a bat file.
Batch file to "Script" a Database Is it possible to somehow use a.bat file to script the schema and/or content of a SQL Server database? I can do this via the wizard, but would like to streamline the creation of this file for source control purposes. I would like to avoid the use of 3rd party tools, just limiting myself to the tools that come with SQL Server.
TITLE: Batch file to "Script" a Database QUESTION: Is it possible to somehow use a.bat file to script the schema and/or content of a SQL Server database? I can do this via the wizard, but would like to streamline the creation of this file for source control purposes. I would like to avoid the use of 3rd party tools, just limiting myself to the tools that come with SQL Server. ANSWER: There is a free tool called SubCommander that is a part of the open source SubSonic software. I have successfully used this tool myself to create both schema and data "dumps" each night. You can script out your schema and data (and then version it in your favorite source control system) using SubCommander. Simply use the command "version" and tell SubCommander where to put the data: sonic.exe version /out Scripts This will output a script file (.sql) to the local scripts directory of your project You can also try using the Microsoft SQL Server Database Publishing wizard, although i am not sure that you can use it in a bat file.
[ "sql-server", "batch-file", "command-line", "scripting", "batch-processing" ]
4
6
1,754
1
0
2008-08-21T22:36:15.750000
2008-08-21T22:45:02.903000
21,355
21,637
Mocking and IQueryable<T>
I've ran into a problem while trying to test following IRepository based on NHibernate: public class NHibernateRepository: Disposable, IRepository where T: IdentifiableObject {... public IQueryable Query() { return NHibernateSession.Linq (); } } How on the Hell to mock returning IQueryable out in the way that it returns given collection in exchange certain expression. I feel I have some misunderstanding of IQueryable...
In Moq it would be: mockRepository.Expect( r => r.Query() ).Returns( myEnumerable.AsQueriable() ); In RhinoMocks it would be: Expect.Call( repository.Query() ).Return( myEnumerable.AsQueriable() );
Mocking and IQueryable<T> I've ran into a problem while trying to test following IRepository based on NHibernate: public class NHibernateRepository: Disposable, IRepository where T: IdentifiableObject {... public IQueryable Query() { return NHibernateSession.Linq (); } } How on the Hell to mock returning IQueryable out in the way that it returns given collection in exchange certain expression. I feel I have some misunderstanding of IQueryable...
TITLE: Mocking and IQueryable<T> QUESTION: I've ran into a problem while trying to test following IRepository based on NHibernate: public class NHibernateRepository: Disposable, IRepository where T: IdentifiableObject {... public IQueryable Query() { return NHibernateSession.Linq (); } } How on the Hell to mock returning IQueryable out in the way that it returns given collection in exchange certain expression. I feel I have some misunderstanding of IQueryable... ANSWER: In Moq it would be: mockRepository.Expect( r => r.Query() ).Returns( myEnumerable.AsQueriable() ); In RhinoMocks it would be: Expect.Call( repository.Query() ).Return( myEnumerable.AsQueriable() );
[ "linq" ]
4
7
603
1
0
2008-08-21T22:38:06.137000
2008-08-22T02:15:07.127000
21,388
694,735
Represent Ordering in a Relational Database
I have a collection of objects in a database. Images in a photo gallery, products in a catalog, chapters in a book, etc. Each object is represented as a row. I want to be able to arbitrarily order these images, storing that ordering in the database so when I display the objects, they will be in the right order. For example, let's say I'm writing a book, and each chapter is an object. I write my book, and put the chapters in the following order: Introduction, Accessibility, Form vs. Function, Errors, Consistency, Conclusion, Index It goes to the editor, and comes back with the following suggested order: Introduction, Form, Function, Accessibility, Consistency, Errors, Conclusion, Index How can I store this ordering in the database in a robust, efficient way? I've had the following ideas, but I'm not thrilled with any of them: Array. Each row has an ordering ID, when order is changed (via a removal followed by an insertion), the order IDs are updated. This makes retrieval easy, since it's just ORDER BY, but it seems easy to break. // REMOVAL UPDATE... SET orderingID=NULL WHERE orderingID=removedID UPDATE... SET orderingID=orderingID-1 WHERE orderingID > removedID // INSERTION UPDATE... SET orderingID=orderingID+1 WHERE orderingID > insertionID UPDATE... SET orderID=insertionID WHERE ID=addedID Linked list. Each row has a column for the id of the next row in the ordering. Traversal seems costly here, though there may by some way to use ORDER BY that I'm not thinking of. Spaced array. Set the orderingID (as used in #1) to be large, so the first object is 100, the second is 200, etc. Then when an insertion happens, you just place it at (objectBefore + objectAfter)/2. Of course, this would need to be rebalanced occasionally, so you don't have things too close together (even with floats, you'd eventually run into rounding errors). None of these seem particularly elegant to me. Does anyone have a better way to do it?
Since I've mostly run into this with Django, I've found this solution to be the most workable. It seems that there isn't any "right way" to do this in a relational database.
Represent Ordering in a Relational Database I have a collection of objects in a database. Images in a photo gallery, products in a catalog, chapters in a book, etc. Each object is represented as a row. I want to be able to arbitrarily order these images, storing that ordering in the database so when I display the objects, they will be in the right order. For example, let's say I'm writing a book, and each chapter is an object. I write my book, and put the chapters in the following order: Introduction, Accessibility, Form vs. Function, Errors, Consistency, Conclusion, Index It goes to the editor, and comes back with the following suggested order: Introduction, Form, Function, Accessibility, Consistency, Errors, Conclusion, Index How can I store this ordering in the database in a robust, efficient way? I've had the following ideas, but I'm not thrilled with any of them: Array. Each row has an ordering ID, when order is changed (via a removal followed by an insertion), the order IDs are updated. This makes retrieval easy, since it's just ORDER BY, but it seems easy to break. // REMOVAL UPDATE... SET orderingID=NULL WHERE orderingID=removedID UPDATE... SET orderingID=orderingID-1 WHERE orderingID > removedID // INSERTION UPDATE... SET orderingID=orderingID+1 WHERE orderingID > insertionID UPDATE... SET orderID=insertionID WHERE ID=addedID Linked list. Each row has a column for the id of the next row in the ordering. Traversal seems costly here, though there may by some way to use ORDER BY that I'm not thinking of. Spaced array. Set the orderingID (as used in #1) to be large, so the first object is 100, the second is 200, etc. Then when an insertion happens, you just place it at (objectBefore + objectAfter)/2. Of course, this would need to be rebalanced occasionally, so you don't have things too close together (even with floats, you'd eventually run into rounding errors). None of these seem particularly elegant to me. Does anyone have a better way to do it?
TITLE: Represent Ordering in a Relational Database QUESTION: I have a collection of objects in a database. Images in a photo gallery, products in a catalog, chapters in a book, etc. Each object is represented as a row. I want to be able to arbitrarily order these images, storing that ordering in the database so when I display the objects, they will be in the right order. For example, let's say I'm writing a book, and each chapter is an object. I write my book, and put the chapters in the following order: Introduction, Accessibility, Form vs. Function, Errors, Consistency, Conclusion, Index It goes to the editor, and comes back with the following suggested order: Introduction, Form, Function, Accessibility, Consistency, Errors, Conclusion, Index How can I store this ordering in the database in a robust, efficient way? I've had the following ideas, but I'm not thrilled with any of them: Array. Each row has an ordering ID, when order is changed (via a removal followed by an insertion), the order IDs are updated. This makes retrieval easy, since it's just ORDER BY, but it seems easy to break. // REMOVAL UPDATE... SET orderingID=NULL WHERE orderingID=removedID UPDATE... SET orderingID=orderingID-1 WHERE orderingID > removedID // INSERTION UPDATE... SET orderingID=orderingID+1 WHERE orderingID > insertionID UPDATE... SET orderID=insertionID WHERE ID=addedID Linked list. Each row has a column for the id of the next row in the ordering. Traversal seems costly here, though there may by some way to use ORDER BY that I'm not thinking of. Spaced array. Set the orderingID (as used in #1) to be large, so the first object is 100, the second is 200, etc. Then when an insertion happens, you just place it at (objectBefore + objectAfter)/2. Of course, this would need to be rebalanced occasionally, so you don't have things too close together (even with floats, you'd eventually run into rounding errors). None of these seem particularly elegant to me. Does anyone have a better way to do it? ANSWER: Since I've mostly run into this with Django, I've found this solution to be the most workable. It seems that there isn't any "right way" to do this in a relational database.
[ "sql", "database", "django", "django-models" ]
36
2
5,963
11
0
2008-08-21T23:01:30.400000
2009-03-29T14:47:15.043000
21,404
511,006
Source Control in Visual Studio Isolated Shell
I am developing an Isolated Shell that caters to " designers/special content creators " performing specific tasks, using the Shell. As they operate on files, they need to be able to use TFS for source control. This is mainly due to the fact that Developers will also operate on the same files from TFS but using Visual studio 2008. After looking and searching I still could not find Team Explorer to be available to Shell. Asking on MSDN forums, lead me to the answer that "this is not supported yet in the Isolated Shell". Well, then the whole point of giving away a shell is not justified, if you want to use a source control system for your files. The idea is not to recreate everything and develop tool windows etc using the TFS provider API. The Visual Studio Extensibility book by Keyven Nayyeri has an example, which only goes so far into this problem of adding a sc provider. Has anyone worked on developing Visual Studio 2008 Isolated Shell applications/environment? Please provide comments, questions - anything that you have to share apart from the following threads, which I've already participated in. Threads from MSDN forums: Team Explorer for Isolated Shell Is it possible to use Team Explorer in VS Shell Isolated? Thanks for your answer. Yes you are right, we will acquire CALs for users without having to buy them Visual Studio, that's the direction we will be taking. But I am yet to figure out how to make Team Explorer available to such users, inside Shell. So I am looking to find out the technical details of how that can be done. I mean, I have a user, he installs my VS Shell application, he has no VStudio Team system on his machine. Now if I acquire CAL for TFS and install Team Explorer, do you think it will be automatically available in the VS Shell app? Any ideas? have you worked on making this happen? Thanks
Just stumbled on this question, it might still be relevant to you. You have the option of including the AnkhSVN ( http://ankhsvn.open.collab.net/ ) packages and load it into your Isolated Shell. While there are some issues around it, with Subversion support, you could use SvnBridge to access TFS repositories. This might bring you a little bit closer to the process you are trying to achieve.
Source Control in Visual Studio Isolated Shell I am developing an Isolated Shell that caters to " designers/special content creators " performing specific tasks, using the Shell. As they operate on files, they need to be able to use TFS for source control. This is mainly due to the fact that Developers will also operate on the same files from TFS but using Visual studio 2008. After looking and searching I still could not find Team Explorer to be available to Shell. Asking on MSDN forums, lead me to the answer that "this is not supported yet in the Isolated Shell". Well, then the whole point of giving away a shell is not justified, if you want to use a source control system for your files. The idea is not to recreate everything and develop tool windows etc using the TFS provider API. The Visual Studio Extensibility book by Keyven Nayyeri has an example, which only goes so far into this problem of adding a sc provider. Has anyone worked on developing Visual Studio 2008 Isolated Shell applications/environment? Please provide comments, questions - anything that you have to share apart from the following threads, which I've already participated in. Threads from MSDN forums: Team Explorer for Isolated Shell Is it possible to use Team Explorer in VS Shell Isolated? Thanks for your answer. Yes you are right, we will acquire CALs for users without having to buy them Visual Studio, that's the direction we will be taking. But I am yet to figure out how to make Team Explorer available to such users, inside Shell. So I am looking to find out the technical details of how that can be done. I mean, I have a user, he installs my VS Shell application, he has no VStudio Team system on his machine. Now if I acquire CAL for TFS and install Team Explorer, do you think it will be automatically available in the VS Shell app? Any ideas? have you worked on making this happen? Thanks
TITLE: Source Control in Visual Studio Isolated Shell QUESTION: I am developing an Isolated Shell that caters to " designers/special content creators " performing specific tasks, using the Shell. As they operate on files, they need to be able to use TFS for source control. This is mainly due to the fact that Developers will also operate on the same files from TFS but using Visual studio 2008. After looking and searching I still could not find Team Explorer to be available to Shell. Asking on MSDN forums, lead me to the answer that "this is not supported yet in the Isolated Shell". Well, then the whole point of giving away a shell is not justified, if you want to use a source control system for your files. The idea is not to recreate everything and develop tool windows etc using the TFS provider API. The Visual Studio Extensibility book by Keyven Nayyeri has an example, which only goes so far into this problem of adding a sc provider. Has anyone worked on developing Visual Studio 2008 Isolated Shell applications/environment? Please provide comments, questions - anything that you have to share apart from the following threads, which I've already participated in. Threads from MSDN forums: Team Explorer for Isolated Shell Is it possible to use Team Explorer in VS Shell Isolated? Thanks for your answer. Yes you are right, we will acquire CALs for users without having to buy them Visual Studio, that's the direction we will be taking. But I am yet to figure out how to make Team Explorer available to such users, inside Shell. So I am looking to find out the technical details of how that can be done. I mean, I have a user, he installs my VS Shell application, he has no VStudio Team system on his machine. Now if I acquire CAL for TFS and install Team Explorer, do you think it will be automatically available in the VS Shell app? Any ideas? have you worked on making this happen? Thanks ANSWER: Just stumbled on this question, it might still be relevant to you. You have the option of including the AnkhSVN ( http://ankhsvn.open.collab.net/ ) packages and load it into your Isolated Shell. While there are some issues around it, with Subversion support, you could use SvnBridge to access TFS repositories. This might bring you a little bit closer to the process you are trying to achieve.
[ "visual-studio", "vsx", "extensibility" ]
1
1
2,095
2
0
2008-08-21T23:13:05.007000
2009-02-04T11:46:45.737000
21,437
21,440
Preventing a visitor from saving an image from my site
What are some effective strategies for preventing the use of my proprietary images? I'm talking about saving them, direct linking to them etc... Presently I have a watermark on the image, but I'd rather not..NET platform preferred, but if there's a strategy that's on another platform that integrates with my existing application that'd be a bonus.
It's not possible to make it "impossible" to download. When a user visits your site you're sending them the pictures. The user will have a copy of that image in the browsers cache and he'd be able to access it even after he leaves the site ( depending on the browser, of course ). Your only real option is to watermark them:O
Preventing a visitor from saving an image from my site What are some effective strategies for preventing the use of my proprietary images? I'm talking about saving them, direct linking to them etc... Presently I have a watermark on the image, but I'd rather not..NET platform preferred, but if there's a strategy that's on another platform that integrates with my existing application that'd be a bonus.
TITLE: Preventing a visitor from saving an image from my site QUESTION: What are some effective strategies for preventing the use of my proprietary images? I'm talking about saving them, direct linking to them etc... Presently I have a watermark on the image, but I'd rather not..NET platform preferred, but if there's a strategy that's on another platform that integrates with my existing application that'd be a bonus. ANSWER: It's not possible to make it "impossible" to download. When a user visits your site you're sending them the pictures. The user will have a copy of that image in the browsers cache and he'd be able to access it even after he leaves the site ( depending on the browser, of course ). Your only real option is to watermark them:O
[ "image" ]
4
30
2,001
15
0
2008-08-21T23:36:14.577000
2008-08-21T23:38:43.463000
21,461
21,479
What Predefined #if symbos does c# have?
#if SYMBOL //code #endif what values does C# predefine for use?
To add to what Nick said, the MSDN documentation does not list any pre-defined names. It would seem that all need to come from #define and /define. #if on MSDN
What Predefined #if symbos does c# have? #if SYMBOL //code #endif what values does C# predefine for use?
TITLE: What Predefined #if symbos does c# have? QUESTION: #if SYMBOL //code #endif what values does C# predefine for use? ANSWER: To add to what Nick said, the MSDN documentation does not list any pre-defined names. It would seem that all need to come from #define and /define. #if on MSDN
[ "c#" ]
9
4
888
3
0
2008-08-21T23:51:23.777000
2008-08-22T00:06:12.337000
21,464
21,494
Recommended iPhone Development Resources
This is my first post here and I wanted to get some input from people doing iPhone development. Other than the Apple DevCenter, where are there good sites to learn iPhone developement? I know Apple has a tough NDA but there has to be people talking about writing applications for the iPhone.
This site covers some of the basics with little regard for the NDA. Start at the bottom and work up.
Recommended iPhone Development Resources This is my first post here and I wanted to get some input from people doing iPhone development. Other than the Apple DevCenter, where are there good sites to learn iPhone developement? I know Apple has a tough NDA but there has to be people talking about writing applications for the iPhone.
TITLE: Recommended iPhone Development Resources QUESTION: This is my first post here and I wanted to get some input from people doing iPhone development. Other than the Apple DevCenter, where are there good sites to learn iPhone developement? I know Apple has a tough NDA but there has to be people talking about writing applications for the iPhone. ANSWER: This site covers some of the basics with little regard for the NDA. Start at the bottom and work up.
[ "ios" ]
8
2
1,670
7
0
2008-08-21T23:53:36.797000
2008-08-22T00:16:32.577000
21,489
21,545
Grouping runs of data
SQL Experts, Is there an efficient way to group runs of data together using SQL? Or is it going to be more efficient to process the data in code. For example if I have the following data: ID|Name 01|Harry Johns 02|Adam Taylor 03|John Smith 04|John Smith 05|Bill Manning 06|John Smith I need to display this: Harry Johns Adam Taylor John Smith (2) Bill Manning John Smith @Matt: Sorry I had trouble formatting the data using an embedded html table it worked in the preview but not in the final display.
Try this: select n.name, (select count(*) from myTable n1 where n1.name = n.name and n1.id >= n.id and (n1.id <= ( select isnull(min(nn.id), (select max(id) + 1 from myTable)) from myTable nn where nn.id > n.id and nn.name <> n.name ) )) from myTable n where not exists ( select 1 from myTable n3 where n3.name = n.name and n3.id < n.id and n3.id > ( select isnull(max(n4.id), (select min(id) - 1 from myTable)) from myTable n4 where n4.id < n.id and n4.name <> n.name ) ) I think that'll do what you want. Bit of a kludge though. Phew! After a few edits I think I have all the edge cases sorted out.
Grouping runs of data SQL Experts, Is there an efficient way to group runs of data together using SQL? Or is it going to be more efficient to process the data in code. For example if I have the following data: ID|Name 01|Harry Johns 02|Adam Taylor 03|John Smith 04|John Smith 05|Bill Manning 06|John Smith I need to display this: Harry Johns Adam Taylor John Smith (2) Bill Manning John Smith @Matt: Sorry I had trouble formatting the data using an embedded html table it worked in the preview but not in the final display.
TITLE: Grouping runs of data QUESTION: SQL Experts, Is there an efficient way to group runs of data together using SQL? Or is it going to be more efficient to process the data in code. For example if I have the following data: ID|Name 01|Harry Johns 02|Adam Taylor 03|John Smith 04|John Smith 05|Bill Manning 06|John Smith I need to display this: Harry Johns Adam Taylor John Smith (2) Bill Manning John Smith @Matt: Sorry I had trouble formatting the data using an embedded html table it worked in the preview but not in the final display. ANSWER: Try this: select n.name, (select count(*) from myTable n1 where n1.name = n.name and n1.id >= n.id and (n1.id <= ( select isnull(min(nn.id), (select max(id) + 1 from myTable)) from myTable nn where nn.id > n.id and nn.name <> n.name ) )) from myTable n where not exists ( select 1 from myTable n3 where n3.name = n.name and n3.id < n.id and n3.id > ( select isnull(max(n4.id), (select min(id) - 1 from myTable)) from myTable n4 where n4.id < n.id and n4.name <> n.name ) ) I think that'll do what you want. Bit of a kludge though. Phew! After a few edits I think I have all the edge cases sorted out.
[ "sql" ]
7
2
280
6
0
2008-08-22T00:13:06
2008-08-22T00:57:08.157000
21,514
21,546
Enumerate Windows user group members on remote system using c#
Within c#, I need to be able to Connect to a remote system, specifying username/password as appropriate List the members of a localgroup on that system Fetch the results back to the executing computer So for example I would connect to \SOMESYSTEM with appropriate creds, and fetch back a list of local administrators including SOMESYSTEM\Administrator, SOMESYSTEM\Bob, DOMAIN\AlanH, "DOMAIN\Domain Administrators". I've tried this with system.directoryservices.accountmanagement but am running into problems with authentication. Sometimes I get: Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed. Disconnect all previous connections to the server or shared resource and try again. (Exception from HRESULT: 0x800704C3) The above is trying because there will be situations where I simply cannot unmap existing drives or UNC connections. Other times my program gets UNKNOWN ERROR and the security log on the remote system reports an error 675, code 0x19 which is KDC_ERR_PREAUTH_REQUIRED. I need a simpler and less error prone way to do this!
This should be easy to do using WMI. Here you have a pointer to some docs: WMI Documentation for Win32_UserAccount Even if you have no previous experience with WMI, it should be quite easy to turn that VB Script code at the bottom of the page into some.NET code. Hope this helped!
Enumerate Windows user group members on remote system using c# Within c#, I need to be able to Connect to a remote system, specifying username/password as appropriate List the members of a localgroup on that system Fetch the results back to the executing computer So for example I would connect to \SOMESYSTEM with appropriate creds, and fetch back a list of local administrators including SOMESYSTEM\Administrator, SOMESYSTEM\Bob, DOMAIN\AlanH, "DOMAIN\Domain Administrators". I've tried this with system.directoryservices.accountmanagement but am running into problems with authentication. Sometimes I get: Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed. Disconnect all previous connections to the server or shared resource and try again. (Exception from HRESULT: 0x800704C3) The above is trying because there will be situations where I simply cannot unmap existing drives or UNC connections. Other times my program gets UNKNOWN ERROR and the security log on the remote system reports an error 675, code 0x19 which is KDC_ERR_PREAUTH_REQUIRED. I need a simpler and less error prone way to do this!
TITLE: Enumerate Windows user group members on remote system using c# QUESTION: Within c#, I need to be able to Connect to a remote system, specifying username/password as appropriate List the members of a localgroup on that system Fetch the results back to the executing computer So for example I would connect to \SOMESYSTEM with appropriate creds, and fetch back a list of local administrators including SOMESYSTEM\Administrator, SOMESYSTEM\Bob, DOMAIN\AlanH, "DOMAIN\Domain Administrators". I've tried this with system.directoryservices.accountmanagement but am running into problems with authentication. Sometimes I get: Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed. Disconnect all previous connections to the server or shared resource and try again. (Exception from HRESULT: 0x800704C3) The above is trying because there will be situations where I simply cannot unmap existing drives or UNC connections. Other times my program gets UNKNOWN ERROR and the security log on the remote system reports an error 675, code 0x19 which is KDC_ERR_PREAUTH_REQUIRED. I need a simpler and less error prone way to do this! ANSWER: This should be easy to do using WMI. Here you have a pointer to some docs: WMI Documentation for Win32_UserAccount Even if you have no previous experience with WMI, it should be quite easy to turn that VB Script code at the bottom of the page into some.NET code. Hope this helped!
[ "c#", "windows", "user-management", "usergroups" ]
7
1
24,909
5
0
2008-08-22T00:29:05.837000
2008-08-22T00:57:21.463000
21,547
317,864
In SQL Server, how do I generate a CREATE TABLE statement for a given table?
I've spent a good amount of time coming up with solution to this problem, so in the spirit of this post, I'm posting it here, since I think it might be useful to others. If anyone has a better script, or anything to add, please post it. Edit: Yes guys, I know how to do it in Management Studio - but I needed to be able to do it from within another application.
I've modified the version above to run for all tables and support new SQL 2005 data types. It also retains the primary key names. Works only on SQL 2005 (using cross apply). select 'create table [' + so.name + '] (' + o.list + ')' + CASE WHEN tc.Constraint_Name IS NULL THEN '' ELSE 'ALTER TABLE ' + so.Name + ' ADD CONSTRAINT ' + tc.Constraint_Name + ' PRIMARY KEY ' + ' (' + LEFT(j.List, Len(j.List)-1) + ')' END from sysobjects so cross apply (SELECT ' ['+column_name+'] ' + data_type + case data_type when 'sql_variant' then '' when 'text' then '' when 'ntext' then '' when 'xml' then '' when 'decimal' then '(' + cast(numeric_precision as varchar) + ', ' + cast(numeric_scale as varchar) + ')' else coalesce('('+case when character_maximum_length = -1 then 'MAX' else cast(character_maximum_length as varchar) end +')','') end + ' ' + case when exists ( select id from syscolumns where object_name(id)=so.name and name=column_name and columnproperty(id,name,'IsIdentity') = 1 ) then 'IDENTITY(' + cast(ident_seed(so.name) as varchar) + ',' + cast(ident_incr(so.name) as varchar) + ')' else '' end + ' ' + (case when UPPER(IS_NULLABLE) = 'NO' then 'NOT ' else '' end ) + 'NULL ' + case when information_schema.columns.COLUMN_DEFAULT IS NOT NULL THEN 'DEFAULT '+ information_schema.columns.COLUMN_DEFAULT ELSE '' END + ', ' from information_schema.columns where table_name = so.name order by ordinal_position FOR XML PATH('')) o (list) left join information_schema.table_constraints tc on tc.Table_name = so.Name AND tc.Constraint_Type = 'PRIMARY KEY' cross apply (select '[' + Column_Name + '], ' FROM information_schema.key_column_usage kcu WHERE kcu.Constraint_Name = tc.Constraint_Name ORDER BY ORDINAL_POSITION FOR XML PATH('')) j (list) where xtype = 'U' AND name NOT IN ('dtproperties') Update: Added handling of the XML data type Update 2: Fixed cases when 1) there is multiple tables with the same name but with different schemas, 2) there is multiple tables having PK constraint with the same name
In SQL Server, how do I generate a CREATE TABLE statement for a given table? I've spent a good amount of time coming up with solution to this problem, so in the spirit of this post, I'm posting it here, since I think it might be useful to others. If anyone has a better script, or anything to add, please post it. Edit: Yes guys, I know how to do it in Management Studio - but I needed to be able to do it from within another application.
TITLE: In SQL Server, how do I generate a CREATE TABLE statement for a given table? QUESTION: I've spent a good amount of time coming up with solution to this problem, so in the spirit of this post, I'm posting it here, since I think it might be useful to others. If anyone has a better script, or anything to add, please post it. Edit: Yes guys, I know how to do it in Management Studio - but I needed to be able to do it from within another application. ANSWER: I've modified the version above to run for all tables and support new SQL 2005 data types. It also retains the primary key names. Works only on SQL 2005 (using cross apply). select 'create table [' + so.name + '] (' + o.list + ')' + CASE WHEN tc.Constraint_Name IS NULL THEN '' ELSE 'ALTER TABLE ' + so.Name + ' ADD CONSTRAINT ' + tc.Constraint_Name + ' PRIMARY KEY ' + ' (' + LEFT(j.List, Len(j.List)-1) + ')' END from sysobjects so cross apply (SELECT ' ['+column_name+'] ' + data_type + case data_type when 'sql_variant' then '' when 'text' then '' when 'ntext' then '' when 'xml' then '' when 'decimal' then '(' + cast(numeric_precision as varchar) + ', ' + cast(numeric_scale as varchar) + ')' else coalesce('('+case when character_maximum_length = -1 then 'MAX' else cast(character_maximum_length as varchar) end +')','') end + ' ' + case when exists ( select id from syscolumns where object_name(id)=so.name and name=column_name and columnproperty(id,name,'IsIdentity') = 1 ) then 'IDENTITY(' + cast(ident_seed(so.name) as varchar) + ',' + cast(ident_incr(so.name) as varchar) + ')' else '' end + ' ' + (case when UPPER(IS_NULLABLE) = 'NO' then 'NOT ' else '' end ) + 'NULL ' + case when information_schema.columns.COLUMN_DEFAULT IS NOT NULL THEN 'DEFAULT '+ information_schema.columns.COLUMN_DEFAULT ELSE '' END + ', ' from information_schema.columns where table_name = so.name order by ordinal_position FOR XML PATH('')) o (list) left join information_schema.table_constraints tc on tc.Table_name = so.Name AND tc.Constraint_Type = 'PRIMARY KEY' cross apply (select '[' + Column_Name + '], ' FROM information_schema.key_column_usage kcu WHERE kcu.Constraint_Name = tc.Constraint_Name ORDER BY ORDINAL_POSITION FOR XML PATH('')) j (list) where xtype = 'U' AND name NOT IN ('dtproperties') Update: Added handling of the XML data type Update 2: Fixed cases when 1) there is multiple tables with the same name but with different schemas, 2) there is multiple tables having PK constraint with the same name
[ "sql-server", "scripting", "dynamic-sql" ]
88
119
130,726
16
0
2008-08-22T00:58:55.173000
2008-11-25T16:04:33.443000
21,558
21,607
In C++, what is a virtual base class?
I want to know what a " virtual base class " is and what it means. Let me show an example: class Foo { public: void DoSomething() { /*... */ } }; class Bar: public virtual Foo { public: void DoSpecific() { /*... */ } };
Virtual base classes, used in virtual inheritance, is a way of preventing multiple "instances" of a given class appearing in an inheritance hierarchy when using multiple inheritance. Consider the following scenario: class A { public: void Foo() {} }; class B: public A {}; class C: public A {}; class D: public B, public C {}; The above class hierarchy results in the "dreaded diamond" which looks like this: A / \ B C \ / D An instance of D will be made up of B, which includes A, and C which also includes A. So you have two "instances" (for want of a better expression) of A. When you have this scenario, you have the possibility of ambiguity. What happens when you do this: D d; d.Foo(); // is this B's Foo() or C's Foo()?? Virtual inheritance is there to solve this problem. When you specify virtual when inheriting your classes, you're telling the compiler that you only want a single instance. class A { public: void Foo() {} }; class B: public virtual A {}; class C: public virtual A {}; class D: public B, public C {}; This means that there is only one "instance" of A included in the hierarchy. Hence D d; d.Foo(); // no longer ambiguous This is a mini summary. For more information, have a read of this and this. A good example is also available here.
In C++, what is a virtual base class? I want to know what a " virtual base class " is and what it means. Let me show an example: class Foo { public: void DoSomething() { /*... */ } }; class Bar: public virtual Foo { public: void DoSpecific() { /*... */ } };
TITLE: In C++, what is a virtual base class? QUESTION: I want to know what a " virtual base class " is and what it means. Let me show an example: class Foo { public: void DoSomething() { /*... */ } }; class Bar: public virtual Foo { public: void DoSpecific() { /*... */ } }; ANSWER: Virtual base classes, used in virtual inheritance, is a way of preventing multiple "instances" of a given class appearing in an inheritance hierarchy when using multiple inheritance. Consider the following scenario: class A { public: void Foo() {} }; class B: public A {}; class C: public A {}; class D: public B, public C {}; The above class hierarchy results in the "dreaded diamond" which looks like this: A / \ B C \ / D An instance of D will be made up of B, which includes A, and C which also includes A. So you have two "instances" (for want of a better expression) of A. When you have this scenario, you have the possibility of ambiguity. What happens when you do this: D d; d.Foo(); // is this B's Foo() or C's Foo()?? Virtual inheritance is there to solve this problem. When you specify virtual when inheriting your classes, you're telling the compiler that you only want a single instance. class A { public: void Foo() {} }; class B: public virtual A {}; class C: public virtual A {}; class D: public B, public C {}; This means that there is only one "instance" of A included in the hierarchy. Hence D d; d.Foo(); // no longer ambiguous This is a mini summary. For more information, have a read of this and this. A good example is also available here.
[ "c++", "virtual-inheritance" ]
473
590
357,684
11
0
2008-08-22T01:13:15.357000
2008-08-22T01:45:02.770000