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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
32,338 | 32,670 | Are there similar tools to Clone Detective for other languages/IDEs? | I just saw Clone Detective linked on YCombinator news, and the idea heavily appeals to me. It seems like it would be useful for many languages, not just C#, but I haven't seen anything similar elsewhere. Edit: For those who don't want to follow the link, Clone Detective scans the codebase for duplicate code that may warrant refactoring to minimize duplication. | Java has a few - some of the most popular static analysis tools have this built in along with many other useful rules. Ones I have used, in the (purely subjective) order that I was happiest with: PMD - comes with CPD - their copy and paste detector Checkstyle - specific rules to look for duplicate code Findbugs - the daddy of all Java static analysis tools. Includes duplicate code detection, along with just about anything else that you can think of, but quite resource intensive There are some nice IDE plugins for all of these and many other reporting tools (for example, you can see results on a Hudson continuos build server, or your project's Maven site ) | Are there similar tools to Clone Detective for other languages/IDEs? I just saw Clone Detective linked on YCombinator news, and the idea heavily appeals to me. It seems like it would be useful for many languages, not just C#, but I haven't seen anything similar elsewhere. Edit: For those who don't want to follow the link, Clone Detective scans the codebase for duplicate code that may warrant refactoring to minimize duplication. | TITLE:
Are there similar tools to Clone Detective for other languages/IDEs?
QUESTION:
I just saw Clone Detective linked on YCombinator news, and the idea heavily appeals to me. It seems like it would be useful for many languages, not just C#, but I haven't seen anything similar elsewhere. Edit: For those who don't want to follow the link, Clone Detective scans the codebase for duplicate code that may warrant refactoring to minimize duplication.
ANSWER:
Java has a few - some of the most popular static analysis tools have this built in along with many other useful rules. Ones I have used, in the (purely subjective) order that I was happiest with: PMD - comes with CPD - their copy and paste detector Checkstyle - specific rules to look for duplicate code Findbugs - the daddy of all Java static analysis tools. Includes duplicate code detection, along with just about anything else that you can think of, but quite resource intensive There are some nice IDE plugins for all of these and many other reporting tools (for example, you can see results on a Hudson continuos build server, or your project's Maven site ) | [
"c#",
"language-agnostic"
] | 4 | 2 | 264 | 2 | 0 | 2008-08-28T14:09:25.880000 | 2008-08-28T16:06:28.360000 |
32,343 | 32,348 | How do I spawn threads on different CPU cores? | Let's say I had a program in C# that did something computationally expensive, like encoding a list of WAV files into MP3s. Ordinarily I would encode the files one at a time, but let's say I wanted the program to figure out how many CPU cores I had and spin up an encoding thread on each core. So, when I run the program on a quad core CPU, the program figures out it's a quad core CPU, figures out there are four cores to work with, then spawns four threads for the encoding, each of which is running on its own separate CPU. How would I do this? And would this be any different if the cores were spread out across multiple physical CPUs? As in, if I had a machine with two quad core CPUs on it, are there any special considerations or are the eight cores across the two dies considered equal in Windows? | Don't bother doing that. Instead use the Thread Pool. The thread pool is a mechanism (actually a class) of the framework that you can query for a new thread. When you ask for a new thread it will either give you a new one or enqueue the work until a thread get freed. In that way the framework is in charge on deciding wether it should create more threads or not depending on the number of present CPUs. Edit: In addition, as it has been already mentioned, the OS is in charge of distributing the threads among the different CPUs. | How do I spawn threads on different CPU cores? Let's say I had a program in C# that did something computationally expensive, like encoding a list of WAV files into MP3s. Ordinarily I would encode the files one at a time, but let's say I wanted the program to figure out how many CPU cores I had and spin up an encoding thread on each core. So, when I run the program on a quad core CPU, the program figures out it's a quad core CPU, figures out there are four cores to work with, then spawns four threads for the encoding, each of which is running on its own separate CPU. How would I do this? And would this be any different if the cores were spread out across multiple physical CPUs? As in, if I had a machine with two quad core CPUs on it, are there any special considerations or are the eight cores across the two dies considered equal in Windows? | TITLE:
How do I spawn threads on different CPU cores?
QUESTION:
Let's say I had a program in C# that did something computationally expensive, like encoding a list of WAV files into MP3s. Ordinarily I would encode the files one at a time, but let's say I wanted the program to figure out how many CPU cores I had and spin up an encoding thread on each core. So, when I run the program on a quad core CPU, the program figures out it's a quad core CPU, figures out there are four cores to work with, then spawns four threads for the encoding, each of which is running on its own separate CPU. How would I do this? And would this be any different if the cores were spread out across multiple physical CPUs? As in, if I had a machine with two quad core CPUs on it, are there any special considerations or are the eight cores across the two dies considered equal in Windows?
ANSWER:
Don't bother doing that. Instead use the Thread Pool. The thread pool is a mechanism (actually a class) of the framework that you can query for a new thread. When you ask for a new thread it will either give you a new one or enqueue the work until a thread get freed. In that way the framework is in charge on deciding wether it should create more threads or not depending on the number of present CPUs. Edit: In addition, as it has been already mentioned, the OS is in charge of distributing the threads among the different CPUs. | [
"c#",
".net",
"windows",
"multithreading"
] | 69 | 65 | 68,729 | 10 | 0 | 2008-08-28T14:11:20.523000 | 2008-08-28T14:13:41.920000 |
32,360 | 32,394 | 1:1 Foreign Key Constraints | How do you specify that a foreign key constraint should be a 1:1 relationship in transact sql? Is declaring the column UNIQUE enough? Below is my existing code.! CREATE TABLE [dbo].MyTable( [MyTablekey] INT IDENTITY(1,1) NOT FOR REPLICATION NOT NULL, [OtherTableKey] INT NOT NULL UNIQUE CONSTRAINT [FK_MyTable_OtherTable] FOREIGN KEY REFERENCES [dbo].[OtherTable]([OtherTableKey]),... CONSTRAINT [PK_MyTable] PRIMARY KEY CLUSTERED ( [MyTableKey] ASC ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO | A foreign key column with the UNIQUE and NOT NULL constraints that references a UNIQUE, NOT NULL column in another table creates a 1:(0|1) relationship, which is probably what you want. If there was a true 1:1 relationship, every record in the first table would have a corresponding record in the second table and vice-versa. In that case, you would probably just want to make one table (unless you needed some strange storage optimization). | 1:1 Foreign Key Constraints How do you specify that a foreign key constraint should be a 1:1 relationship in transact sql? Is declaring the column UNIQUE enough? Below is my existing code.! CREATE TABLE [dbo].MyTable( [MyTablekey] INT IDENTITY(1,1) NOT FOR REPLICATION NOT NULL, [OtherTableKey] INT NOT NULL UNIQUE CONSTRAINT [FK_MyTable_OtherTable] FOREIGN KEY REFERENCES [dbo].[OtherTable]([OtherTableKey]),... CONSTRAINT [PK_MyTable] PRIMARY KEY CLUSTERED ( [MyTableKey] ASC ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO | TITLE:
1:1 Foreign Key Constraints
QUESTION:
How do you specify that a foreign key constraint should be a 1:1 relationship in transact sql? Is declaring the column UNIQUE enough? Below is my existing code.! CREATE TABLE [dbo].MyTable( [MyTablekey] INT IDENTITY(1,1) NOT FOR REPLICATION NOT NULL, [OtherTableKey] INT NOT NULL UNIQUE CONSTRAINT [FK_MyTable_OtherTable] FOREIGN KEY REFERENCES [dbo].[OtherTable]([OtherTableKey]),... CONSTRAINT [PK_MyTable] PRIMARY KEY CLUSTERED ( [MyTableKey] ASC ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO
ANSWER:
A foreign key column with the UNIQUE and NOT NULL constraints that references a UNIQUE, NOT NULL column in another table creates a 1:(0|1) relationship, which is probably what you want. If there was a true 1:1 relationship, every record in the first table would have a corresponding record in the second table and vice-versa. In that case, you would probably just want to make one table (unless you needed some strange storage optimization). | [
"sql",
"sql-server"
] | 9 | 9 | 9,870 | 5 | 0 | 2008-08-28T14:16:15.520000 | 2008-08-28T14:24:12.113000 |
32,364 | 32,466 | Assert action redirected to correct action/route? | How do I exercise an action to ensure it redirects to the correct action or route? | public ActionResult Foo() { return RedirectToAction("Products", "Index"); }
[Test] public void foo_redirects_to_products_index() { var controller = new BarController(); var result = controller.Foo() as RedirectToRouteResult;
if(result == null) Assert.Fail("should have redirected");
Assert.That(result.RouteData.Values["Controller"], Is.EqualTo("Products")); Assert.That(result.RouteData.Values["Action"], Is.EqualTo("Index"));
} | Assert action redirected to correct action/route? How do I exercise an action to ensure it redirects to the correct action or route? | TITLE:
Assert action redirected to correct action/route?
QUESTION:
How do I exercise an action to ensure it redirects to the correct action or route?
ANSWER:
public ActionResult Foo() { return RedirectToAction("Products", "Index"); }
[Test] public void foo_redirects_to_products_index() { var controller = new BarController(); var result = controller.Foo() as RedirectToRouteResult;
if(result == null) Assert.Fail("should have redirected");
Assert.That(result.RouteData.Values["Controller"], Is.EqualTo("Products")); Assert.That(result.RouteData.Values["Action"], Is.EqualTo("Index"));
} | [
"asp.net-mvc",
"unit-testing"
] | 6 | 10 | 1,242 | 1 | 0 | 2008-08-28T14:17:11.477000 | 2008-08-28T14:47:08.113000 |
32,366 | 32,392 | What are the key considerations when creating a web crawler? | I just started thinking about creating/customizing a web crawler today, and know very little about web crawler/robot etiquette. A majority of the writings on etiquette I've found seem old and awkward, so I'd like to get some current (and practical) insights from the web developer community. I want to use a crawler to walk over "the web" for a super simple purpose - "does the markup of site XYZ meet condition ABC?". This raises a lot of questions for me, but I think the two main questions I need to get out of the way first are: It feels a little "iffy" from the get go -- is this sort of thing acceptable? What specific considerations should the crawler take to not upset people? | Obey robots.txt (and not too aggressive like has been said already). You might want to think about your user-agent string - they're a good place to be up-front about what you're doing and how you can be contacted. | What are the key considerations when creating a web crawler? I just started thinking about creating/customizing a web crawler today, and know very little about web crawler/robot etiquette. A majority of the writings on etiquette I've found seem old and awkward, so I'd like to get some current (and practical) insights from the web developer community. I want to use a crawler to walk over "the web" for a super simple purpose - "does the markup of site XYZ meet condition ABC?". This raises a lot of questions for me, but I think the two main questions I need to get out of the way first are: It feels a little "iffy" from the get go -- is this sort of thing acceptable? What specific considerations should the crawler take to not upset people? | TITLE:
What are the key considerations when creating a web crawler?
QUESTION:
I just started thinking about creating/customizing a web crawler today, and know very little about web crawler/robot etiquette. A majority of the writings on etiquette I've found seem old and awkward, so I'd like to get some current (and practical) insights from the web developer community. I want to use a crawler to walk over "the web" for a super simple purpose - "does the markup of site XYZ meet condition ABC?". This raises a lot of questions for me, but I think the two main questions I need to get out of the way first are: It feels a little "iffy" from the get go -- is this sort of thing acceptable? What specific considerations should the crawler take to not upset people?
ANSWER:
Obey robots.txt (and not too aggressive like has been said already). You might want to think about your user-agent string - they're a good place to be up-front about what you're doing and how you can be contacted. | [
"web-crawler"
] | 11 | 9 | 3,241 | 9 | 0 | 2008-08-28T14:17:35.780000 | 2008-08-28T14:24:01.757000 |
32,369 | 32,386 | Disable browser 'Save Password' functionality | One of the joys of working for a government healthcare agency is having to deal with all of the paranoia around dealing with PHI (Protected Health Information). Don't get me wrong, I'm all for doing everything possible to protect people's personal information (health, financial, surfing habits, etc.), but sometimes people get a little too jumpy. Case in point: One of our state customers recently found out that the browser provides the handy feature to save your password. We all know that it has been there for a while and is completely optional and is up to the end user to decide whether or not it is a smart decision to use or not. However, there is a bit of an uproar at the moment and we are being demanded to find a way to disable that functionality for our site. Question: Is there a way for a site to tell the browser not to offer to remember passwords? I've been around web development a long time but don't know that I have come across that before. Any help is appreciated. | I'm not sure if it'll work in all browsers but you should try setting autocomplete="off" on the form. The easiest and simplest way to disable Form and Password storage prompts and prevent form data from being cached in session history is to use the autocomplete form element attribute with value "off". From https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion Some minor research shows that this works in IE to but I'll leave no guarantees;) @Joseph: If it's a strict requirement to pass XHTML validation with the actual markup (don't know why it would be though) you could theoretically add this attribute with javascript afterwards but then users with js disabled (probably a neglectable amount of your userbase or zero if your site requires js) will still have their passwords saved. Example with jQuery: $('#loginForm').attr('autocomplete', 'off'); | Disable browser 'Save Password' functionality One of the joys of working for a government healthcare agency is having to deal with all of the paranoia around dealing with PHI (Protected Health Information). Don't get me wrong, I'm all for doing everything possible to protect people's personal information (health, financial, surfing habits, etc.), but sometimes people get a little too jumpy. Case in point: One of our state customers recently found out that the browser provides the handy feature to save your password. We all know that it has been there for a while and is completely optional and is up to the end user to decide whether or not it is a smart decision to use or not. However, there is a bit of an uproar at the moment and we are being demanded to find a way to disable that functionality for our site. Question: Is there a way for a site to tell the browser not to offer to remember passwords? I've been around web development a long time but don't know that I have come across that before. Any help is appreciated. | TITLE:
Disable browser 'Save Password' functionality
QUESTION:
One of the joys of working for a government healthcare agency is having to deal with all of the paranoia around dealing with PHI (Protected Health Information). Don't get me wrong, I'm all for doing everything possible to protect people's personal information (health, financial, surfing habits, etc.), but sometimes people get a little too jumpy. Case in point: One of our state customers recently found out that the browser provides the handy feature to save your password. We all know that it has been there for a while and is completely optional and is up to the end user to decide whether or not it is a smart decision to use or not. However, there is a bit of an uproar at the moment and we are being demanded to find a way to disable that functionality for our site. Question: Is there a way for a site to tell the browser not to offer to remember passwords? I've been around web development a long time but don't know that I have come across that before. Any help is appreciated.
ANSWER:
I'm not sure if it'll work in all browsers but you should try setting autocomplete="off" on the form. The easiest and simplest way to disable Form and Password storage prompts and prevent form data from being cached in session history is to use the autocomplete form element attribute with value "off". From https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion Some minor research shows that this works in IE to but I'll leave no guarantees;) @Joseph: If it's a strict requirement to pass XHTML validation with the actual markup (don't know why it would be though) you could theoretically add this attribute with javascript afterwards but then users with js disabled (probably a neglectable amount of your userbase or zero if your site requires js) will still have their passwords saved. Example with jQuery: $('#loginForm').attr('autocomplete', 'off'); | [
"security",
"browser",
"autocomplete",
"passwords"
] | 464 | 339 | 330,592 | 36 | 0 | 2008-08-28T14:18:09.150000 | 2008-08-28T14:23:22.913000 |
32,385 | 32,402 | Programmatically editing Python source | This is something that I think would be very useful. Basically, I'd like there to be a way to edit Python source programmatically without requiring human intervention. There are a couple of things I would like to do with this: Edit the configuration of Python apps that use source modules for configuration. Set up a "template" so that I can customize a Python source file on the fly. This way, I can set up a "project" system on an open source app I'm working on and allow certain files to be customized. I could probably write something that can do this myself, but I can see that opening up a lot of "devil's in the details" type issues. Are there any ways to do this currently, or am I just going to have to bite the bullet and implement it myself? | Python's standard library provides pretty good facilities for working with Python source; note the tokenize and parser modules. | Programmatically editing Python source This is something that I think would be very useful. Basically, I'd like there to be a way to edit Python source programmatically without requiring human intervention. There are a couple of things I would like to do with this: Edit the configuration of Python apps that use source modules for configuration. Set up a "template" so that I can customize a Python source file on the fly. This way, I can set up a "project" system on an open source app I'm working on and allow certain files to be customized. I could probably write something that can do this myself, but I can see that opening up a lot of "devil's in the details" type issues. Are there any ways to do this currently, or am I just going to have to bite the bullet and implement it myself? | TITLE:
Programmatically editing Python source
QUESTION:
This is something that I think would be very useful. Basically, I'd like there to be a way to edit Python source programmatically without requiring human intervention. There are a couple of things I would like to do with this: Edit the configuration of Python apps that use source modules for configuration. Set up a "template" so that I can customize a Python source file on the fly. This way, I can set up a "project" system on an open source app I'm working on and allow certain files to be customized. I could probably write something that can do this myself, but I can see that opening up a lot of "devil's in the details" type issues. Are there any ways to do this currently, or am I just going to have to bite the bullet and implement it myself?
ANSWER:
Python's standard library provides pretty good facilities for working with Python source; note the tokenize and parser modules. | [
"python",
"file-io"
] | 12 | 7 | 2,683 | 3 | 0 | 2008-08-28T14:23:00.247000 | 2008-08-28T14:27:37.410000 |
32,397 | 32,399 | Popularity algorithm | On SO 18 Joel mentioned an algorithm that would rank items based on their age and popularity and it's based on gravity. Could someone post this? C# would be lovely, but really any language (well, I can't do LISP) would be fine. | My understanding is that it is approximately the following from another Jeff Atwood post t = (time of entry post) - (Dec 8, 2005) x = upvotes - downvotes
y = {1 if x > 0, 0 if x = 0, -1 if x < 0) z = {1 if x < 1, otherwise x}
log(z) + (y * t)/45000 | Popularity algorithm On SO 18 Joel mentioned an algorithm that would rank items based on their age and popularity and it's based on gravity. Could someone post this? C# would be lovely, but really any language (well, I can't do LISP) would be fine. | TITLE:
Popularity algorithm
QUESTION:
On SO 18 Joel mentioned an algorithm that would rank items based on their age and popularity and it's based on gravity. Could someone post this? C# would be lovely, but really any language (well, I can't do LISP) would be fine.
ANSWER:
My understanding is that it is approximately the following from another Jeff Atwood post t = (time of entry post) - (Dec 8, 2005) x = upvotes - downvotes
y = {1 if x > 0, 0 if x = 0, -1 if x < 0) z = {1 if x < 1, otherwise x}
log(z) + (y * t)/45000 | [
"c#",
"algorithm",
"math"
] | 14 | 11 | 3,941 | 2 | 0 | 2008-08-28T14:24:21.303000 | 2008-08-28T14:26:05.777000 |
32,404 | 32,440 | How do you run a Python script as a service in Windows? | I am sketching the architecture for a set of programs that share various interrelated objects stored in a database. I want one of the programs to act as a service which provides a higher level interface for operations on these objects, and the other programs to access the objects through that service. I am currently aiming for Python and the Django framework as the technologies to implement that service with. I'm pretty sure I figure how to daemonize the Python program in Linux. However, it is an optional spec item that the system should support Windows. I have little experience with Windows programming and no experience at all with Windows services. Is it possible to run a Python programs as a Windows service (i. e. run it automatically without user login)? I won't necessarily have to implement this part, but I need a rough idea how it would be done in order to decide whether to design along these lines. Edit: Thanks for all the answers so far, they are quite comprehensive. I would like to know one more thing: How is Windows aware of my service? Can I manage it with the native Windows utilities? What is the equivalent of putting a start/stop script in /etc/init.d? | Yes you can. I do it using the pythoncom libraries that come included with ActivePython or can be installed with pywin32 (Python for Windows extensions). This is a basic skeleton for a simple service: import win32serviceutil import win32service import win32event import servicemanager import socket
class AppServerSvc (win32serviceutil.ServiceFramework): _svc_name_ = "TestService" _svc_display_name_ = "Test Service"
def __init__(self,args): win32serviceutil.ServiceFramework.__init__(self,args) self.hWaitStop = win32event.CreateEvent(None,0,0,None) socket.setdefaulttimeout(60)
def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self): servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_,'')) self.main()
def main(self): pass
if __name__ == '__main__': win32serviceutil.HandleCommandLine(AppServerSvc) Your code would go in the main() method—usually with some kind of infinite loop that might be interrupted by checking a flag, which you set in the SvcStop method | How do you run a Python script as a service in Windows? I am sketching the architecture for a set of programs that share various interrelated objects stored in a database. I want one of the programs to act as a service which provides a higher level interface for operations on these objects, and the other programs to access the objects through that service. I am currently aiming for Python and the Django framework as the technologies to implement that service with. I'm pretty sure I figure how to daemonize the Python program in Linux. However, it is an optional spec item that the system should support Windows. I have little experience with Windows programming and no experience at all with Windows services. Is it possible to run a Python programs as a Windows service (i. e. run it automatically without user login)? I won't necessarily have to implement this part, but I need a rough idea how it would be done in order to decide whether to design along these lines. Edit: Thanks for all the answers so far, they are quite comprehensive. I would like to know one more thing: How is Windows aware of my service? Can I manage it with the native Windows utilities? What is the equivalent of putting a start/stop script in /etc/init.d? | TITLE:
How do you run a Python script as a service in Windows?
QUESTION:
I am sketching the architecture for a set of programs that share various interrelated objects stored in a database. I want one of the programs to act as a service which provides a higher level interface for operations on these objects, and the other programs to access the objects through that service. I am currently aiming for Python and the Django framework as the technologies to implement that service with. I'm pretty sure I figure how to daemonize the Python program in Linux. However, it is an optional spec item that the system should support Windows. I have little experience with Windows programming and no experience at all with Windows services. Is it possible to run a Python programs as a Windows service (i. e. run it automatically without user login)? I won't necessarily have to implement this part, but I need a rough idea how it would be done in order to decide whether to design along these lines. Edit: Thanks for all the answers so far, they are quite comprehensive. I would like to know one more thing: How is Windows aware of my service? Can I manage it with the native Windows utilities? What is the equivalent of putting a start/stop script in /etc/init.d?
ANSWER:
Yes you can. I do it using the pythoncom libraries that come included with ActivePython or can be installed with pywin32 (Python for Windows extensions). This is a basic skeleton for a simple service: import win32serviceutil import win32service import win32event import servicemanager import socket
class AppServerSvc (win32serviceutil.ServiceFramework): _svc_name_ = "TestService" _svc_display_name_ = "Test Service"
def __init__(self,args): win32serviceutil.ServiceFramework.__init__(self,args) self.hWaitStop = win32event.CreateEvent(None,0,0,None) socket.setdefaulttimeout(60)
def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self): servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_,'')) self.main()
def main(self): pass
if __name__ == '__main__': win32serviceutil.HandleCommandLine(AppServerSvc) Your code would go in the main() method—usually with some kind of infinite loop that might be interrupted by checking a flag, which you set in the SvcStop method | [
"python",
"windows",
"cross-platform"
] | 346 | 301 | 455,082 | 14 | 0 | 2008-08-28T14:28:04.493000 | 2008-08-28T14:39:04.763000 |
32,414 | 32,427 | How can I force clients to refresh JavaScript files? | We are currently working in a private beta and so are still in the process of making fairly rapid changes, although obviously as usage is starting to ramp up, we will be slowing down this process. That being said, one issue we are running into is that after we push out an update with new JavaScript files, the client browsers still use the cached version of the file and they do not see the update. Obviously, on a support call, we can simply inform them to do a ctrl F5 refresh to ensure that they get the up-to-date files from the server, but it would be preferable to handle this before that time. Our current thought is to simply attach a version number onto the name of the JavaScript files and then when changes are made, increment the version on the script and update all references. This definitely gets the job done, but updating the references on each release could get cumbersome. As I'm sure we're not the first ones to deal with this, I figured I would throw it out to the community. How are you ensuring clients update their cache when you update your code? If you're using the method described above, are you using a process that simplifies the change? | As far as I know a common solution is to add a? to the script's src link. For instance: I assume at this point that there isn't a better way than find-replace to increment these "version numbers" in all of the script tags? You might have a version control system do that for you? Most version control systems have a way to automatically inject the revision number on check-in for instance. It would look something like this: Of course, there are always better solutions like this one. | How can I force clients to refresh JavaScript files? We are currently working in a private beta and so are still in the process of making fairly rapid changes, although obviously as usage is starting to ramp up, we will be slowing down this process. That being said, one issue we are running into is that after we push out an update with new JavaScript files, the client browsers still use the cached version of the file and they do not see the update. Obviously, on a support call, we can simply inform them to do a ctrl F5 refresh to ensure that they get the up-to-date files from the server, but it would be preferable to handle this before that time. Our current thought is to simply attach a version number onto the name of the JavaScript files and then when changes are made, increment the version on the script and update all references. This definitely gets the job done, but updating the references on each release could get cumbersome. As I'm sure we're not the first ones to deal with this, I figured I would throw it out to the community. How are you ensuring clients update their cache when you update your code? If you're using the method described above, are you using a process that simplifies the change? | TITLE:
How can I force clients to refresh JavaScript files?
QUESTION:
We are currently working in a private beta and so are still in the process of making fairly rapid changes, although obviously as usage is starting to ramp up, we will be slowing down this process. That being said, one issue we are running into is that after we push out an update with new JavaScript files, the client browsers still use the cached version of the file and they do not see the update. Obviously, on a support call, we can simply inform them to do a ctrl F5 refresh to ensure that they get the up-to-date files from the server, but it would be preferable to handle this before that time. Our current thought is to simply attach a version number onto the name of the JavaScript files and then when changes are made, increment the version on the script and update all references. This definitely gets the job done, but updating the references on each release could get cumbersome. As I'm sure we're not the first ones to deal with this, I figured I would throw it out to the community. How are you ensuring clients update their cache when you update your code? If you're using the method described above, are you using a process that simplifies the change?
ANSWER:
As far as I know a common solution is to add a? to the script's src link. For instance: I assume at this point that there isn't a better way than find-replace to increment these "version numbers" in all of the script tags? You might have a version control system do that for you? Most version control systems have a way to automatically inject the revision number on check-in for instance. It would look something like this: Of course, there are always better solutions like this one. | [
"javascript",
"caching",
"versioning"
] | 711 | 616 | 619,737 | 30 | 0 | 2008-08-28T14:30:26.233000 | 2008-08-28T14:34:12.870000 |
32,428 | 37,379 | How do I resolve a System.Security.SecurityException with custom code in SSRS? | I've created an assembly and referenced it in my Reporting Services report. I've tested the report locally (works), and I then uploaded the report to a report server (doesn't work). Here is the error that is thrown by the custom code I've written. System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed. at System.Security.CodeAccessSecurityEngine.CheckNReturnSO(PermissionToken permToken, CodeAccessPermission demand, StackCrawlMark& stackMark, Int32 unrestrictedOverride, Int32 create) at System.Security.CodeAccessSecurityEngine.Assert(CodeAccessPermission cap, StackCrawlMark& stackMark) at System.Security.CodeAccessPermission.Assert() at [Snipped Method Name] at ReportExprHostImpl.CustomCodeProxy.[Snipped Method Name] The action that failed was: Demand The type of the first permission that failed was: System.Security.Permissions.SecurityPermission The Zone of the assembly that failed was: MyComputer This project is something I inherited, and I'm not intimately familiar with it. Although I do have the code (now), so I can at least work with it:) I believe the code that is failing is this: Dim fio As System.Security.Permissions.FileIOPermission = New System.Security.Permissions.FileIOPermission(Security.Permissions.PermissionState.Unrestricted) fio.Assert() However, this kind of stuff is everywhere too: Private Declare Function CryptHashData Lib "advapi32.dll" (ByVal hhash As Integer, ByVal pbData As String, ByVal dwDataLen As Integer, ByVal dwFlags As Integer) As Integer I can see either of these being things that Reporting Services would not accommodate out of the box. | This is how I was able to solve the issue: strongly sign the custom assembly in question modify the rssrvpolicy.config file to add permissions for the assembly Side note: here is a great way to get the public key blob of your assembly VS trick for obtaining the public key token and blob of a signed assembly. | How do I resolve a System.Security.SecurityException with custom code in SSRS? I've created an assembly and referenced it in my Reporting Services report. I've tested the report locally (works), and I then uploaded the report to a report server (doesn't work). Here is the error that is thrown by the custom code I've written. System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed. at System.Security.CodeAccessSecurityEngine.CheckNReturnSO(PermissionToken permToken, CodeAccessPermission demand, StackCrawlMark& stackMark, Int32 unrestrictedOverride, Int32 create) at System.Security.CodeAccessSecurityEngine.Assert(CodeAccessPermission cap, StackCrawlMark& stackMark) at System.Security.CodeAccessPermission.Assert() at [Snipped Method Name] at ReportExprHostImpl.CustomCodeProxy.[Snipped Method Name] The action that failed was: Demand The type of the first permission that failed was: System.Security.Permissions.SecurityPermission The Zone of the assembly that failed was: MyComputer This project is something I inherited, and I'm not intimately familiar with it. Although I do have the code (now), so I can at least work with it:) I believe the code that is failing is this: Dim fio As System.Security.Permissions.FileIOPermission = New System.Security.Permissions.FileIOPermission(Security.Permissions.PermissionState.Unrestricted) fio.Assert() However, this kind of stuff is everywhere too: Private Declare Function CryptHashData Lib "advapi32.dll" (ByVal hhash As Integer, ByVal pbData As String, ByVal dwDataLen As Integer, ByVal dwFlags As Integer) As Integer I can see either of these being things that Reporting Services would not accommodate out of the box. | TITLE:
How do I resolve a System.Security.SecurityException with custom code in SSRS?
QUESTION:
I've created an assembly and referenced it in my Reporting Services report. I've tested the report locally (works), and I then uploaded the report to a report server (doesn't work). Here is the error that is thrown by the custom code I've written. System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed. at System.Security.CodeAccessSecurityEngine.CheckNReturnSO(PermissionToken permToken, CodeAccessPermission demand, StackCrawlMark& stackMark, Int32 unrestrictedOverride, Int32 create) at System.Security.CodeAccessSecurityEngine.Assert(CodeAccessPermission cap, StackCrawlMark& stackMark) at System.Security.CodeAccessPermission.Assert() at [Snipped Method Name] at ReportExprHostImpl.CustomCodeProxy.[Snipped Method Name] The action that failed was: Demand The type of the first permission that failed was: System.Security.Permissions.SecurityPermission The Zone of the assembly that failed was: MyComputer This project is something I inherited, and I'm not intimately familiar with it. Although I do have the code (now), so I can at least work with it:) I believe the code that is failing is this: Dim fio As System.Security.Permissions.FileIOPermission = New System.Security.Permissions.FileIOPermission(Security.Permissions.PermissionState.Unrestricted) fio.Assert() However, this kind of stuff is everywhere too: Private Declare Function CryptHashData Lib "advapi32.dll" (ByVal hhash As Integer, ByVal pbData As String, ByVal dwDataLen As Integer, ByVal dwFlags As Integer) As Integer I can see either of these being things that Reporting Services would not accommodate out of the box.
ANSWER:
This is how I was able to solve the issue: strongly sign the custom assembly in question modify the rssrvpolicy.config file to add permissions for the assembly Side note: here is a great way to get the public key blob of your assembly VS trick for obtaining the public key token and blob of a signed assembly. | [
"reporting-services",
"securityexception"
] | 13 | 9 | 73,693 | 4 | 0 | 2008-08-28T14:34:26.020000 | 2008-09-01T02:16:49.710000 |
32,433 | 32,465 | Creating a LINQ select from multiple tables | This query works great: var pageObject = (from op in db.ObjectPermissions join pg in db.Pages on op.ObjectPermissionName equals page.PageName where pg.PageID == page.PageID select op).SingleOrDefault(); I get a new type with my 'op' fields. Now I want to retrieve my 'pg' fields as well, but select op, pg).SingleOrDefault(); doesn't work. How can I select everything from both tables so that they appear in my new pageObject type? | You can use anonymous types for this, i.e.: var pageObject = (from op in db.ObjectPermissions join pg in db.Pages on op.ObjectPermissionName equals page.PageName where pg.PageID == page.PageID select new { pg, op }).SingleOrDefault(); This will make pageObject into an IEnumerable of an anonymous type so AFAIK you won't be able to pass it around to other methods, however if you're simply obtaining data to play with in the method you're currently in it's perfectly fine. You can also name properties in your anonymous type, i.e.:- var pageObject = (from op in db.ObjectPermissions join pg in db.Pages on op.ObjectPermissionName equals page.PageName where pg.PageID == page.PageID select new { PermissionName = pg, ObjectPermission = op }).SingleOrDefault(); This will enable you to say:- if (pageObject.PermissionName.FooBar == "golden goose") Application.Exit(); For example:-) | Creating a LINQ select from multiple tables This query works great: var pageObject = (from op in db.ObjectPermissions join pg in db.Pages on op.ObjectPermissionName equals page.PageName where pg.PageID == page.PageID select op).SingleOrDefault(); I get a new type with my 'op' fields. Now I want to retrieve my 'pg' fields as well, but select op, pg).SingleOrDefault(); doesn't work. How can I select everything from both tables so that they appear in my new pageObject type? | TITLE:
Creating a LINQ select from multiple tables
QUESTION:
This query works great: var pageObject = (from op in db.ObjectPermissions join pg in db.Pages on op.ObjectPermissionName equals page.PageName where pg.PageID == page.PageID select op).SingleOrDefault(); I get a new type with my 'op' fields. Now I want to retrieve my 'pg' fields as well, but select op, pg).SingleOrDefault(); doesn't work. How can I select everything from both tables so that they appear in my new pageObject type?
ANSWER:
You can use anonymous types for this, i.e.: var pageObject = (from op in db.ObjectPermissions join pg in db.Pages on op.ObjectPermissionName equals page.PageName where pg.PageID == page.PageID select new { pg, op }).SingleOrDefault(); This will make pageObject into an IEnumerable of an anonymous type so AFAIK you won't be able to pass it around to other methods, however if you're simply obtaining data to play with in the method you're currently in it's perfectly fine. You can also name properties in your anonymous type, i.e.:- var pageObject = (from op in db.ObjectPermissions join pg in db.Pages on op.ObjectPermissionName equals page.PageName where pg.PageID == page.PageID select new { PermissionName = pg, ObjectPermission = op }).SingleOrDefault(); This will enable you to say:- if (pageObject.PermissionName.FooBar == "golden goose") Application.Exit(); For example:-) | [
"c#",
"linq"
] | 54 | 91 | 201,987 | 5 | 0 | 2008-08-28T14:35:50.637000 | 2008-08-28T14:46:40.437000 |
32,448 | 37,293 | Which 4.x version of gcc should one use? | The product-group I work for is currently using gcc 3.4.6 (we know it is ancient) for a large low-level c-code base, and want to upgrade to a later version. We have seen performance benefits testing different versions of gcc 4.x on all hardware platforms we tested it on. We are however very scared of c-compiler bugs (for a good reason historically), and wonder if anyone has insight to which version we should upgrade to. Are people using 4.3.2 for large code-bases and feel that it works fine? | The best quality control for gcc is the linux kernel. GCC is the compiler of choice for basically all major open source C/C++ programs. A released GCC, especially one like 4.3.X, which is in major linux distros, should be pretty good. GCC 4.3 also has better support for optimizations on newer cpus. | Which 4.x version of gcc should one use? The product-group I work for is currently using gcc 3.4.6 (we know it is ancient) for a large low-level c-code base, and want to upgrade to a later version. We have seen performance benefits testing different versions of gcc 4.x on all hardware platforms we tested it on. We are however very scared of c-compiler bugs (for a good reason historically), and wonder if anyone has insight to which version we should upgrade to. Are people using 4.3.2 for large code-bases and feel that it works fine? | TITLE:
Which 4.x version of gcc should one use?
QUESTION:
The product-group I work for is currently using gcc 3.4.6 (we know it is ancient) for a large low-level c-code base, and want to upgrade to a later version. We have seen performance benefits testing different versions of gcc 4.x on all hardware platforms we tested it on. We are however very scared of c-compiler bugs (for a good reason historically), and wonder if anyone has insight to which version we should upgrade to. Are people using 4.3.2 for large code-bases and feel that it works fine?
ANSWER:
The best quality control for gcc is the linux kernel. GCC is the compiler of choice for basically all major open source C/C++ programs. A released GCC, especially one like 4.3.X, which is in major linux distros, should be pretty good. GCC 4.3 also has better support for optimizations on newer cpus. | [
"c",
"gcc"
] | 6 | 4 | 1,741 | 6 | 0 | 2008-08-28T14:41:23.150000 | 2008-09-01T00:10:42.493000 |
32,458 | 32,631 | Random data in Unit Tests? | I have a coworker who writes unit tests for objects which fill their fields with random data. His reason is that it gives a wider range of testing, since it will test a lot of different values, whereas a normal test only uses a single static value. I've given him a number of different reasons against this, the main ones being: random values means the test isn't truly repeatable (which also means that if the test can randomly fail, it can do so on the build server and break the build) if it's a random value and the test fails, we need to a) fix the object and b) force ourselves to test for that value every time, so we know it works, but since it's random we don't know what the value was Another coworker added: If I am testing an exception, random values will not ensure that the test ends up in the expected state random data is used for flushing out a system and load testing, not for unit tests Can anyone else add additional reasons I can give him to get him to stop doing this? (Or alternately, is this an acceptable method of writing unit tests, and I and my other coworker are wrong?) | There's a compromise. Your coworker is actually onto something, but I think he's doing it wrong. I'm not sure that totally random testing is very useful, but it's certainly not invalid. A program (or unit) specification is a hypothesis that there exists some program that meets it. The program itself is then evidence of that hypothesis. What unit testing ought to be is an attempt to provide counter-evidence to refute that the program works according to the spec. Now, you can write the unit tests by hand, but it really is a mechanical task. It can be automated. All you have to do is write the spec, and a machine can generate lots and lots of unit tests that try to break your code. I don't know what language you're using, but see here: Java http://functionaljava.org/ Scala (or Java) http://github.com/rickynils/scalacheck Haskell http://www.cs.chalmers.se/~rjmh/QuickCheck/.NET: http://blogs.msdn.com/dsyme/archive/2008/08/09/fscheck-0-2.aspx These tools will take your well-formed spec as input and automatically generate as many unit tests as you want, with automatically generated data. They use "shrinking" strategies (which you can tweak) to find the simplest possible test case to break your code and to make sure it covers the edge cases well. Happy testing! | Random data in Unit Tests? I have a coworker who writes unit tests for objects which fill their fields with random data. His reason is that it gives a wider range of testing, since it will test a lot of different values, whereas a normal test only uses a single static value. I've given him a number of different reasons against this, the main ones being: random values means the test isn't truly repeatable (which also means that if the test can randomly fail, it can do so on the build server and break the build) if it's a random value and the test fails, we need to a) fix the object and b) force ourselves to test for that value every time, so we know it works, but since it's random we don't know what the value was Another coworker added: If I am testing an exception, random values will not ensure that the test ends up in the expected state random data is used for flushing out a system and load testing, not for unit tests Can anyone else add additional reasons I can give him to get him to stop doing this? (Or alternately, is this an acceptable method of writing unit tests, and I and my other coworker are wrong?) | TITLE:
Random data in Unit Tests?
QUESTION:
I have a coworker who writes unit tests for objects which fill their fields with random data. His reason is that it gives a wider range of testing, since it will test a lot of different values, whereas a normal test only uses a single static value. I've given him a number of different reasons against this, the main ones being: random values means the test isn't truly repeatable (which also means that if the test can randomly fail, it can do so on the build server and break the build) if it's a random value and the test fails, we need to a) fix the object and b) force ourselves to test for that value every time, so we know it works, but since it's random we don't know what the value was Another coworker added: If I am testing an exception, random values will not ensure that the test ends up in the expected state random data is used for flushing out a system and load testing, not for unit tests Can anyone else add additional reasons I can give him to get him to stop doing this? (Or alternately, is this an acceptable method of writing unit tests, and I and my other coworker are wrong?)
ANSWER:
There's a compromise. Your coworker is actually onto something, but I think he's doing it wrong. I'm not sure that totally random testing is very useful, but it's certainly not invalid. A program (or unit) specification is a hypothesis that there exists some program that meets it. The program itself is then evidence of that hypothesis. What unit testing ought to be is an attempt to provide counter-evidence to refute that the program works according to the spec. Now, you can write the unit tests by hand, but it really is a mechanical task. It can be automated. All you have to do is write the spec, and a machine can generate lots and lots of unit tests that try to break your code. I don't know what language you're using, but see here: Java http://functionaljava.org/ Scala (or Java) http://github.com/rickynils/scalacheck Haskell http://www.cs.chalmers.se/~rjmh/QuickCheck/.NET: http://blogs.msdn.com/dsyme/archive/2008/08/09/fscheck-0-2.aspx These tools will take your well-formed spec as input and automatically generate as many unit tests as you want, with automatically generated data. They use "shrinking" strategies (which you can tweak) to find the simplest possible test case to break your code and to make sure it covers the edge cases well. Happy testing! | [
"unit-testing",
"tdd",
"mocking"
] | 185 | 91 | 69,937 | 21 | 0 | 2008-08-28T14:45:26.807000 | 2008-08-28T15:46:31.963000 |
32,462 | 32,522 | Pulling limited tagged photos from Flickr | So I've got a hobby site I'm working on. I've got items that are tagged and I want to associate those items with photos from Flickr. Even with restrictive searches, I might get results numbering in the thousands. Requirements: I want to display between 10-20 pictures but I want to randomize the photos each time. I don't want to hit Flickr every time a page request is made. Not every Flickr photo with the same tags as my item will be relevant. How should I store that number of results and how would I determine which ones are relevant? | I would suggest moving the code that selects, randomizes, downloads and caches photos to separate service. It could be locally accessible REST application. Keep your core code clean and don't clutter it with remote operations and retention policy. Build tags-to-images map and store it locally, in file or database. Randomizing array is easy in both cases. Point image src to local cache. Clean cache periodically, depending on your hosting capacity. Whitelist or blacklist photos to filter them in step 1. | Pulling limited tagged photos from Flickr So I've got a hobby site I'm working on. I've got items that are tagged and I want to associate those items with photos from Flickr. Even with restrictive searches, I might get results numbering in the thousands. Requirements: I want to display between 10-20 pictures but I want to randomize the photos each time. I don't want to hit Flickr every time a page request is made. Not every Flickr photo with the same tags as my item will be relevant. How should I store that number of results and how would I determine which ones are relevant? | TITLE:
Pulling limited tagged photos from Flickr
QUESTION:
So I've got a hobby site I'm working on. I've got items that are tagged and I want to associate those items with photos from Flickr. Even with restrictive searches, I might get results numbering in the thousands. Requirements: I want to display between 10-20 pictures but I want to randomize the photos each time. I don't want to hit Flickr every time a page request is made. Not every Flickr photo with the same tags as my item will be relevant. How should I store that number of results and how would I determine which ones are relevant?
ANSWER:
I would suggest moving the code that selects, randomizes, downloads and caches photos to separate service. It could be locally accessible REST application. Keep your core code clean and don't clutter it with remote operations and retention policy. Build tags-to-images map and store it locally, in file or database. Randomizing array is easy in both cases. Point image src to local cache. Clean cache periodically, depending on your hosting capacity. Whitelist or blacklist photos to filter them in step 1. | [
"php",
"tags",
"flickr"
] | 0 | 1 | 255 | 2 | 0 | 2008-08-28T14:46:04.247000 | 2008-08-28T15:09:08.310000 |
32,493 | 32,543 | Advice on how to be graphically creative | I've always felt that my graphic design skills have lacked, but I do have a desire to improve them. Even though I'm not the worlds worst artist, it's discouraging to see the results from a professional designer, who can do an amazing mockup from a simple spec in just a few hours. I always wonder how they came up with their design and more importantly, how they executed it so quickly. I'd like to think that all good artists aren't naturally gifted. I'm guessing that a lot of skill/talent comes from just putting in the time. Is there a recommended path to right brain nirvana for someone starting from scratch, a little later in life? I'd be interested in book recommendations, personal theories, or anything else that may shed some light on the best path to take. I have questions like should I read books about color theory, should I draw any chance I have, should I analyze shapes like an architect, etc... As far as my current skills go, I can make my way around Photoshop enough where I can do simple image manipulation... Thanks for any advice | Most of artistic talent comes from putting in the time. However, as in most skills, practicing bad habits doesn't help you progress. You need to learn basic drawing skills (form, mainly) and practice doing them well and right (which means slowly). As you practice correctly, you'll improve much faster. This is the kind of thing that changes you from a person who says, "It doesn't look right, but I can't tell why - it's just 'off' somehow" to a person who says, "Oops, the arm is a bit long. If I shorten the elbow end it'll change the piece in this way, if I shorten the hand end it'll change the piece this way..." So you've got to study the forms you intend to draw, and recognize their internally related parts (the body height is generally X times the size of the head, the arms and legs are related in size but vary from the torso, etc). Same thing with buildings, physical objects, etc. Another thing that will really help you is understanding light and shadow - humans pick up on shape relationships based on outlines and based on shadows. Color theory is something that will make your designs attractive, or evoke certain responses and emotions, but until you get the form and lighting right the colors are not something you should stress. One reason why art books and classes focus so much on monochrome drawings. There are books and classes out there for these subjects - I could recommend some, but what you really need is to look at them yourself and pick the ones that appeal to you. You won't want to learn if you don't like drawing fruit bowls, and that's all your book does. Though you shouldn't avoid what you don't like, given that you're going the self taught route you should make it easy in the beginning, and then force yourself to draw the uninteresting and bland once you've got a bit of confidence and speed so you can go through those barriers more quickly. Good luck! -Adam | Advice on how to be graphically creative I've always felt that my graphic design skills have lacked, but I do have a desire to improve them. Even though I'm not the worlds worst artist, it's discouraging to see the results from a professional designer, who can do an amazing mockup from a simple spec in just a few hours. I always wonder how they came up with their design and more importantly, how they executed it so quickly. I'd like to think that all good artists aren't naturally gifted. I'm guessing that a lot of skill/talent comes from just putting in the time. Is there a recommended path to right brain nirvana for someone starting from scratch, a little later in life? I'd be interested in book recommendations, personal theories, or anything else that may shed some light on the best path to take. I have questions like should I read books about color theory, should I draw any chance I have, should I analyze shapes like an architect, etc... As far as my current skills go, I can make my way around Photoshop enough where I can do simple image manipulation... Thanks for any advice | TITLE:
Advice on how to be graphically creative
QUESTION:
I've always felt that my graphic design skills have lacked, but I do have a desire to improve them. Even though I'm not the worlds worst artist, it's discouraging to see the results from a professional designer, who can do an amazing mockup from a simple spec in just a few hours. I always wonder how they came up with their design and more importantly, how they executed it so quickly. I'd like to think that all good artists aren't naturally gifted. I'm guessing that a lot of skill/talent comes from just putting in the time. Is there a recommended path to right brain nirvana for someone starting from scratch, a little later in life? I'd be interested in book recommendations, personal theories, or anything else that may shed some light on the best path to take. I have questions like should I read books about color theory, should I draw any chance I have, should I analyze shapes like an architect, etc... As far as my current skills go, I can make my way around Photoshop enough where I can do simple image manipulation... Thanks for any advice
ANSWER:
Most of artistic talent comes from putting in the time. However, as in most skills, practicing bad habits doesn't help you progress. You need to learn basic drawing skills (form, mainly) and practice doing them well and right (which means slowly). As you practice correctly, you'll improve much faster. This is the kind of thing that changes you from a person who says, "It doesn't look right, but I can't tell why - it's just 'off' somehow" to a person who says, "Oops, the arm is a bit long. If I shorten the elbow end it'll change the piece in this way, if I shorten the hand end it'll change the piece this way..." So you've got to study the forms you intend to draw, and recognize their internally related parts (the body height is generally X times the size of the head, the arms and legs are related in size but vary from the torso, etc). Same thing with buildings, physical objects, etc. Another thing that will really help you is understanding light and shadow - humans pick up on shape relationships based on outlines and based on shadows. Color theory is something that will make your designs attractive, or evoke certain responses and emotions, but until you get the form and lighting right the colors are not something you should stress. One reason why art books and classes focus so much on monochrome drawings. There are books and classes out there for these subjects - I could recommend some, but what you really need is to look at them yourself and pick the ones that appeal to you. You won't want to learn if you don't like drawing fruit bowls, and that's all your book does. Though you shouldn't avoid what you don't like, given that you're going the self taught route you should make it easy in the beginning, and then force yourself to draw the uninteresting and bland once you've got a bit of confidence and speed so you can go through those barriers more quickly. Good luck! -Adam | [
"graphics"
] | 8 | 4 | 962 | 8 | 0 | 2008-08-28T14:56:09.073000 | 2008-08-28T15:14:42.617000 |
32,494 | 42,043 | Visual Studio identical token highlighting | I coded a Mancala game in Java for a college class this past spring, and I used the Eclipse IDE to write it. One of the great (and fairly simple) visual aids in Eclipse is if you select a particular token, say a declared variable, then the IDE will automatically highlight all other references to that token on your screen. Notepad++, my preferred Notepad replacement, also does this. Another neat and similar feature in Eclipse was the vertical "error bar" to the right of your code (not sure what to call it). It display little red boxes for all of the syntax errors in your document, yellow boxes for warnings like "variable declared but not used", and if you select a word, boxes appear in the bar for each occurrence of the word in the document. A screenshot of these features in action: After a half hour of searching, I've determined that Visual Studio cannot do this on its own, so my question is: does anyone know of any add-ins for 2005 or 2008 that can provide either one of the aforementioned features? Being able to highlight the current line your cursor is on would be nice too. I believe the add-in ReSharper can do this, but I'd prefer to use a free add-in rather than purchase one. | In a different question on SO ( link ), someone mentioned the VS 2005 / VS 2008 add-in "RockScroll". It seems to provide the "error bar" feature I was inquiring about in my question above. RockScroll EDIT: RockScroll also does the identical token highlighting that I was looking for! Great! | Visual Studio identical token highlighting I coded a Mancala game in Java for a college class this past spring, and I used the Eclipse IDE to write it. One of the great (and fairly simple) visual aids in Eclipse is if you select a particular token, say a declared variable, then the IDE will automatically highlight all other references to that token on your screen. Notepad++, my preferred Notepad replacement, also does this. Another neat and similar feature in Eclipse was the vertical "error bar" to the right of your code (not sure what to call it). It display little red boxes for all of the syntax errors in your document, yellow boxes for warnings like "variable declared but not used", and if you select a word, boxes appear in the bar for each occurrence of the word in the document. A screenshot of these features in action: After a half hour of searching, I've determined that Visual Studio cannot do this on its own, so my question is: does anyone know of any add-ins for 2005 or 2008 that can provide either one of the aforementioned features? Being able to highlight the current line your cursor is on would be nice too. I believe the add-in ReSharper can do this, but I'd prefer to use a free add-in rather than purchase one. | TITLE:
Visual Studio identical token highlighting
QUESTION:
I coded a Mancala game in Java for a college class this past spring, and I used the Eclipse IDE to write it. One of the great (and fairly simple) visual aids in Eclipse is if you select a particular token, say a declared variable, then the IDE will automatically highlight all other references to that token on your screen. Notepad++, my preferred Notepad replacement, also does this. Another neat and similar feature in Eclipse was the vertical "error bar" to the right of your code (not sure what to call it). It display little red boxes for all of the syntax errors in your document, yellow boxes for warnings like "variable declared but not used", and if you select a word, boxes appear in the bar for each occurrence of the word in the document. A screenshot of these features in action: After a half hour of searching, I've determined that Visual Studio cannot do this on its own, so my question is: does anyone know of any add-ins for 2005 or 2008 that can provide either one of the aforementioned features? Being able to highlight the current line your cursor is on would be nice too. I believe the add-in ReSharper can do this, but I'd prefer to use a free add-in rather than purchase one.
ANSWER:
In a different question on SO ( link ), someone mentioned the VS 2005 / VS 2008 add-in "RockScroll". It seems to provide the "error bar" feature I was inquiring about in my question above. RockScroll EDIT: RockScroll also does the identical token highlighting that I was looking for! Great! | [
"visual-studio",
"visual-studio-2008",
"visual-studio-2005"
] | 68 | 11 | 37,229 | 11 | 0 | 2008-08-28T14:56:55.810000 | 2008-09-03T16:17:47.787000 |
32,513 | 32,794 | Write files to App_Data under medium trust hack? | Is there any way to Write files to App_Data under medium trust hack? Im sure I've heard about some hack, is that true? | I don't have access to the server itself, so I can't check that. I can only chmod files and folder from my FTP client. I think my hosting provider needs to grant write permission to the network service account on the App_Data folder. | Write files to App_Data under medium trust hack? Is there any way to Write files to App_Data under medium trust hack? Im sure I've heard about some hack, is that true? | TITLE:
Write files to App_Data under medium trust hack?
QUESTION:
Is there any way to Write files to App_Data under medium trust hack? Im sure I've heard about some hack, is that true?
ANSWER:
I don't have access to the server itself, so I can't check that. I can only chmod files and folder from my FTP client. I think my hosting provider needs to grant write permission to the network service account on the App_Data folder. | [
"asp.net",
"trust"
] | 1 | 0 | 960 | 2 | 0 | 2008-08-28T15:05:28.177000 | 2008-08-28T16:54:08.043000 |
32,519 | 32,707 | List in JScrollPane painting outside the viewport | I have a list, each item of which has several things in it, including a JProgressBar which can be updated a lot. Each time one of the items updates its JProgressBar, the ListDataListener on the list tries to scroll it to the visible range using /* * This makes the updating content item automatically scroll * into view if it is off the viewport. */ public void contentsChanged(final ListDataEvent evt) { if (!EventQueue.isDispatchThread()) { /** * Make sure the scrolling happens in the graphics "dispatch" thread. */ EventQueue.invokeLater(new Runnable() { public void run() { contentsChanged(evt); } }); } if (playbackInProgress) { int index = evt.getIndex0(); currentContentList.ensureIndexIsVisible(index); } } Note that I'm trying to make sure the scrolling is done in the dispatch thread, since I thought maybe the problem was it being scrolled while it was repainting. And yet, I still have a problem where if things are really active, some of the list items paint outside of the viewport, overwriting what's outside the JScrollPane. Forcing an exposure event will repaint those things, but it's annoying. Is there anything else I need to look out for to stop these things painting outside of their clipping area? | Have you tried explicitly enabling double-buffering on the JList and/or the components that it is drawing over? (with: setDoubleBuffered(boolean aFlag) ) Another thought is that you might need to exit the function immediately after delegating to the EDT. The way your code is written, it looks like the update will happen in both threads if ContentChanged is invoked from a non-EDT thread. Logging in the first if (or set a breakpoint in the if -- but not in the runnable -- should help determine if that is your problem. eg: public void contentsChanged(final ListDataEvent evt) { if (!EventQueue.isDispatchThread()) { log.debug("Delegating contentsChanged(...) to EDT");
EventQueue.invokeLater(new Runnable() { public void run() { contentsChanged(evt); } }); // don't run ensureIndexIsVisible twice: return; }
if (playbackInProgress) { int index = evt.getIndex0(); currentContentList.ensureIndexIsVisible(index); } } | List in JScrollPane painting outside the viewport I have a list, each item of which has several things in it, including a JProgressBar which can be updated a lot. Each time one of the items updates its JProgressBar, the ListDataListener on the list tries to scroll it to the visible range using /* * This makes the updating content item automatically scroll * into view if it is off the viewport. */ public void contentsChanged(final ListDataEvent evt) { if (!EventQueue.isDispatchThread()) { /** * Make sure the scrolling happens in the graphics "dispatch" thread. */ EventQueue.invokeLater(new Runnable() { public void run() { contentsChanged(evt); } }); } if (playbackInProgress) { int index = evt.getIndex0(); currentContentList.ensureIndexIsVisible(index); } } Note that I'm trying to make sure the scrolling is done in the dispatch thread, since I thought maybe the problem was it being scrolled while it was repainting. And yet, I still have a problem where if things are really active, some of the list items paint outside of the viewport, overwriting what's outside the JScrollPane. Forcing an exposure event will repaint those things, but it's annoying. Is there anything else I need to look out for to stop these things painting outside of their clipping area? | TITLE:
List in JScrollPane painting outside the viewport
QUESTION:
I have a list, each item of which has several things in it, including a JProgressBar which can be updated a lot. Each time one of the items updates its JProgressBar, the ListDataListener on the list tries to scroll it to the visible range using /* * This makes the updating content item automatically scroll * into view if it is off the viewport. */ public void contentsChanged(final ListDataEvent evt) { if (!EventQueue.isDispatchThread()) { /** * Make sure the scrolling happens in the graphics "dispatch" thread. */ EventQueue.invokeLater(new Runnable() { public void run() { contentsChanged(evt); } }); } if (playbackInProgress) { int index = evt.getIndex0(); currentContentList.ensureIndexIsVisible(index); } } Note that I'm trying to make sure the scrolling is done in the dispatch thread, since I thought maybe the problem was it being scrolled while it was repainting. And yet, I still have a problem where if things are really active, some of the list items paint outside of the viewport, overwriting what's outside the JScrollPane. Forcing an exposure event will repaint those things, but it's annoying. Is there anything else I need to look out for to stop these things painting outside of their clipping area?
ANSWER:
Have you tried explicitly enabling double-buffering on the JList and/or the components that it is drawing over? (with: setDoubleBuffered(boolean aFlag) ) Another thought is that you might need to exit the function immediately after delegating to the EDT. The way your code is written, it looks like the update will happen in both threads if ContentChanged is invoked from a non-EDT thread. Logging in the first if (or set a breakpoint in the if -- but not in the runnable -- should help determine if that is your problem. eg: public void contentsChanged(final ListDataEvent evt) { if (!EventQueue.isDispatchThread()) { log.debug("Delegating contentsChanged(...) to EDT");
EventQueue.invokeLater(new Runnable() { public void run() { contentsChanged(evt); } }); // don't run ensureIndexIsVisible twice: return; }
if (playbackInProgress) { int index = evt.getIndex0(); currentContentList.ensureIndexIsVisible(index); } } | [
"java",
"swing",
"jscrollpane"
] | 3 | 3 | 1,146 | 1 | 0 | 2008-08-28T15:08:47.547000 | 2008-08-28T16:17:19.207000 |
32,529 | 32,549 | How do I restrict JFileChooser to a directory? | I want to limit my users to a directory and its sub directories but the "Parent Directory" button allows them to browse to an arbitrary directory. How should I go about doing that? | You can probably do this by setting your own FileSystemView. | How do I restrict JFileChooser to a directory? I want to limit my users to a directory and its sub directories but the "Parent Directory" button allows them to browse to an arbitrary directory. How should I go about doing that? | TITLE:
How do I restrict JFileChooser to a directory?
QUESTION:
I want to limit my users to a directory and its sub directories but the "Parent Directory" button allows them to browse to an arbitrary directory. How should I go about doing that?
ANSWER:
You can probably do this by setting your own FileSystemView. | [
"java",
"swing",
"jfilechooser"
] | 26 | 14 | 15,938 | 4 | 0 | 2008-08-28T15:11:45.277000 | 2008-08-28T15:15:28.793000 |
32,533 | 32,553 | How do you write code that is both 32 bit and 64 bit compatible? | What considerations do I need to make if I want my code to run correctly on both 32bit and 64bit platforms? EDIT: What kind of areas do I need to take care in, e.g. printing strings/characters or using structures? | Options: Code it in some language with a Virtual Machine (such as Java) Code it in.NET and don't target any specific architecture. The.NET JIT compiler will compile it for you to the right architecture before running it. | How do you write code that is both 32 bit and 64 bit compatible? What considerations do I need to make if I want my code to run correctly on both 32bit and 64bit platforms? EDIT: What kind of areas do I need to take care in, e.g. printing strings/characters or using structures? | TITLE:
How do you write code that is both 32 bit and 64 bit compatible?
QUESTION:
What considerations do I need to make if I want my code to run correctly on both 32bit and 64bit platforms? EDIT: What kind of areas do I need to take care in, e.g. printing strings/characters or using structures?
ANSWER:
Options: Code it in some language with a Virtual Machine (such as Java) Code it in.NET and don't target any specific architecture. The.NET JIT compiler will compile it for you to the right architecture before running it. | [
"language-agnostic",
"compatibility",
"32bit-64bit"
] | 0 | 2 | 2,527 | 9 | 0 | 2008-08-28T15:12:15.290000 | 2008-08-28T15:17:48.397000 |
32,537 | 32,686 | What is the best way to use a console when developing? | For scripting languages, what is the most effective way to utilize a console when developing? Are there ways to be more productive with a console than a "compile and run" only language? Added clarification: I am thinking more along the lines of Ruby, Python, Boo, etc. Languages that are used for full blown apps, but also have a way to run small snippets of code in a console. | I am thinking more along the lines of Ruby,... Well for Ruby the irb interactive prompt is a great tool for "practicing" something simple. Here are the things I'll mention about the irb to give you an idea of effective use: Automation. You are allowed a.irbrc file that will be automatically executed when launching irb. That means you can load your favorite libraries or do whatever you want in full Ruby automatically. To see what I mean check out some of the ones at dotfiles.org. Autocompletion. That even makes writing code easier. Can't remember that string method to remove newlines? "".ch produces chop and chomp. NOTE: you have to enable autocompletion for irb yourself Divide and Conquer. irb makes the small things really easy. If you're writing a function to manipulate strings, the ability to test the code interactively right in the prompt saves a lot of time! For instance you can just open up irb and start running functions on an example string and have working and tested code already ready for your library/program. Learning, Experimenting, and Hacking. Something like this would take a very long time to test in C/C++, even Java. If you tried testing them all at once you might seg-fault and have to start over. Here I'm just learning how the String#[] function works. joe[~]$ irb >> "12341:asdf"[/\d+/] # => "12341" >> "12341:asdf"[/\d*/] # => "12341" >> "12341:asdf"[0..5] # => "12341:" >> "12341:asdf"[0...5] # => "12341" >> "12341:asdf"[0, ':'] TypeError: can't convert String into Integer from (irb):5:in `[]' from (irb):5 >> "12341:asdf"[0, 5] # => "12341" Testing and Benchmarking. Now they are nice and easy to perform. Here is someone's idea to emulate the Unix time function for quick benchmarking. Just add it to your.irbrc file and its always there! Debugging - I haven't used this much myself but there is always the ability to debug code like this. Or pull out some code and run it in the irb to see what its actually doing. I'm sure I'm missing some things but I hit on my favorite points. You really have zero limitation in shells so you're limited only by what you can think of doing. I almost always have a few shells running. Bash, Javascript, and Ruby's irb to name a few. I use them for a lot of things! | What is the best way to use a console when developing? For scripting languages, what is the most effective way to utilize a console when developing? Are there ways to be more productive with a console than a "compile and run" only language? Added clarification: I am thinking more along the lines of Ruby, Python, Boo, etc. Languages that are used for full blown apps, but also have a way to run small snippets of code in a console. | TITLE:
What is the best way to use a console when developing?
QUESTION:
For scripting languages, what is the most effective way to utilize a console when developing? Are there ways to be more productive with a console than a "compile and run" only language? Added clarification: I am thinking more along the lines of Ruby, Python, Boo, etc. Languages that are used for full blown apps, but also have a way to run small snippets of code in a console.
ANSWER:
I am thinking more along the lines of Ruby,... Well for Ruby the irb interactive prompt is a great tool for "practicing" something simple. Here are the things I'll mention about the irb to give you an idea of effective use: Automation. You are allowed a.irbrc file that will be automatically executed when launching irb. That means you can load your favorite libraries or do whatever you want in full Ruby automatically. To see what I mean check out some of the ones at dotfiles.org. Autocompletion. That even makes writing code easier. Can't remember that string method to remove newlines? "".ch produces chop and chomp. NOTE: you have to enable autocompletion for irb yourself Divide and Conquer. irb makes the small things really easy. If you're writing a function to manipulate strings, the ability to test the code interactively right in the prompt saves a lot of time! For instance you can just open up irb and start running functions on an example string and have working and tested code already ready for your library/program. Learning, Experimenting, and Hacking. Something like this would take a very long time to test in C/C++, even Java. If you tried testing them all at once you might seg-fault and have to start over. Here I'm just learning how the String#[] function works. joe[~]$ irb >> "12341:asdf"[/\d+/] # => "12341" >> "12341:asdf"[/\d*/] # => "12341" >> "12341:asdf"[0..5] # => "12341:" >> "12341:asdf"[0...5] # => "12341" >> "12341:asdf"[0, ':'] TypeError: can't convert String into Integer from (irb):5:in `[]' from (irb):5 >> "12341:asdf"[0, 5] # => "12341" Testing and Benchmarking. Now they are nice and easy to perform. Here is someone's idea to emulate the Unix time function for quick benchmarking. Just add it to your.irbrc file and its always there! Debugging - I haven't used this much myself but there is always the ability to debug code like this. Or pull out some code and run it in the irb to see what its actually doing. I'm sure I'm missing some things but I hit on my favorite points. You really have zero limitation in shells so you're limited only by what you can think of doing. I almost always have a few shells running. Bash, Javascript, and Ruby's irb to name a few. I use them for a lot of things! | [
"scripting",
"console"
] | 2 | 2 | 328 | 5 | 0 | 2008-08-28T15:13:20.157000 | 2008-08-28T16:11:07.473000 |
32,540 | 32,594 | Alternative "architectural" approaches to javaScript client code? | How is your javaScript code organized? Does it follow patterns like MVC, or something else? I've been working on a side project for some time now, and the further I get, the more my webpage has turned into a full-featured application. Right now, I'm sticking with jQuery, however, the logic on the page is growing to a point where some organization, or dare I say it, "architecture" is needed. My first approach is "MVC-ish": The 'model' is a JSON tree that gets extended with helpers The view is the DOM plus classes that tweak it The controller is the object where I connect events handling and kick off view or model manipulation I'm very interested, however, in how other people have built more substantial javaScript apps. I'm not interested in GWT, or other server-oriented approaches... just in the approach of "javaScript + " Note: earlier I said javaScript "is not really OO, not really functional". This, I think, distracted everyone. Let's put it this way, because javaScript is unique in many ways, and I'm coming from a strongly-typed background, I don't want to force paradigms I know but were developed in very different languages. | ..but Javascript has many facets that are OO. Consider this: var Vehicle = jQuery.Class.create({ init: function(name) { this.name = name; } });
var Car = Vehicle.extend({ fillGas: function(){ this.gas = 100; } }); I've used this technique to create page-level javascript classes that have their own state, this helps keep it contained (and I often identify areas that I can reuse and put into other classes). This is also especially useful when you have components/server controls that have their own script to execute, but when you might have multiple instances on the same page. This keeps the state separate. | Alternative "architectural" approaches to javaScript client code? How is your javaScript code organized? Does it follow patterns like MVC, or something else? I've been working on a side project for some time now, and the further I get, the more my webpage has turned into a full-featured application. Right now, I'm sticking with jQuery, however, the logic on the page is growing to a point where some organization, or dare I say it, "architecture" is needed. My first approach is "MVC-ish": The 'model' is a JSON tree that gets extended with helpers The view is the DOM plus classes that tweak it The controller is the object where I connect events handling and kick off view or model manipulation I'm very interested, however, in how other people have built more substantial javaScript apps. I'm not interested in GWT, or other server-oriented approaches... just in the approach of "javaScript + " Note: earlier I said javaScript "is not really OO, not really functional". This, I think, distracted everyone. Let's put it this way, because javaScript is unique in many ways, and I'm coming from a strongly-typed background, I don't want to force paradigms I know but were developed in very different languages. | TITLE:
Alternative "architectural" approaches to javaScript client code?
QUESTION:
How is your javaScript code organized? Does it follow patterns like MVC, or something else? I've been working on a side project for some time now, and the further I get, the more my webpage has turned into a full-featured application. Right now, I'm sticking with jQuery, however, the logic on the page is growing to a point where some organization, or dare I say it, "architecture" is needed. My first approach is "MVC-ish": The 'model' is a JSON tree that gets extended with helpers The view is the DOM plus classes that tweak it The controller is the object where I connect events handling and kick off view or model manipulation I'm very interested, however, in how other people have built more substantial javaScript apps. I'm not interested in GWT, or other server-oriented approaches... just in the approach of "javaScript + " Note: earlier I said javaScript "is not really OO, not really functional". This, I think, distracted everyone. Let's put it this way, because javaScript is unique in many ways, and I'm coming from a strongly-typed background, I don't want to force paradigms I know but were developed in very different languages.
ANSWER:
..but Javascript has many facets that are OO. Consider this: var Vehicle = jQuery.Class.create({ init: function(name) { this.name = name; } });
var Car = Vehicle.extend({ fillGas: function(){ this.gas = 100; } }); I've used this technique to create page-level javascript classes that have their own state, this helps keep it contained (and I often identify areas that I can reuse and put into other classes). This is also especially useful when you have components/server controls that have their own script to execute, but when you might have multiple instances on the same page. This keeps the state separate. | [
"javascript",
"model-view-controller",
"architecture",
"client",
"ria"
] | 19 | 7 | 1,401 | 7 | 0 | 2008-08-28T15:13:57.533000 | 2008-08-28T15:29:51.863000 |
32,541 | 33,036 | How can you clone a WPF object? | Anybody have a good example how to deep clone a WPF object, preserving databindings? The marked answer is the first part. The second part is that you have to create an ExpressionConverter and inject it into the serialization process. Details for this are here: http://www.codeproject.com/KB/WPF/xamlwriterandbinding.aspx?fid=1428301&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2801571 | The simplest way that I've done it is to use a XamlWriter to save the WPF object as a string. The Save method will serialize the object and all of its children in the logical tree. Now you can create a new object and load it with a XamlReader. ex: Write the object to xaml (let's say the object was a Grid control): string gridXaml = XamlWriter.Save(myGrid); Load it into a new object: StringReader stringReader = new StringReader(gridXaml); XmlReader xmlReader = XmlReader.Create(stringReader); Grid newGrid = (Grid)XamlReader.Load(xmlReader); | How can you clone a WPF object? Anybody have a good example how to deep clone a WPF object, preserving databindings? The marked answer is the first part. The second part is that you have to create an ExpressionConverter and inject it into the serialization process. Details for this are here: http://www.codeproject.com/KB/WPF/xamlwriterandbinding.aspx?fid=1428301&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2801571 | TITLE:
How can you clone a WPF object?
QUESTION:
Anybody have a good example how to deep clone a WPF object, preserving databindings? The marked answer is the first part. The second part is that you have to create an ExpressionConverter and inject it into the serialization process. Details for this are here: http://www.codeproject.com/KB/WPF/xamlwriterandbinding.aspx?fid=1428301&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2801571
ANSWER:
The simplest way that I've done it is to use a XamlWriter to save the WPF object as a string. The Save method will serialize the object and all of its children in the logical tree. Now you can create a new object and load it with a XamlReader. ex: Write the object to xaml (let's say the object was a Grid control): string gridXaml = XamlWriter.Save(myGrid); Load it into a new object: StringReader stringReader = new StringReader(gridXaml); XmlReader xmlReader = XmlReader.Create(stringReader); Grid newGrid = (Grid)XamlReader.Load(xmlReader); | [
"c#",
"wpf",
"binding",
"clone"
] | 42 | 65 | 49,107 | 4 | 0 | 2008-08-28T15:14:29.967000 | 2008-08-28T18:38:06.887000 |
32,570 | 32,577 | How to make 'pretty urls' work in php hosted in IIS? | Is there some way I can use URLs like: http://www.blog.com/team-spirit/ instead of http://www.blog.com/?p=122 in a Windows hosted PHP server? | This is how I did it with WordPress on IIS 6.0 http://www.coderjournal.com/2008/02/url-rewriter-reverse-proxy-iis-wordpress/ However it all depends on what version of IIS you are using. If you are lucky enough to use IIS 7.0 you don't really have to worry about pretty urls because everything is supported out of the box. However if you are using IIS 6.0 you are going to have to use a rewriter and some rules to force the IISness out of IIS. | How to make 'pretty urls' work in php hosted in IIS? Is there some way I can use URLs like: http://www.blog.com/team-spirit/ instead of http://www.blog.com/?p=122 in a Windows hosted PHP server? | TITLE:
How to make 'pretty urls' work in php hosted in IIS?
QUESTION:
Is there some way I can use URLs like: http://www.blog.com/team-spirit/ instead of http://www.blog.com/?p=122 in a Windows hosted PHP server?
ANSWER:
This is how I did it with WordPress on IIS 6.0 http://www.coderjournal.com/2008/02/url-rewriter-reverse-proxy-iis-wordpress/ However it all depends on what version of IIS you are using. If you are lucky enough to use IIS 7.0 you don't really have to worry about pretty urls because everything is supported out of the box. However if you are using IIS 6.0 you are going to have to use a rewriter and some rules to force the IISness out of IIS. | [
"php",
"iis"
] | 1 | 1 | 1,737 | 5 | 0 | 2008-08-28T15:23:53.500000 | 2008-08-28T15:25:17.553000 |
32,596 | 34,771 | Odd behaviour for rowSpan in Flex | I am experiencing some oddities when working with a Grid component in flex, I have the following form that uses a grid to align the fields, as you can see, each GridRow has a border. My problem is that the border is still visible through GridItems that span multiple rows (observe the TextArea that spans 4 rows, the GridRow borders go right threw it!) Any ideas of how to fix this? | I think the problem is that when the Grid is drawn, it draws each row from top to bottom, and within each row the items left to right. So the row-spanned item is drawn first extending down into the area of the 2 next rows, which get drawn after and on top. The quickest way around I can see would be to draw the row borders on the s instead, skipping the left and right edges based on the item's placement in the row. Something like this: Grid { background-color: white; horizontal-gap: 0; } GridItem { padding-top: 5; padding-left: 5; padding-right: 5; padding-bottom: 5; background-color: #efefef;
border-style: solid; border-thickness: 1; border-color: black; }.left { border-sides: top, bottom, left; }.right { border-sides: top, bottom, right; }.center { border-sides: top, bottom; } | Odd behaviour for rowSpan in Flex I am experiencing some oddities when working with a Grid component in flex, I have the following form that uses a grid to align the fields, as you can see, each GridRow has a border. My problem is that the border is still visible through GridItems that span multiple rows (observe the TextArea that spans 4 rows, the GridRow borders go right threw it!) Any ideas of how to fix this? | TITLE:
Odd behaviour for rowSpan in Flex
QUESTION:
I am experiencing some oddities when working with a Grid component in flex, I have the following form that uses a grid to align the fields, as you can see, each GridRow has a border. My problem is that the border is still visible through GridItems that span multiple rows (observe the TextArea that spans 4 rows, the GridRow borders go right threw it!) Any ideas of how to fix this?
ANSWER:
I think the problem is that when the Grid is drawn, it draws each row from top to bottom, and within each row the items left to right. So the row-spanned item is drawn first extending down into the area of the 2 next rows, which get drawn after and on top. The quickest way around I can see would be to draw the row borders on the s instead, skipping the left and right edges based on the item's placement in the row. Something like this: Grid { background-color: white; horizontal-gap: 0; } GridItem { padding-top: 5; padding-left: 5; padding-right: 5; padding-bottom: 5; background-color: #efefef;
border-style: solid; border-thickness: 1; border-color: black; }.left { border-sides: top, bottom, left; }.right { border-sides: top, bottom, right; }.center { border-sides: top, bottom; } | [
"apache-flex"
] | 0 | 1 | 2,334 | 1 | 0 | 2008-08-28T15:30:27.040000 | 2008-08-29T17:12:05.327000 |
32,597 | 39,208 | Installing Team Foundation Server | What are the best practices in setting up a new instance of TFS 2008 Workgroup edition? Specifically, the constraints are as follows: Must install on an existing Windows Server 2008 64 bit TFS application layer is 32 bit only Should I install SQL Server 2008, Sharepoint and the app layer in a virtual instance of Windows Server 2008 or 2003(I am already running Hyper-V) or split the layers with a database on the host OS and the app layer in a virtual machine? Edit: Apparently, splitting the layers is not recommended | This is my recipe for installing TFS 2008 SP1. There is no domain controller in this scenario, we are only a couple of users. If I was to do it again, I would consider changing our environement to use a active directory domain. Host Server running Windows Server 2008 with 8GB RAM and quad processor Fresh install of Windows Server 2008 32bit in a VM under Hyper-V Install Application Server role with IIS Install SQL Server 2008 Standard edition Use a user account for Reporting Services and Analysis Services Create a slipstreamed image of TFS 2008 with SP1 and install TFS Install VSTS 2008 Install Team System Explorer Install VSTS 2008 SP1 Install TFS Web Access Power tool After installing everything, reports were not generated. Found this forum post that helped resolve the problem. Open p://localhost:8080/Warehouse/v1.0/warehousecontroller.asmx Run the webservice (see above link for details), it will take a little while, the tfsWarehouse will be rebuilt It is very important to do things in order, download the installation guide and follow it to the letter. I forgot to install the Team System Explorer until after installing SP1 and ventured into all sorts of problems. Installing SP1 once more fixed that. | Installing Team Foundation Server What are the best practices in setting up a new instance of TFS 2008 Workgroup edition? Specifically, the constraints are as follows: Must install on an existing Windows Server 2008 64 bit TFS application layer is 32 bit only Should I install SQL Server 2008, Sharepoint and the app layer in a virtual instance of Windows Server 2008 or 2003(I am already running Hyper-V) or split the layers with a database on the host OS and the app layer in a virtual machine? Edit: Apparently, splitting the layers is not recommended | TITLE:
Installing Team Foundation Server
QUESTION:
What are the best practices in setting up a new instance of TFS 2008 Workgroup edition? Specifically, the constraints are as follows: Must install on an existing Windows Server 2008 64 bit TFS application layer is 32 bit only Should I install SQL Server 2008, Sharepoint and the app layer in a virtual instance of Windows Server 2008 or 2003(I am already running Hyper-V) or split the layers with a database on the host OS and the app layer in a virtual machine? Edit: Apparently, splitting the layers is not recommended
ANSWER:
This is my recipe for installing TFS 2008 SP1. There is no domain controller in this scenario, we are only a couple of users. If I was to do it again, I would consider changing our environement to use a active directory domain. Host Server running Windows Server 2008 with 8GB RAM and quad processor Fresh install of Windows Server 2008 32bit in a VM under Hyper-V Install Application Server role with IIS Install SQL Server 2008 Standard edition Use a user account for Reporting Services and Analysis Services Create a slipstreamed image of TFS 2008 with SP1 and install TFS Install VSTS 2008 Install Team System Explorer Install VSTS 2008 SP1 Install TFS Web Access Power tool After installing everything, reports were not generated. Found this forum post that helped resolve the problem. Open p://localhost:8080/Warehouse/v1.0/warehousecontroller.asmx Run the webservice (see above link for details), it will take a little while, the tfsWarehouse will be rebuilt It is very important to do things in order, download the installation guide and follow it to the letter. I forgot to install the Team System Explorer until after installing SP1 and ventured into all sorts of problems. Installing SP1 once more fixed that. | [
"visual-studio",
"visual-studio-2008",
"version-control",
"tfs",
"hyper-v"
] | 3 | 8 | 2,741 | 4 | 0 | 2008-08-28T15:30:34.280000 | 2008-09-02T10:46:29.697000 |
32,598 | 32,626 | Any disadvantages in accessing Subversion repositories through file:// for a solo developer? | If you have Subversion installed on your development machine and you don't work in a team, is there any reason why you should use the svn protocol instead of file? | If you are working by yourself on a single machine, then in my experience using the file:// protocol works fine. Even when my team was using Subversion off a remote server, I would set up a local file-based repository for my own personal projects. If you get to the point where you need to access it from a different machine, then I would go to the trouble of setting up a server-based repository. You might also look at a distributed system like Mercurial - we were evaluating it at my last company just before I left - but definitely pick one or the other, mixing svn and hg doesn't work well at all. | Any disadvantages in accessing Subversion repositories through file:// for a solo developer? If you have Subversion installed on your development machine and you don't work in a team, is there any reason why you should use the svn protocol instead of file? | TITLE:
Any disadvantages in accessing Subversion repositories through file:// for a solo developer?
QUESTION:
If you have Subversion installed on your development machine and you don't work in a team, is there any reason why you should use the svn protocol instead of file?
ANSWER:
If you are working by yourself on a single machine, then in my experience using the file:// protocol works fine. Even when my team was using Subversion off a remote server, I would set up a local file-based repository for my own personal projects. If you get to the point where you need to access it from a different machine, then I would go to the trouble of setting up a server-based repository. You might also look at a distributed system like Mercurial - we were evaluating it at my last company just before I left - but definitely pick one or the other, mixing svn and hg doesn't work well at all. | [
"svn"
] | 6 | 8 | 4,359 | 12 | 0 | 2008-08-28T15:30:37.727000 | 2008-08-28T15:43:48.507000 |
32,612 | 33,622 | Best way to manage session in NHibernate? | I'm new to NHibernate (my 1st big project with it). I had been using a simple method of data access by creating the ISession object within a using block to do my grab my Object or list of Objects, and in that way the session was destroyed after exiting the code block. This doesn't work in a situation where lazy-loading is required, however. For example, if I have a Customer object that has a property which is a collection of Orders, then when the lazy-load is attempted, I get a Hibernate exception. Anyone using a different method? | Session management: http://code.google.com/p/dot-net-reference-app/source/browse/trunk/src/Infrastructure/Impl/HybridSessionBuilder.cs Session per request: http://code.google.com/p/dot-net-reference-app/source/browse/trunk/src/Infrastructure/Impl/NHibernateSessionModule.cs | Best way to manage session in NHibernate? I'm new to NHibernate (my 1st big project with it). I had been using a simple method of data access by creating the ISession object within a using block to do my grab my Object or list of Objects, and in that way the session was destroyed after exiting the code block. This doesn't work in a situation where lazy-loading is required, however. For example, if I have a Customer object that has a property which is a collection of Orders, then when the lazy-load is attempted, I get a Hibernate exception. Anyone using a different method? | TITLE:
Best way to manage session in NHibernate?
QUESTION:
I'm new to NHibernate (my 1st big project with it). I had been using a simple method of data access by creating the ISession object within a using block to do my grab my Object or list of Objects, and in that way the session was destroyed after exiting the code block. This doesn't work in a situation where lazy-loading is required, however. For example, if I have a Customer object that has a property which is a collection of Orders, then when the lazy-load is attempted, I get a Hibernate exception. Anyone using a different method?
ANSWER:
Session management: http://code.google.com/p/dot-net-reference-app/source/browse/trunk/src/Infrastructure/Impl/HybridSessionBuilder.cs Session per request: http://code.google.com/p/dot-net-reference-app/source/browse/trunk/src/Infrastructure/Impl/NHibernateSessionModule.cs | [
"c#",
".net",
"nhibernate"
] | 5 | 6 | 6,654 | 4 | 0 | 2008-08-28T15:34:09.467000 | 2008-08-28T23:20:08.207000 |
32,617 | 32,627 | Is there a way to do "intraWord" text navigation in Visual Studio? | On Windows, Ctrl+Right Arrow will move the text cursor from one "word" to the next. While working with Xcode on the Mac, they extended that so that Option+Right Arrow will move the cursor to the beginning of the next subword. For example, if the cursor was at the beginning of the word myCamelCaseVar then hitting Option+Right Arrow will put the cursor at the first C. This was an amazingly useful feature that I haven't found in a Windows editor. Do you know of any way to do this in Visual Studio (perhaps with an Add-In)? I'm currently using pretty old iterations of Visual Studio (Visual Basic 6.0 and Visual C++ ), although I'm interested to know if the more modern releases can do this, too. | ReSharper has a " Camel Humps " feature that lets you do this. | Is there a way to do "intraWord" text navigation in Visual Studio? On Windows, Ctrl+Right Arrow will move the text cursor from one "word" to the next. While working with Xcode on the Mac, they extended that so that Option+Right Arrow will move the cursor to the beginning of the next subword. For example, if the cursor was at the beginning of the word myCamelCaseVar then hitting Option+Right Arrow will put the cursor at the first C. This was an amazingly useful feature that I haven't found in a Windows editor. Do you know of any way to do this in Visual Studio (perhaps with an Add-In)? I'm currently using pretty old iterations of Visual Studio (Visual Basic 6.0 and Visual C++ ), although I'm interested to know if the more modern releases can do this, too. | TITLE:
Is there a way to do "intraWord" text navigation in Visual Studio?
QUESTION:
On Windows, Ctrl+Right Arrow will move the text cursor from one "word" to the next. While working with Xcode on the Mac, they extended that so that Option+Right Arrow will move the cursor to the beginning of the next subword. For example, if the cursor was at the beginning of the word myCamelCaseVar then hitting Option+Right Arrow will put the cursor at the first C. This was an amazingly useful feature that I haven't found in a Windows editor. Do you know of any way to do this in Visual Studio (perhaps with an Add-In)? I'm currently using pretty old iterations of Visual Studio (Visual Basic 6.0 and Visual C++ ), although I'm interested to know if the more modern releases can do this, too.
ANSWER:
ReSharper has a " Camel Humps " feature that lets you do this. | [
"visual-studio",
"keyboard"
] | 1 | 2 | 143 | 1 | 0 | 2008-08-28T15:37:32.720000 | 2008-08-28T15:44:03.093000 |
32,621 | 67,303 | How do I find the the exact lat/lng coordinates of a birdseye scene in Virtual Earth? | I'm trying to find the latitude and longitude of the corners of my map while in birdseye view. I want to be able to plot pins on the map, but I have hundreds of thousands of addresses that I want to be able to limit to the ones that need to show on the map. In normal view, VEMap.GetMapView().TopLeftLatLong and.BottomRightLatLong return the coordinates I need; but in Birdseye view they return blank (or encrypted values). The SDK recommends using VEBirdseyeScene.GetBoundingRectangle(), but this returns bounds of up to two miles from the center of my scene which in major cities still returns way too many addresses. In previous versions of the VE Control, there was an undocumented VEDecoder object I could use to decrypt the LatLong values for the birdseye scenes, but this object seems to have disappeared (probably been renamed). How can I decode these values in version 6.1? | Here's the code for getting the Center Lat/Long point of the map. This method works in both Road/Aerial and Birdseye/Oblique map styles. function GetCenterLatLong() { //Check if in Birdseye or Oblique Map Style if (map.GetMapStyle() == VEMapStyle.Birdseye || map.GetMapStyle() == VEMapStyle.BirdseyeHybrid) { //IN Birdseye or Oblique Map Style
//Get the BirdseyeScene being displayed var birdseyeScene = map.GetBirdseyeScene();
//Get approximate center coordinate of the map var x = birdseyeScene.GetWidth() / 2; var y = birdseyeScene.GetHeight() / 2;
// Get the Lat/Long var center = birdseyeScene.PixelToLatLong(new VEPixel(x,y), map.GetZoomLevel());
// Convert the BirdseyeScene LatLong to a normal LatLong we can use return (new _xy1).Decode(center); } else { // NOT in Birdseye or Oblique Map Style return map.GetCenter(); } } This code was copied from here: http://pietschsoft.com/post/2008/06/Virtual-Earth-Get-Center-LatLong-When-In-Birdseye-or-Oblique-Map-Style.aspx | How do I find the the exact lat/lng coordinates of a birdseye scene in Virtual Earth? I'm trying to find the latitude and longitude of the corners of my map while in birdseye view. I want to be able to plot pins on the map, but I have hundreds of thousands of addresses that I want to be able to limit to the ones that need to show on the map. In normal view, VEMap.GetMapView().TopLeftLatLong and.BottomRightLatLong return the coordinates I need; but in Birdseye view they return blank (or encrypted values). The SDK recommends using VEBirdseyeScene.GetBoundingRectangle(), but this returns bounds of up to two miles from the center of my scene which in major cities still returns way too many addresses. In previous versions of the VE Control, there was an undocumented VEDecoder object I could use to decrypt the LatLong values for the birdseye scenes, but this object seems to have disappeared (probably been renamed). How can I decode these values in version 6.1? | TITLE:
How do I find the the exact lat/lng coordinates of a birdseye scene in Virtual Earth?
QUESTION:
I'm trying to find the latitude and longitude of the corners of my map while in birdseye view. I want to be able to plot pins on the map, but I have hundreds of thousands of addresses that I want to be able to limit to the ones that need to show on the map. In normal view, VEMap.GetMapView().TopLeftLatLong and.BottomRightLatLong return the coordinates I need; but in Birdseye view they return blank (or encrypted values). The SDK recommends using VEBirdseyeScene.GetBoundingRectangle(), but this returns bounds of up to two miles from the center of my scene which in major cities still returns way too many addresses. In previous versions of the VE Control, there was an undocumented VEDecoder object I could use to decrypt the LatLong values for the birdseye scenes, but this object seems to have disappeared (probably been renamed). How can I decode these values in version 6.1?
ANSWER:
Here's the code for getting the Center Lat/Long point of the map. This method works in both Road/Aerial and Birdseye/Oblique map styles. function GetCenterLatLong() { //Check if in Birdseye or Oblique Map Style if (map.GetMapStyle() == VEMapStyle.Birdseye || map.GetMapStyle() == VEMapStyle.BirdseyeHybrid) { //IN Birdseye or Oblique Map Style
//Get the BirdseyeScene being displayed var birdseyeScene = map.GetBirdseyeScene();
//Get approximate center coordinate of the map var x = birdseyeScene.GetWidth() / 2; var y = birdseyeScene.GetHeight() / 2;
// Get the Lat/Long var center = birdseyeScene.PixelToLatLong(new VEPixel(x,y), map.GetZoomLevel());
// Convert the BirdseyeScene LatLong to a normal LatLong we can use return (new _xy1).Decode(center); } else { // NOT in Birdseye or Oblique Map Style return map.GetCenter(); } } This code was copied from here: http://pietschsoft.com/post/2008/06/Virtual-Earth-Get-Center-LatLong-When-In-Birdseye-or-Oblique-Map-Style.aspx | [
"javascript",
"virtual-earth"
] | 4 | 2 | 2,051 | 5 | 0 | 2008-08-28T15:38:42.577000 | 2008-09-15T21:44:18.257000 |
32,633 | 1,330,776 | How can I set breakpoints in an external JS script in Firebug | I can easily set breakpoints in embedded JS functions, but I don't see any way of accessing external JS scripts via Firebug unless I happen to enter them during a debug session. Is there a way to do this without having to 'explore' my way into the script? @Jason: This is a good point, but in my case I do not have easy access to the script. I am specifically talking about the client scripts which are invoked by the ASP.Net Validators that I would like to debug. I can access them during a debug session through entering the function calls, but I could not find a way to access them directly. | To view and access external JavaScript files (*.js) from within Firebug: Click on the 'Script' tab. Click on the 'all' drop down in the upper left hand corner above the script code content window. Select 'Show Static Scripts'. Click on the dropdown button just to the right of what now says 'static' (By default, it should show the name of your current web page). You should now see a list of files associated with the current web page including any external JS files. Select the JavaScript file you are interested in and it's code will display in the content window. From there, you should be able to set breakpoints as normal. | How can I set breakpoints in an external JS script in Firebug I can easily set breakpoints in embedded JS functions, but I don't see any way of accessing external JS scripts via Firebug unless I happen to enter them during a debug session. Is there a way to do this without having to 'explore' my way into the script? @Jason: This is a good point, but in my case I do not have easy access to the script. I am specifically talking about the client scripts which are invoked by the ASP.Net Validators that I would like to debug. I can access them during a debug session through entering the function calls, but I could not find a way to access them directly. | TITLE:
How can I set breakpoints in an external JS script in Firebug
QUESTION:
I can easily set breakpoints in embedded JS functions, but I don't see any way of accessing external JS scripts via Firebug unless I happen to enter them during a debug session. Is there a way to do this without having to 'explore' my way into the script? @Jason: This is a good point, but in my case I do not have easy access to the script. I am specifically talking about the client scripts which are invoked by the ASP.Net Validators that I would like to debug. I can access them during a debug session through entering the function calls, but I could not find a way to access them directly.
ANSWER:
To view and access external JavaScript files (*.js) from within Firebug: Click on the 'Script' tab. Click on the 'all' drop down in the upper left hand corner above the script code content window. Select 'Show Static Scripts'. Click on the dropdown button just to the right of what now says 'static' (By default, it should show the name of your current web page). You should now see a list of files associated with the current web page including any external JS files. Select the JavaScript file you are interested in and it's code will display in the content window. From there, you should be able to set breakpoints as normal. | [
"javascript",
"debugging",
"firebug"
] | 28 | 21 | 19,824 | 5 | 0 | 2008-08-28T15:48:03.083000 | 2009-08-25T20:28:36.300000 |
32,637 | 32,648 | Easiest way to convert a URL to a hyperlink in a C# string? | I am consuming the Twitter API and want to convert all URLs to hyperlinks. What is the most effective way you've come up with to do this? from string myString = "This is my tweet check it out http://tinyurl.com/blah"; to This is my tweet check it out http://tinyurl.com/>blah | Regular expressions are probably your friend for this kind of task: Regex r = new Regex(@"(https?://[^\s]+)"); myString = r.Replace(myString, " $1 "); The regular expression for matching URLs might need a bit of work. | Easiest way to convert a URL to a hyperlink in a C# string? I am consuming the Twitter API and want to convert all URLs to hyperlinks. What is the most effective way you've come up with to do this? from string myString = "This is my tweet check it out http://tinyurl.com/blah"; to This is my tweet check it out http://tinyurl.com/>blah | TITLE:
Easiest way to convert a URL to a hyperlink in a C# string?
QUESTION:
I am consuming the Twitter API and want to convert all URLs to hyperlinks. What is the most effective way you've come up with to do this? from string myString = "This is my tweet check it out http://tinyurl.com/blah"; to This is my tweet check it out http://tinyurl.com/>blah
ANSWER:
Regular expressions are probably your friend for this kind of task: Regex r = new Regex(@"(https?://[^\s]+)"); myString = r.Replace(myString, " $1 "); The regular expression for matching URLs might need a bit of work. | [
"c#",
"regex",
"string",
"hyperlink"
] | 18 | 24 | 18,180 | 5 | 0 | 2008-08-28T15:49:32.690000 | 2008-08-28T15:54:16.923000 |
32,640 | 32,672 | Mocking Asp.net-mvc Controller Context | So the controller context depends on some asp.net internals. What are some ways to cleanly mock these up for unit tests? Seems like its very easy to clog up tests with tons of setup when I only need, for example, Request.HttpMethod to return "GET". I've seen some examples/helpers out on the nets, but some are dated. Figured this would be a good place to keep the latest and greatest. I'm using latest version of rhino mocks | Using MoQ it looks something like this: var request = new Mock (); request.Expect(r => r.HttpMethod).Returns("GET"); var mockHttpContext = new Mock (); mockHttpContext.Expect(c => c.Request).Returns(request.Object); var controllerContext = new ControllerContext(mockHttpContext.Object, new RouteData(), new Mock ().Object); I think the Rhino Mocks syntax is similar. | Mocking Asp.net-mvc Controller Context So the controller context depends on some asp.net internals. What are some ways to cleanly mock these up for unit tests? Seems like its very easy to clog up tests with tons of setup when I only need, for example, Request.HttpMethod to return "GET". I've seen some examples/helpers out on the nets, but some are dated. Figured this would be a good place to keep the latest and greatest. I'm using latest version of rhino mocks | TITLE:
Mocking Asp.net-mvc Controller Context
QUESTION:
So the controller context depends on some asp.net internals. What are some ways to cleanly mock these up for unit tests? Seems like its very easy to clog up tests with tons of setup when I only need, for example, Request.HttpMethod to return "GET". I've seen some examples/helpers out on the nets, but some are dated. Figured this would be a good place to keep the latest and greatest. I'm using latest version of rhino mocks
ANSWER:
Using MoQ it looks something like this: var request = new Mock (); request.Expect(r => r.HttpMethod).Returns("GET"); var mockHttpContext = new Mock (); mockHttpContext.Expect(c => c.Request).Returns(request.Object); var controllerContext = new ControllerContext(mockHttpContext.Object, new RouteData(), new Mock ().Object); I think the Rhino Mocks syntax is similar. | [
"asp.net-mvc",
"unit-testing",
"mocking",
"moq",
"rhino-mocks"
] | 70 | 66 | 49,845 | 7 | 0 | 2008-08-28T15:50:35.543000 | 2008-08-28T16:06:37.890000 |
32,642 | 32,653 | Beginning ASP.NET MVC with VB.net 2008 | Where can I find a good tutorial on learning ASP.NET MVC using VB.net 2008 as the language? Most in-depth tutorials that I found in searching the web were written in C#. | Have you tried adding the word "VB" to your searches?? http://www.myvbprof.com/2007_Version/MVC_Intro_Tutorial.aspx http://www.asp.net/learn/mvc/tutorial-07-vb.aspx < Link > | Beginning ASP.NET MVC with VB.net 2008 Where can I find a good tutorial on learning ASP.NET MVC using VB.net 2008 as the language? Most in-depth tutorials that I found in searching the web were written in C#. | TITLE:
Beginning ASP.NET MVC with VB.net 2008
QUESTION:
Where can I find a good tutorial on learning ASP.NET MVC using VB.net 2008 as the language? Most in-depth tutorials that I found in searching the web were written in C#.
ANSWER:
Have you tried adding the word "VB" to your searches?? http://www.myvbprof.com/2007_Version/MVC_Intro_Tutorial.aspx http://www.asp.net/learn/mvc/tutorial-07-vb.aspx < Link > | [
"asp.net-mvc",
"vb.net",
"visual-studio-2008",
"model-view-controller",
".net-3.5"
] | 3 | 3 | 6,311 | 2 | 0 | 2008-08-28T15:50:49.927000 | 2008-08-28T15:57:10.003000 |
32,643 | 34,311 | Automatic image rotation based on a logo | We're looking for a package to help identify and automatically rotate faxed TIFF images based on a watermark or logo. We use libtiff for rotation currently, but don't know of any other libraries or packages I can use for detecting this logo and determining how to rotate the images. I have done some basic work with OpenCV but I'm not sure that it is the right tool for this job. I would prefer to use C/C++ but Java, Perl or PHP would be acceptable too. | You are in the right place using OpenCV, it is an excellent utility. For example, this guy used it for template matching, which is fairly similar to what you need to do. Also, the link Roddy specified looks similar to what you want to do. I feel that OpenCV is the best library out there for this kind of development. @Brian, OpenCV and the IntelIPP are closely linked and very similar (both Intel libs). As far as I know, if OpenCV finds the intel IPP on your computer it will automatically use it under the hood for improved speed. | Automatic image rotation based on a logo We're looking for a package to help identify and automatically rotate faxed TIFF images based on a watermark or logo. We use libtiff for rotation currently, but don't know of any other libraries or packages I can use for detecting this logo and determining how to rotate the images. I have done some basic work with OpenCV but I'm not sure that it is the right tool for this job. I would prefer to use C/C++ but Java, Perl or PHP would be acceptable too. | TITLE:
Automatic image rotation based on a logo
QUESTION:
We're looking for a package to help identify and automatically rotate faxed TIFF images based on a watermark or logo. We use libtiff for rotation currently, but don't know of any other libraries or packages I can use for detecting this logo and determining how to rotate the images. I have done some basic work with OpenCV but I'm not sure that it is the right tool for this job. I would prefer to use C/C++ but Java, Perl or PHP would be acceptable too.
ANSWER:
You are in the right place using OpenCV, it is an excellent utility. For example, this guy used it for template matching, which is fairly similar to what you need to do. Also, the link Roddy specified looks similar to what you want to do. I feel that OpenCV is the best library out there for this kind of development. @Brian, OpenCV and the IntelIPP are closely linked and very similar (both Intel libs). As far as I know, if OpenCV finds the intel IPP on your computer it will automatically use it under the hood for improved speed. | [
"opencv",
"tiff",
"watermark",
"image-rotation"
] | 3 | 1 | 1,477 | 3 | 0 | 2008-08-28T15:50:57.133000 | 2008-08-29T10:07:59.507000 |
32,649 | 32,705 | Data Conflict in LINQ | When making changes using SubmitChanges(), LINQ sometimes dies with a ChangeConflictException exception with the error message Row not found or changed, without any indication of either the row that has the conflict or the fields with changes that are in conflict, when another user has changed some data in that row. Is there any way to determine which row has a conflict and which fields they occur in, and also is there a way of getting LINQ to ignore the issue and simply commit the data regardless? Additionally, does anybody know whether this exception occurs when any data in the row has changed, or only when data has been changed in a field that LINQ is attempting to alter? | Here's a way to see where the conflicts are (this is an MSDN example, so you'll need to heavily customize): try { db.SubmitChanges(ConflictMode.ContinueOnConflict); } catch (ChangeConflictException e) { Console.WriteLine("Optimistic concurrency error."); Console.WriteLine(e.Message); Console.ReadLine(); foreach (ObjectChangeConflict occ in db.ChangeConflicts) { MetaTable metatable = db.Mapping.GetTable(occ.Object.GetType()); Customer entityInConflict = (Customer)occ.Object; Console.WriteLine("Table name: {0}", metatable.TableName); Console.Write("Customer ID: "); Console.WriteLine(entityInConflict.CustomerID); foreach (MemberChangeConflict mcc in occ.MemberConflicts) { object currVal = mcc.CurrentValue; object origVal = mcc.OriginalValue; object databaseVal = mcc.DatabaseValue; MemberInfo mi = mcc.Member; Console.WriteLine("Member: {0}", mi.Name); Console.WriteLine("current value: {0}", currVal); Console.WriteLine("original value: {0}", origVal); Console.WriteLine("database value: {0}", databaseVal); } } } To make it ignore the problem and commit anyway: db.SubmitChanges(ConflictMode.ContinueOnConflict); | Data Conflict in LINQ When making changes using SubmitChanges(), LINQ sometimes dies with a ChangeConflictException exception with the error message Row not found or changed, without any indication of either the row that has the conflict or the fields with changes that are in conflict, when another user has changed some data in that row. Is there any way to determine which row has a conflict and which fields they occur in, and also is there a way of getting LINQ to ignore the issue and simply commit the data regardless? Additionally, does anybody know whether this exception occurs when any data in the row has changed, or only when data has been changed in a field that LINQ is attempting to alter? | TITLE:
Data Conflict in LINQ
QUESTION:
When making changes using SubmitChanges(), LINQ sometimes dies with a ChangeConflictException exception with the error message Row not found or changed, without any indication of either the row that has the conflict or the fields with changes that are in conflict, when another user has changed some data in that row. Is there any way to determine which row has a conflict and which fields they occur in, and also is there a way of getting LINQ to ignore the issue and simply commit the data regardless? Additionally, does anybody know whether this exception occurs when any data in the row has changed, or only when data has been changed in a field that LINQ is attempting to alter?
ANSWER:
Here's a way to see where the conflicts are (this is an MSDN example, so you'll need to heavily customize): try { db.SubmitChanges(ConflictMode.ContinueOnConflict); } catch (ChangeConflictException e) { Console.WriteLine("Optimistic concurrency error."); Console.WriteLine(e.Message); Console.ReadLine(); foreach (ObjectChangeConflict occ in db.ChangeConflicts) { MetaTable metatable = db.Mapping.GetTable(occ.Object.GetType()); Customer entityInConflict = (Customer)occ.Object; Console.WriteLine("Table name: {0}", metatable.TableName); Console.Write("Customer ID: "); Console.WriteLine(entityInConflict.CustomerID); foreach (MemberChangeConflict mcc in occ.MemberConflicts) { object currVal = mcc.CurrentValue; object origVal = mcc.OriginalValue; object databaseVal = mcc.DatabaseValue; MemberInfo mi = mcc.Member; Console.WriteLine("Member: {0}", mi.Name); Console.WriteLine("current value: {0}", currVal); Console.WriteLine("original value: {0}", origVal); Console.WriteLine("database value: {0}", databaseVal); } } } To make it ignore the problem and commit anyway: db.SubmitChanges(ConflictMode.ContinueOnConflict); | [
"c#",
"linq",
"linq-to-sql"
] | 19 | 24 | 10,942 | 7 | 0 | 2008-08-28T15:54:56.047000 | 2008-08-28T16:16:19.787000 |
32,668 | 32,692 | How to remember in CSS that margin is outside the border, and padding inside | I don't edit CSS very often, and almost every time I need to go and google the CSS box model to check whether padding is inside the border and margin outside, or vice versa. (Just checked again and padding is inside). Does anyone have a good way of remembering this? A little mnemonic, a good explanation as to why the names are that way round... | When working with CSS finally drives you mad the padded cell that they will put you in has the padding on the inside of the walls. | How to remember in CSS that margin is outside the border, and padding inside I don't edit CSS very often, and almost every time I need to go and google the CSS box model to check whether padding is inside the border and margin outside, or vice versa. (Just checked again and padding is inside). Does anyone have a good way of remembering this? A little mnemonic, a good explanation as to why the names are that way round... | TITLE:
How to remember in CSS that margin is outside the border, and padding inside
QUESTION:
I don't edit CSS very often, and almost every time I need to go and google the CSS box model to check whether padding is inside the border and margin outside, or vice versa. (Just checked again and padding is inside). Does anyone have a good way of remembering this? A little mnemonic, a good explanation as to why the names are that way round...
ANSWER:
When working with CSS finally drives you mad the padded cell that they will put you in has the padding on the inside of the walls. | [
"css",
"padding",
"margin",
"mnemonics"
] | 35 | 153 | 15,686 | 15 | 0 | 2008-08-28T16:06:04.803000 | 2008-08-28T16:13:09.030000 |
32,689 | 32,714 | In MS SQL Server 2005, is there a way to export, the complete maintenance plan of a database as a SQL Script? | Currently, if I want to output a SQL script for a table in my database, in Management Studio, I can right click and output a create script. Is there an equivalent to output an SQL script for a database's maintenance plan?# Edit The company I work for has 4 servers, 3 servers and no sign of integration, each one running about 500,000 transactions a day. The original maintenance plans were undocumented and trying to create a default template maintenance plan. | You can't export them as scripts, but if your intention is to migrate them between server instances then you can import and export them as follows: Connect to Integration Services and expand Stored Packages>MSDB>Maintenance Plans. You can then right click on the plan and select import or export | In MS SQL Server 2005, is there a way to export, the complete maintenance plan of a database as a SQL Script? Currently, if I want to output a SQL script for a table in my database, in Management Studio, I can right click and output a create script. Is there an equivalent to output an SQL script for a database's maintenance plan?# Edit The company I work for has 4 servers, 3 servers and no sign of integration, each one running about 500,000 transactions a day. The original maintenance plans were undocumented and trying to create a default template maintenance plan. | TITLE:
In MS SQL Server 2005, is there a way to export, the complete maintenance plan of a database as a SQL Script?
QUESTION:
Currently, if I want to output a SQL script for a table in my database, in Management Studio, I can right click and output a create script. Is there an equivalent to output an SQL script for a database's maintenance plan?# Edit The company I work for has 4 servers, 3 servers and no sign of integration, each one running about 500,000 transactions a day. The original maintenance plans were undocumented and trying to create a default template maintenance plan.
ANSWER:
You can't export them as scripts, but if your intention is to migrate them between server instances then you can import and export them as follows: Connect to Integration Services and expand Stored Packages>MSDB>Maintenance Plans. You can then right click on the plan and select import or export | [
"sql",
"sql-server",
"sql-server-2005"
] | 3 | 2 | 2,203 | 2 | 0 | 2008-08-28T16:12:06.427000 | 2008-08-28T16:20:07.843000 |
32,709 | 32,778 | Isn't Func<T, bool> and Predicate<T> the same thing after compilation? | Haven't fired up reflector to look at the difference but would one expect to see the exact same compiled code when comparing Func vs. Predicate I would imagine there is no difference as both take a generic parameter and return bool? | They share the same signature, but they're still different types. | Isn't Func<T, bool> and Predicate<T> the same thing after compilation? Haven't fired up reflector to look at the difference but would one expect to see the exact same compiled code when comparing Func vs. Predicate I would imagine there is no difference as both take a generic parameter and return bool? | TITLE:
Isn't Func<T, bool> and Predicate<T> the same thing after compilation?
QUESTION:
Haven't fired up reflector to look at the difference but would one expect to see the exact same compiled code when comparing Func vs. Predicate I would imagine there is no difference as both take a generic parameter and return bool?
ANSWER:
They share the same signature, but they're still different types. | [
"c#",
".net",
"predicate",
"func"
] | 21 | 18 | 3,434 | 4 | 0 | 2008-08-28T16:17:52.090000 | 2008-08-28T16:48:26.357000 |
32,715 | 32,812 | Is there a way to get images to display with ASP.NET and app_offline.htm? | When using the app_offline.htm feature of ASP.NET, it only allows html, but no images. Is there a way to get images to display without having to point them to a different url on another site? | Yes, it just can't come from the site that has the app_offline.htm file. The image would have to be hosted elsewhere. | Is there a way to get images to display with ASP.NET and app_offline.htm? When using the app_offline.htm feature of ASP.NET, it only allows html, but no images. Is there a way to get images to display without having to point them to a different url on another site? | TITLE:
Is there a way to get images to display with ASP.NET and app_offline.htm?
QUESTION:
When using the app_offline.htm feature of ASP.NET, it only allows html, but no images. Is there a way to get images to display without having to point them to a different url on another site?
ANSWER:
Yes, it just can't come from the site that has the app_offline.htm file. The image would have to be hosted elsewhere. | [
"asp.net",
"iis-6"
] | 18 | 14 | 12,687 | 6 | 0 | 2008-08-28T16:20:19.387000 | 2008-08-28T17:03:27.160000 |
32,717 | 188,237 | Out-of-place builds with C# | I just finished setting up an out-of-place build system for our existing C++ code using inherited property sheets, a feature that seems to be specific to the Visual C++ product. Building out-of-place requires that many of the project settings be changed, and the inherited property sheets allowed me to change all the necessary settings just by attaching a property sheet to the project. I am migrating our team from C++/MFC for UI to C# and WPF, but I need to provide the same out-of-place build functionality, hopefully with the same convenience. I cannot seem to find a way to do this with C# projects - I first looked to see if I could reference an MsBuild targets file, but could not find a way to do this. I know I could just use MsBuild for the whole thing, but that seems more complicated than necessary. Is there a way I can define a macro for a directory and use it in the output path, for example? | I'm not quite sure what an "out-of-place" build system is, but if you just need the ability to copy the compiled files (or other resources) to other directories you can do so by tying into the MSBuild build targets. In our projects we move the compiled dlls into lib folders and put the files into the proper locations after a build is complete. To do this we've created a custom build.target file that creates the Target 's, Property 's, and ItemGroup 's that we then use to populate our external output folder. Our custom targets file looks a bit like this: TheProject..\..\..\..\lib\ $(ProjectsLibFolder)$(ProjectName)\$(Configuration)\ false The.csproj file in Visual Studio then integrates with this custom target file:... false In a nutshell, this build script first tells MSBuild to load our custom build script, then adds the compiled file to the LibFiles ItemGroup, and lastly ties our custom build targets, DeleteLibFiles and CopyLibFiles, into the build process. We set this up for each project in our solution so only the files that are updated get deleted/copied and each project is responsible for it's own files (dlls, images, etc). I hope this helps. I apologize if I misunderstood what you mean by out-of-place build system and this is completely useless to you! | Out-of-place builds with C# I just finished setting up an out-of-place build system for our existing C++ code using inherited property sheets, a feature that seems to be specific to the Visual C++ product. Building out-of-place requires that many of the project settings be changed, and the inherited property sheets allowed me to change all the necessary settings just by attaching a property sheet to the project. I am migrating our team from C++/MFC for UI to C# and WPF, but I need to provide the same out-of-place build functionality, hopefully with the same convenience. I cannot seem to find a way to do this with C# projects - I first looked to see if I could reference an MsBuild targets file, but could not find a way to do this. I know I could just use MsBuild for the whole thing, but that seems more complicated than necessary. Is there a way I can define a macro for a directory and use it in the output path, for example? | TITLE:
Out-of-place builds with C#
QUESTION:
I just finished setting up an out-of-place build system for our existing C++ code using inherited property sheets, a feature that seems to be specific to the Visual C++ product. Building out-of-place requires that many of the project settings be changed, and the inherited property sheets allowed me to change all the necessary settings just by attaching a property sheet to the project. I am migrating our team from C++/MFC for UI to C# and WPF, but I need to provide the same out-of-place build functionality, hopefully with the same convenience. I cannot seem to find a way to do this with C# projects - I first looked to see if I could reference an MsBuild targets file, but could not find a way to do this. I know I could just use MsBuild for the whole thing, but that seems more complicated than necessary. Is there a way I can define a macro for a directory and use it in the output path, for example?
ANSWER:
I'm not quite sure what an "out-of-place" build system is, but if you just need the ability to copy the compiled files (or other resources) to other directories you can do so by tying into the MSBuild build targets. In our projects we move the compiled dlls into lib folders and put the files into the proper locations after a build is complete. To do this we've created a custom build.target file that creates the Target 's, Property 's, and ItemGroup 's that we then use to populate our external output folder. Our custom targets file looks a bit like this: TheProject..\..\..\..\lib\ $(ProjectsLibFolder)$(ProjectName)\$(Configuration)\ false The.csproj file in Visual Studio then integrates with this custom target file:... false In a nutshell, this build script first tells MSBuild to load our custom build script, then adds the compiled file to the LibFiles ItemGroup, and lastly ties our custom build targets, DeleteLibFiles and CopyLibFiles, into the build process. We set this up for each project in our solution so only the files that are updated get deleted/copied and each project is responsible for it's own files (dlls, images, etc). I hope this helps. I apologize if I misunderstood what you mean by out-of-place build system and this is completely useless to you! | [
"c#",
"msbuild",
"build-process"
] | 4 | 3 | 1,286 | 3 | 0 | 2008-08-28T16:21:03.800000 | 2008-10-09T17:09:15.907000 |
32,718 | 32,743 | Setting time zone remotely in C# | How do you set the Windows time zone on the local machine programmatically in C#? Using an interactive tool is not an option because the remote units have no user interface or users. The remote machine is running.NET 2.0 and Windows XP Embedded and a local app that communicates with a central server (via web service) for automated direction of its tasks. We can deliver a command to synch to a certain time/zone combination, but what code can be put in the local app to accomplish the change? The equipment is not imaged for specific locations before installation, so in order to use any equipment at any location, we have to be able to synch this information. | SetTimeZoneInformation should do what you need. You'll need to use P/Invoke to get at it. Note also that you'll need to possess and enable the SE_TIME_ZONE_NAME privilege. | Setting time zone remotely in C# How do you set the Windows time zone on the local machine programmatically in C#? Using an interactive tool is not an option because the remote units have no user interface or users. The remote machine is running.NET 2.0 and Windows XP Embedded and a local app that communicates with a central server (via web service) for automated direction of its tasks. We can deliver a command to synch to a certain time/zone combination, but what code can be put in the local app to accomplish the change? The equipment is not imaged for specific locations before installation, so in order to use any equipment at any location, we have to be able to synch this information. | TITLE:
Setting time zone remotely in C#
QUESTION:
How do you set the Windows time zone on the local machine programmatically in C#? Using an interactive tool is not an option because the remote units have no user interface or users. The remote machine is running.NET 2.0 and Windows XP Embedded and a local app that communicates with a central server (via web service) for automated direction of its tasks. We can deliver a command to synch to a certain time/zone combination, but what code can be put in the local app to accomplish the change? The equipment is not imaged for specific locations before installation, so in order to use any equipment at any location, we have to be able to synch this information.
ANSWER:
SetTimeZoneInformation should do what you need. You'll need to use P/Invoke to get at it. Note also that you'll need to possess and enable the SE_TIME_ZONE_NAME privilege. | [
"c#",
".net",
"windows",
"localization",
"timezone"
] | 3 | 3 | 8,122 | 6 | 0 | 2008-08-28T16:21:21.973000 | 2008-08-28T16:34:55.950000 |
32,733 | 32,807 | .NET : Double-click event in TabControl | I would like to intercept the event in a.NET Windows Forms TabControl when the user has changed tab by double-clicking the tab (instead of just single-clicking it). Do you have any idea of how I can do that? | The MouseDoubleClick event of the TabControl seems to respond just fine to double-clicking. The only additional step I would do is set a short timer after the TabIndexChanged event to track that a new tab has been selected and ignore any double-clicks that happen outside the timer. This will prevent double-clicking on the selected tab. | .NET : Double-click event in TabControl I would like to intercept the event in a.NET Windows Forms TabControl when the user has changed tab by double-clicking the tab (instead of just single-clicking it). Do you have any idea of how I can do that? | TITLE:
.NET : Double-click event in TabControl
QUESTION:
I would like to intercept the event in a.NET Windows Forms TabControl when the user has changed tab by double-clicking the tab (instead of just single-clicking it). Do you have any idea of how I can do that?
ANSWER:
The MouseDoubleClick event of the TabControl seems to respond just fine to double-clicking. The only additional step I would do is set a short timer after the TabIndexChanged event to track that a new tab has been selected and ignore any double-clicks that happen outside the timer. This will prevent double-clicking on the selected tab. | [
"c#",
".net",
"vb.net",
"winforms",
"tabcontrol"
] | 5 | 3 | 3,268 | 3 | 0 | 2008-08-28T16:28:25.280000 | 2008-08-28T16:58:31.870000 |
32,744 | 32,776 | What protocols and servers are involved in sending an email, and what are the steps? | For the past few weeks, I've been trying to learn about just how email works. I understand the process of a client receiving mail from a server using POP pretty well. I also understand how a client computer can use SMTP to ask an SMTP server to send a message. However, I'm still missing something... The way I understand it, outgoing mail has to make three trips: Client (gmail user using Thunderbird) to a server (Gmail) First server (Gmail) to second server (Hotmail) Second server (Hotmail) to second client (hotmail user using OS X Mail) As I understand it, step one uses SMTP for the client to communicate. The client authenticates itself somehow (say, with USER and PASS), and then sends a message to the gmail server. However, I don't understand how gmail server transfers the message to the hotmail server. For step three, I'm pretty sure, the hotmail server uses POP to send the message to the hotmail client (using authentication, again). So, the big question is: when I click send Mail sends my message to my gmail server, how does my gmail server forward the message to, say, a hotmail server so my friend can recieve it? Thank you so much! ~Jason Thanks, that's been helpful so far. As I understand it, the first client sends the message to the first server using SMTP, often to an address such as smtp.mail.SOMESERVER.com on port 25 (usually). Then, SOMESERVER uses SMTP again to send the message to RECEIVESERVER.com on port 25 (not smtp.mail.RECEIVESERVER.com or anything fancy). Then, when the recipient asks RECEIVESERVER for its mail, using POP, s/he recieves the message... right? Thanks again (especially to dr-jan), Jason | The SMTP server at Gmail (which accepted the message from Thunderbird) will route the message to the final recipient. It does this by using DNS to find the MX (mail exchanger) record for the domain name part of the destination email address (hotmail.com in this example). The DNS server will return an IP address which the message should be sent to. The server at the destination IP address will hopefully be running SMTP (on the standard port 25) so it can receive the incoming messages. Once the message has been received by the hotmail server, it is stored until the appropriate user logs in and retrieves their messages using POP (or IMAP). Jason - to answer your follow up... Then, SOMESERVER uses SMTP again to send the message to RECEIVESERVER.com on port 25 (not smtp.mail.RECEIVESERVER.com or anything fancy). That's correct - the domain name to send to is taken as everything after the '@' in the email address of the recipient. Often, RECEIVESERVER.com is an alias for something more specific, say something like incoming.RECEIVESERVER.com, (or, indeed, smtp.mail.RECEIVESERVER.com). You can use nslookup to query your local DNS servers (this works in Linux and in a Windows cmd window): nslookup > set type=mx > stackoverflow.com Server: 158.155.25.16 Address: 158.155.25.16#53
Non-authoritative answer: stackoverflow.com mail exchanger = 10 aspmx.l.google.com. stackoverflow.com mail exchanger = 20 alt1.aspmx.l.google.com. stackoverflow.com mail exchanger = 30 alt2.aspmx.l.google.com. stackoverflow.com mail exchanger = 40 aspmx2.googlemail.com. stackoverflow.com mail exchanger = 50 aspmx3.googlemail.com.
Authoritative answers can be found from: aspmx.l.google.com internet address = 64.233.183.114 aspmx.l.google.com internet address = 64.233.183.27 > This shows us that email to anyone at stackoverflow.com should be sent to one of the gmail servers shown above. The Wikipedia article mentioned ( http://en.wikipedia.org/wiki/Mx_record ) discusses the priority numbers shown above (10, 20,..., 50). | What protocols and servers are involved in sending an email, and what are the steps? For the past few weeks, I've been trying to learn about just how email works. I understand the process of a client receiving mail from a server using POP pretty well. I also understand how a client computer can use SMTP to ask an SMTP server to send a message. However, I'm still missing something... The way I understand it, outgoing mail has to make three trips: Client (gmail user using Thunderbird) to a server (Gmail) First server (Gmail) to second server (Hotmail) Second server (Hotmail) to second client (hotmail user using OS X Mail) As I understand it, step one uses SMTP for the client to communicate. The client authenticates itself somehow (say, with USER and PASS), and then sends a message to the gmail server. However, I don't understand how gmail server transfers the message to the hotmail server. For step three, I'm pretty sure, the hotmail server uses POP to send the message to the hotmail client (using authentication, again). So, the big question is: when I click send Mail sends my message to my gmail server, how does my gmail server forward the message to, say, a hotmail server so my friend can recieve it? Thank you so much! ~Jason Thanks, that's been helpful so far. As I understand it, the first client sends the message to the first server using SMTP, often to an address such as smtp.mail.SOMESERVER.com on port 25 (usually). Then, SOMESERVER uses SMTP again to send the message to RECEIVESERVER.com on port 25 (not smtp.mail.RECEIVESERVER.com or anything fancy). Then, when the recipient asks RECEIVESERVER for its mail, using POP, s/he recieves the message... right? Thanks again (especially to dr-jan), Jason | TITLE:
What protocols and servers are involved in sending an email, and what are the steps?
QUESTION:
For the past few weeks, I've been trying to learn about just how email works. I understand the process of a client receiving mail from a server using POP pretty well. I also understand how a client computer can use SMTP to ask an SMTP server to send a message. However, I'm still missing something... The way I understand it, outgoing mail has to make three trips: Client (gmail user using Thunderbird) to a server (Gmail) First server (Gmail) to second server (Hotmail) Second server (Hotmail) to second client (hotmail user using OS X Mail) As I understand it, step one uses SMTP for the client to communicate. The client authenticates itself somehow (say, with USER and PASS), and then sends a message to the gmail server. However, I don't understand how gmail server transfers the message to the hotmail server. For step three, I'm pretty sure, the hotmail server uses POP to send the message to the hotmail client (using authentication, again). So, the big question is: when I click send Mail sends my message to my gmail server, how does my gmail server forward the message to, say, a hotmail server so my friend can recieve it? Thank you so much! ~Jason Thanks, that's been helpful so far. As I understand it, the first client sends the message to the first server using SMTP, often to an address such as smtp.mail.SOMESERVER.com on port 25 (usually). Then, SOMESERVER uses SMTP again to send the message to RECEIVESERVER.com on port 25 (not smtp.mail.RECEIVESERVER.com or anything fancy). Then, when the recipient asks RECEIVESERVER for its mail, using POP, s/he recieves the message... right? Thanks again (especially to dr-jan), Jason
ANSWER:
The SMTP server at Gmail (which accepted the message from Thunderbird) will route the message to the final recipient. It does this by using DNS to find the MX (mail exchanger) record for the domain name part of the destination email address (hotmail.com in this example). The DNS server will return an IP address which the message should be sent to. The server at the destination IP address will hopefully be running SMTP (on the standard port 25) so it can receive the incoming messages. Once the message has been received by the hotmail server, it is stored until the appropriate user logs in and retrieves their messages using POP (or IMAP). Jason - to answer your follow up... Then, SOMESERVER uses SMTP again to send the message to RECEIVESERVER.com on port 25 (not smtp.mail.RECEIVESERVER.com or anything fancy). That's correct - the domain name to send to is taken as everything after the '@' in the email address of the recipient. Often, RECEIVESERVER.com is an alias for something more specific, say something like incoming.RECEIVESERVER.com, (or, indeed, smtp.mail.RECEIVESERVER.com). You can use nslookup to query your local DNS servers (this works in Linux and in a Windows cmd window): nslookup > set type=mx > stackoverflow.com Server: 158.155.25.16 Address: 158.155.25.16#53
Non-authoritative answer: stackoverflow.com mail exchanger = 10 aspmx.l.google.com. stackoverflow.com mail exchanger = 20 alt1.aspmx.l.google.com. stackoverflow.com mail exchanger = 30 alt2.aspmx.l.google.com. stackoverflow.com mail exchanger = 40 aspmx2.googlemail.com. stackoverflow.com mail exchanger = 50 aspmx3.googlemail.com.
Authoritative answers can be found from: aspmx.l.google.com internet address = 64.233.183.114 aspmx.l.google.com internet address = 64.233.183.27 > This shows us that email to anyone at stackoverflow.com should be sent to one of the gmail servers shown above. The Wikipedia article mentioned ( http://en.wikipedia.org/wiki/Mx_record ) discusses the priority numbers shown above (10, 20,..., 50). | [
"email",
"smtp",
"pop3"
] | 15 | 18 | 3,922 | 7 | 0 | 2008-08-28T16:35:52.143000 | 2008-08-28T16:47:51.113000 |
32,747 | 32,749 | How do I get today's date in C# in mm/dd/yyyy format? | How do I get today's date in C# in mm/dd/yyyy format? I need to set a string variable to today's date (preferably without the year), but there's got to be a better way than building it month-/-day one piece at a time. BTW: I'm in the US so M/dd would be correct, e.g. September 11th is 9/11. Note: an answer from kronoz came in that discussed internationalization, and I thought it was awesome enough to mention since I can't make it an 'accepted' answer as well. kronoz's answer | DateTime.Now.ToString("M/d/yyyy"); http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx | How do I get today's date in C# in mm/dd/yyyy format? How do I get today's date in C# in mm/dd/yyyy format? I need to set a string variable to today's date (preferably without the year), but there's got to be a better way than building it month-/-day one piece at a time. BTW: I'm in the US so M/dd would be correct, e.g. September 11th is 9/11. Note: an answer from kronoz came in that discussed internationalization, and I thought it was awesome enough to mention since I can't make it an 'accepted' answer as well. kronoz's answer | TITLE:
How do I get today's date in C# in mm/dd/yyyy format?
QUESTION:
How do I get today's date in C# in mm/dd/yyyy format? I need to set a string variable to today's date (preferably without the year), but there's got to be a better way than building it month-/-day one piece at a time. BTW: I'm in the US so M/dd would be correct, e.g. September 11th is 9/11. Note: an answer from kronoz came in that discussed internationalization, and I thought it was awesome enough to mention since I can't make it an 'accepted' answer as well. kronoz's answer
ANSWER:
DateTime.Now.ToString("M/d/yyyy"); http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx | [
"c#",
"date"
] | 116 | 228 | 407,711 | 8 | 0 | 2008-08-28T16:37:10.860000 | 2008-08-28T16:37:44.680000 |
32,750 | 32,841 | How can I take a byte array of a TIFF image and turn it into a System.Drawing.Image object? | I have a byte[] array, the contents of which represent a TIFF file (as in, if I write out these bytes directly to a file using the BinaryWriter object, it forms a perfectly valid TIFF file) and I'm trying to turn it into a System.Drawing.Image object so that I can use it for later manipulation (feeding into a multipage TIFF object) The problem I'm having is that the commonly accepted code for this task: public Image byteArrayToImage(byte[] byteArrayIn) { MemoryStream ms = new MemoryStream(byteArrayIn); Image returnImage = Image.FromStream(ms, true); return returnImage; } doesn't work for me. The second line of the above method where it calls the Image.FromStream method dies at runtime, saying Parameter Not Valid I believe that the method is choking on the fact that this is a TIFF file but I cannot figure out how to make the FromStream method accept this fact. How do I turn a byte array of a TIFF image into an Image object? Also, like I said the end goal of this is to have a byte array representing a multipage TIFF file, which contains the TIFF files for which I have byte array objects of right now. If there's a much better way to go about doing this, I'm all for it. | Edit: The assumption below is not correct, I had a chance to fire up my IDE later and tested with and without Write and both populated the MemoryStream correctly. I think you need to write to your MemeoryStream first. As if my memory (no pun intended) serves me correctly this: MemoryStream ms = new MemoryStream(byteArrayIn); Creates a memory stream of that size. You then need to write your byte array contents to the memory stream: ms.Write(byteArrayIn, 0, byteArrayIn.Length); See if that fixes it. | How can I take a byte array of a TIFF image and turn it into a System.Drawing.Image object? I have a byte[] array, the contents of which represent a TIFF file (as in, if I write out these bytes directly to a file using the BinaryWriter object, it forms a perfectly valid TIFF file) and I'm trying to turn it into a System.Drawing.Image object so that I can use it for later manipulation (feeding into a multipage TIFF object) The problem I'm having is that the commonly accepted code for this task: public Image byteArrayToImage(byte[] byteArrayIn) { MemoryStream ms = new MemoryStream(byteArrayIn); Image returnImage = Image.FromStream(ms, true); return returnImage; } doesn't work for me. The second line of the above method where it calls the Image.FromStream method dies at runtime, saying Parameter Not Valid I believe that the method is choking on the fact that this is a TIFF file but I cannot figure out how to make the FromStream method accept this fact. How do I turn a byte array of a TIFF image into an Image object? Also, like I said the end goal of this is to have a byte array representing a multipage TIFF file, which contains the TIFF files for which I have byte array objects of right now. If there's a much better way to go about doing this, I'm all for it. | TITLE:
How can I take a byte array of a TIFF image and turn it into a System.Drawing.Image object?
QUESTION:
I have a byte[] array, the contents of which represent a TIFF file (as in, if I write out these bytes directly to a file using the BinaryWriter object, it forms a perfectly valid TIFF file) and I'm trying to turn it into a System.Drawing.Image object so that I can use it for later manipulation (feeding into a multipage TIFF object) The problem I'm having is that the commonly accepted code for this task: public Image byteArrayToImage(byte[] byteArrayIn) { MemoryStream ms = new MemoryStream(byteArrayIn); Image returnImage = Image.FromStream(ms, true); return returnImage; } doesn't work for me. The second line of the above method where it calls the Image.FromStream method dies at runtime, saying Parameter Not Valid I believe that the method is choking on the fact that this is a TIFF file but I cannot figure out how to make the FromStream method accept this fact. How do I turn a byte array of a TIFF image into an Image object? Also, like I said the end goal of this is to have a byte array representing a multipage TIFF file, which contains the TIFF files for which I have byte array objects of right now. If there's a much better way to go about doing this, I'm all for it.
ANSWER:
Edit: The assumption below is not correct, I had a chance to fire up my IDE later and tested with and without Write and both populated the MemoryStream correctly. I think you need to write to your MemeoryStream first. As if my memory (no pun intended) serves me correctly this: MemoryStream ms = new MemoryStream(byteArrayIn); Creates a memory stream of that size. You then need to write your byte array contents to the memory stream: ms.Write(byteArrayIn, 0, byteArrayIn.Length); See if that fixes it. | [
"c#",
".net",
"image",
"tiff"
] | 6 | 2 | 13,332 | 3 | 0 | 2008-08-28T16:38:10.827000 | 2008-08-28T17:15:42.530000 |
32,766 | 32,865 | generation of designer file failed | Every few days VS2008 decides to get mad at me and fails to generate a designer file claiming it cannot find the file specified and that it's missing an assembly. Here's the scenario: The aspx page has a reference to a custom user control (inheriting UserControl) which references another assembly in the backend. There are many other references to this "missing" assembly in other places in code which don't throw errors. rebuilding, updating the source to the clean copy, shouting at the computer, punching the screen, etc all fail to work. Any suggestions? This is quite annoying. | We've had similar problems before, unfortunately I don't remember the exact solution. If your using a "Web Site" project (no project file) then start by checking that both your page and your control both set the ClassName property in the first line of your aspx/ascx file and that you specify the full name of the class including the namespace. Example: <@Control Language="VB" AutoEventWireup="false" ClassName="YourProjectName.YourUserControl" Inherits="YourProjectName.YourUserControl" CodeFile="YourUserControl.ascx.vb" %> Many times not setting all of these will still work but you will get odd compiler errors and behavior in VS. If you using a Web Site Application project try deleting the designer file manually and then right click on your project and choose "Convert from Web Application." This will should recreate the designer file for you. My only other suggestion would be to recreate the page and/or the user control from scratch. | generation of designer file failed Every few days VS2008 decides to get mad at me and fails to generate a designer file claiming it cannot find the file specified and that it's missing an assembly. Here's the scenario: The aspx page has a reference to a custom user control (inheriting UserControl) which references another assembly in the backend. There are many other references to this "missing" assembly in other places in code which don't throw errors. rebuilding, updating the source to the clean copy, shouting at the computer, punching the screen, etc all fail to work. Any suggestions? This is quite annoying. | TITLE:
generation of designer file failed
QUESTION:
Every few days VS2008 decides to get mad at me and fails to generate a designer file claiming it cannot find the file specified and that it's missing an assembly. Here's the scenario: The aspx page has a reference to a custom user control (inheriting UserControl) which references another assembly in the backend. There are many other references to this "missing" assembly in other places in code which don't throw errors. rebuilding, updating the source to the clean copy, shouting at the computer, punching the screen, etc all fail to work. Any suggestions? This is quite annoying.
ANSWER:
We've had similar problems before, unfortunately I don't remember the exact solution. If your using a "Web Site" project (no project file) then start by checking that both your page and your control both set the ClassName property in the first line of your aspx/ascx file and that you specify the full name of the class including the namespace. Example: <@Control Language="VB" AutoEventWireup="false" ClassName="YourProjectName.YourUserControl" Inherits="YourProjectName.YourUserControl" CodeFile="YourUserControl.ascx.vb" %> Many times not setting all of these will still work but you will get odd compiler errors and behavior in VS. If you using a Web Site Application project try deleting the designer file manually and then right click on your project and choose "Convert from Web Application." This will should recreate the designer file for you. My only other suggestion would be to recreate the page and/or the user control from scratch. | [
"visual-studio",
"visual-studio-2008"
] | 7 | 9 | 4,216 | 4 | 0 | 2008-08-28T16:42:42.797000 | 2008-08-28T17:27:42.517000 |
32,777 | 32,785 | What is the best and most complete implementation of Unix system commands for Windows? | I've found a few (unfortunately, they are bookmarked at home and I'm at work, so no links), but I was wondering if anyone had any opinions about any of them (love it, hate it, whatever) so I could make a good decision. I think I'm going to use Cygwin for my Unix commands on Windows, but I'm not sure how well that's going to work, so I would love for alternatives and I'm sure there are people out there interested in this who aren't running Cygwin. | These work very well for me: http://unxutils.sourceforge.net/. Cygwin is not so good on Vista or 64 bit, so I stopped using it a while back. | What is the best and most complete implementation of Unix system commands for Windows? I've found a few (unfortunately, they are bookmarked at home and I'm at work, so no links), but I was wondering if anyone had any opinions about any of them (love it, hate it, whatever) so I could make a good decision. I think I'm going to use Cygwin for my Unix commands on Windows, but I'm not sure how well that's going to work, so I would love for alternatives and I'm sure there are people out there interested in this who aren't running Cygwin. | TITLE:
What is the best and most complete implementation of Unix system commands for Windows?
QUESTION:
I've found a few (unfortunately, they are bookmarked at home and I'm at work, so no links), but I was wondering if anyone had any opinions about any of them (love it, hate it, whatever) so I could make a good decision. I think I'm going to use Cygwin for my Unix commands on Windows, but I'm not sure how well that's going to work, so I would love for alternatives and I'm sure there are people out there interested in this who aren't running Cygwin.
ANSWER:
These work very well for me: http://unxutils.sourceforge.net/. Cygwin is not so good on Vista or 64 bit, so I stopped using it a while back. | [
"windows",
"unix",
"command-line"
] | 15 | 5 | 3,282 | 9 | 0 | 2008-08-28T16:48:23.843000 | 2008-08-28T16:50:57.113000 |
32,780 | 32,797 | Restrict the server access from LAN only | Recently we got a new server at the office purely for testing purposes. It is set up so that we can access it from any computer. However today our ip got blocked from one of our other sites saying that our ip has been suspected of having a virus that sends spam emails. we learned this from the cbl http://cbl.abuseat.org/ So of course we turned the server off to stop this. The problem is the server must be on to continue developing our application and to access the database that is installed on it. Our normal admin is on vacation and is unreachable, and the rest of us are idiots(me included) in this area. We believe that the best solution is to remove it from connecting to the internet but still access it on the lan. If that is a valid solution how would this be done or is there a better way? say blocking specified ports or whatever. | I assume that this server is behind a router? You should be able to block WAN connections to the server on the router and still leave it open to accepting LAN connection. Or you could restrict the IPs that can connect to the server to the development machines on the network. | Restrict the server access from LAN only Recently we got a new server at the office purely for testing purposes. It is set up so that we can access it from any computer. However today our ip got blocked from one of our other sites saying that our ip has been suspected of having a virus that sends spam emails. we learned this from the cbl http://cbl.abuseat.org/ So of course we turned the server off to stop this. The problem is the server must be on to continue developing our application and to access the database that is installed on it. Our normal admin is on vacation and is unreachable, and the rest of us are idiots(me included) in this area. We believe that the best solution is to remove it from connecting to the internet but still access it on the lan. If that is a valid solution how would this be done or is there a better way? say blocking specified ports or whatever. | TITLE:
Restrict the server access from LAN only
QUESTION:
Recently we got a new server at the office purely for testing purposes. It is set up so that we can access it from any computer. However today our ip got blocked from one of our other sites saying that our ip has been suspected of having a virus that sends spam emails. we learned this from the cbl http://cbl.abuseat.org/ So of course we turned the server off to stop this. The problem is the server must be on to continue developing our application and to access the database that is installed on it. Our normal admin is on vacation and is unreachable, and the rest of us are idiots(me included) in this area. We believe that the best solution is to remove it from connecting to the internet but still access it on the lan. If that is a valid solution how would this be done or is there a better way? say blocking specified ports or whatever.
ANSWER:
I assume that this server is behind a router? You should be able to block WAN connections to the server on the router and still leave it open to accepting LAN connection. Or you could restrict the IPs that can connect to the server to the development machines on the network. | [
"server",
"router",
"lan",
"wan"
] | 1 | 1 | 1,350 | 1 | 0 | 2008-08-28T16:48:46.930000 | 2008-08-28T16:54:44.903000 |
32,790 | 33,008 | Alternatives to System.exit(1) | For various reasons calling System.exit is frowned upon when writing Java Applications, so how can I notify the calling process that not everything is going according to plan? Edit: The 1 is a standin for any non-zero exit code. | The use of System.exit is frowned upon when the 'application' is really a sub-application (e.g. servlet, applet) of a larger Java application (server): in this case the System.exit could stop the JVM and hence also all other sub-applications. In this situation, throwing an appropriate exception, which could be caught and handled by the application framework/server is the best option. If the java application is really meant to be run as a standalone application, there is nothing wrong with using System.exit. in this case, setting an exit value is probably the easiest (and also most used) way of communicating failure or success to the parent process. | Alternatives to System.exit(1) For various reasons calling System.exit is frowned upon when writing Java Applications, so how can I notify the calling process that not everything is going according to plan? Edit: The 1 is a standin for any non-zero exit code. | TITLE:
Alternatives to System.exit(1)
QUESTION:
For various reasons calling System.exit is frowned upon when writing Java Applications, so how can I notify the calling process that not everything is going according to plan? Edit: The 1 is a standin for any non-zero exit code.
ANSWER:
The use of System.exit is frowned upon when the 'application' is really a sub-application (e.g. servlet, applet) of a larger Java application (server): in this case the System.exit could stop the JVM and hence also all other sub-applications. In this situation, throwing an appropriate exception, which could be caught and handled by the application framework/server is the best option. If the java application is really meant to be run as a standalone application, there is nothing wrong with using System.exit. in this case, setting an exit value is probably the easiest (and also most used) way of communicating failure or success to the parent process. | [
"java",
"process"
] | 26 | 33 | 22,647 | 9 | 0 | 2008-08-28T16:52:44.067000 | 2008-08-28T18:25:27.760000 |
32,814 | 32,996 | ASP.NET Validators inside an UpdatePanel | I'm using an older version of ASP.NET AJAX due to runtime limitations, Placing a ASP.NET Validator inside of an update panel does not work. Is there a trick to make these work, or do I need to use the ValidatorCallOut control that comes with the AJAX toolkit? | I suspect you are running the original release (RTM) of.NET 2.0. Until early 2007 validator controls were not compatible with UpdatePanels. This was resolved with the SP1 of the.NET Framework. The source of the problem is that UpdatePanel can detect markup changes in your page, but it has no way to track scripts correctly. Validators rely heavily on scripts. During a partial postback, the scripts are either blown away, not updated, or not run when they are meant to. In early betas, MS had the UpdatePanel try to guess what scripts needed to be re-rendered or run. It didn't work very well, and they had to take it out. To get around the immediate problem, Microsoft released a patched version of the validator classes in a new DLL called Validators.DLL, and gave instructions on how to tell ASP.NET to use those classes instead of the real ones. If you Google for that DLL name, you should find more information. See also This blog post. This was a stop-gag measure and you should not use it avoid it if possible. The real solution to the problem came shortly after, in.NET 2.0 SP1. Microsoft introduced a new mechanism to register scripts in SP1, and changed the real validator classes to use that mechanism instead of the older one. Let me give you some details on the changes: Traditionally, you were supposed to register scripts via Page methods such as Page.RegisterStartupScript() and Page.RegisterClientScriptBlock(). The problem is that these methods were not designed for extensibility and UpdatePanel had no way to monitor those calls. In SP1 there is a new property object on the page called Page.ClientScripts. This object has methods to register scripts that are equivalent (and in some ways better) to the original ones. Also, UpdatePanel can monitor these calls, so that it rerenders or calls the methods when appropriate. The older RegisterStartupScript(), etc. methods have been deprecated. They still work, but not inside an UpdatePanel. There is no reason (other than politics, I suppose) to not update your installations to.NET 2.0 SP1. Service Packs carry important fixes. Good luck. | ASP.NET Validators inside an UpdatePanel I'm using an older version of ASP.NET AJAX due to runtime limitations, Placing a ASP.NET Validator inside of an update panel does not work. Is there a trick to make these work, or do I need to use the ValidatorCallOut control that comes with the AJAX toolkit? | TITLE:
ASP.NET Validators inside an UpdatePanel
QUESTION:
I'm using an older version of ASP.NET AJAX due to runtime limitations, Placing a ASP.NET Validator inside of an update panel does not work. Is there a trick to make these work, or do I need to use the ValidatorCallOut control that comes with the AJAX toolkit?
ANSWER:
I suspect you are running the original release (RTM) of.NET 2.0. Until early 2007 validator controls were not compatible with UpdatePanels. This was resolved with the SP1 of the.NET Framework. The source of the problem is that UpdatePanel can detect markup changes in your page, but it has no way to track scripts correctly. Validators rely heavily on scripts. During a partial postback, the scripts are either blown away, not updated, or not run when they are meant to. In early betas, MS had the UpdatePanel try to guess what scripts needed to be re-rendered or run. It didn't work very well, and they had to take it out. To get around the immediate problem, Microsoft released a patched version of the validator classes in a new DLL called Validators.DLL, and gave instructions on how to tell ASP.NET to use those classes instead of the real ones. If you Google for that DLL name, you should find more information. See also This blog post. This was a stop-gag measure and you should not use it avoid it if possible. The real solution to the problem came shortly after, in.NET 2.0 SP1. Microsoft introduced a new mechanism to register scripts in SP1, and changed the real validator classes to use that mechanism instead of the older one. Let me give you some details on the changes: Traditionally, you were supposed to register scripts via Page methods such as Page.RegisterStartupScript() and Page.RegisterClientScriptBlock(). The problem is that these methods were not designed for extensibility and UpdatePanel had no way to monitor those calls. In SP1 there is a new property object on the page called Page.ClientScripts. This object has methods to register scripts that are equivalent (and in some ways better) to the original ones. Also, UpdatePanel can monitor these calls, so that it rerenders or calls the methods when appropriate. The older RegisterStartupScript(), etc. methods have been deprecated. They still work, but not inside an UpdatePanel. There is no reason (other than politics, I suppose) to not update your installations to.NET 2.0 SP1. Service Packs carry important fixes. Good luck. | [
"asp.net",
"asp.net-ajax",
"updatepanel"
] | 14 | 21 | 8,942 | 4 | 0 | 2008-08-28T17:03:59.610000 | 2008-08-28T18:20:00.923000 |
32,824 | 34,004 | Why does HttpCacheability.Private suppress ETags? | While writing a custom IHttpHandler I came across a behavior that I didn't expect concerning the HttpCachePolicy object. My handler calculates and sets an entity-tag (using the SetETag method on the HttpCachePolicy associated with the current response object). If I set the cache-control to public using the SetCacheability method everything works like a charm and the server sends along the e-tag header. If I set it to private the e-tag header will be suppressed. Maybe I just haven't looked hard enough but I haven't seen anything in the HTTP/1.1 spec that would justify this behavior. Why wouldn't you want to send E-Tag to browsers while still prohibiting proxies from storing the data? using System; using System.Web;
public class Handler: IHttpHandler { public void ProcessRequest (HttpContext ctx) { ctx.Response.Cache.SetCacheability(HttpCacheability.Private); ctx.Response.Cache.SetETag("\"static\""); ctx.Response.ContentType = "text/plain"; ctx.Response.Write("Hello World"); }
public bool IsReusable { get { return true; } } } Will return Cache-Control: private Content-Type: text/plain; charset=utf-8 Content-Length: 11 But if we change it to public it'll return Cache-Control: public Content-Type: text/plain; charset=utf-8 Content-Length: 11 Etag: "static" I've run this on the ASP.NET development server and IIS6 so far with the same results. Also I'm unable to explicitly set the ETag using Response.AppendHeader("ETag", "static") Update: It's possible to append the ETag header manually when running in IIS7, I suspect this is caused by the tight integration between ASP.NET and the IIS7 pipeline. Clarification: It's a long question but the core question is this: why does ASP.NET do this, how can I get around it and should I? Update: I'm going to accept Tony's answer since it's essentially correct (go Tony!). I found that if you want to emulate the HttpCacheability.Private fully you can set the cacheability to ServerAndPrivate but you also have call cache. SetOmitVaryStar (true) otherwise the cache will add the Vary: * header to the output and you don't want that. I'll edit that into the answer when I get edit permissions (or if you see this Tony perhaps you could edit your answer to include that call?) | I think you need to use HttpCacheability.ServerAndPrivate That should give you cache-control: private in the headers and let you set an ETag. The documentation on that needs to be a bit better. Edit: Markus found that you also have call cache.SetOmitVaryStar(true) otherwise the cache will add the Vary: * header to the output and you don't want that. | Why does HttpCacheability.Private suppress ETags? While writing a custom IHttpHandler I came across a behavior that I didn't expect concerning the HttpCachePolicy object. My handler calculates and sets an entity-tag (using the SetETag method on the HttpCachePolicy associated with the current response object). If I set the cache-control to public using the SetCacheability method everything works like a charm and the server sends along the e-tag header. If I set it to private the e-tag header will be suppressed. Maybe I just haven't looked hard enough but I haven't seen anything in the HTTP/1.1 spec that would justify this behavior. Why wouldn't you want to send E-Tag to browsers while still prohibiting proxies from storing the data? using System; using System.Web;
public class Handler: IHttpHandler { public void ProcessRequest (HttpContext ctx) { ctx.Response.Cache.SetCacheability(HttpCacheability.Private); ctx.Response.Cache.SetETag("\"static\""); ctx.Response.ContentType = "text/plain"; ctx.Response.Write("Hello World"); }
public bool IsReusable { get { return true; } } } Will return Cache-Control: private Content-Type: text/plain; charset=utf-8 Content-Length: 11 But if we change it to public it'll return Cache-Control: public Content-Type: text/plain; charset=utf-8 Content-Length: 11 Etag: "static" I've run this on the ASP.NET development server and IIS6 so far with the same results. Also I'm unable to explicitly set the ETag using Response.AppendHeader("ETag", "static") Update: It's possible to append the ETag header manually when running in IIS7, I suspect this is caused by the tight integration between ASP.NET and the IIS7 pipeline. Clarification: It's a long question but the core question is this: why does ASP.NET do this, how can I get around it and should I? Update: I'm going to accept Tony's answer since it's essentially correct (go Tony!). I found that if you want to emulate the HttpCacheability.Private fully you can set the cacheability to ServerAndPrivate but you also have call cache. SetOmitVaryStar (true) otherwise the cache will add the Vary: * header to the output and you don't want that. I'll edit that into the answer when I get edit permissions (or if you see this Tony perhaps you could edit your answer to include that call?) | TITLE:
Why does HttpCacheability.Private suppress ETags?
QUESTION:
While writing a custom IHttpHandler I came across a behavior that I didn't expect concerning the HttpCachePolicy object. My handler calculates and sets an entity-tag (using the SetETag method on the HttpCachePolicy associated with the current response object). If I set the cache-control to public using the SetCacheability method everything works like a charm and the server sends along the e-tag header. If I set it to private the e-tag header will be suppressed. Maybe I just haven't looked hard enough but I haven't seen anything in the HTTP/1.1 spec that would justify this behavior. Why wouldn't you want to send E-Tag to browsers while still prohibiting proxies from storing the data? using System; using System.Web;
public class Handler: IHttpHandler { public void ProcessRequest (HttpContext ctx) { ctx.Response.Cache.SetCacheability(HttpCacheability.Private); ctx.Response.Cache.SetETag("\"static\""); ctx.Response.ContentType = "text/plain"; ctx.Response.Write("Hello World"); }
public bool IsReusable { get { return true; } } } Will return Cache-Control: private Content-Type: text/plain; charset=utf-8 Content-Length: 11 But if we change it to public it'll return Cache-Control: public Content-Type: text/plain; charset=utf-8 Content-Length: 11 Etag: "static" I've run this on the ASP.NET development server and IIS6 so far with the same results. Also I'm unable to explicitly set the ETag using Response.AppendHeader("ETag", "static") Update: It's possible to append the ETag header manually when running in IIS7, I suspect this is caused by the tight integration between ASP.NET and the IIS7 pipeline. Clarification: It's a long question but the core question is this: why does ASP.NET do this, how can I get around it and should I? Update: I'm going to accept Tony's answer since it's essentially correct (go Tony!). I found that if you want to emulate the HttpCacheability.Private fully you can set the cacheability to ServerAndPrivate but you also have call cache. SetOmitVaryStar (true) otherwise the cache will add the Vary: * header to the output and you don't want that. I'll edit that into the answer when I get edit permissions (or if you see this Tony perhaps you could edit your answer to include that call?)
ANSWER:
I think you need to use HttpCacheability.ServerAndPrivate That should give you cache-control: private in the headers and let you set an ETag. The documentation on that needs to be a bit better. Edit: Markus found that you also have call cache.SetOmitVaryStar(true) otherwise the cache will add the Vary: * header to the output and you don't want that. | [
"c#",
"asp.net",
"http",
"caching"
] | 25 | 17 | 7,224 | 3 | 0 | 2008-08-28T17:08:58.990000 | 2008-08-29T05:25:27.503000 |
32,835 | 32,859 | XNA Unit Testing | So I'm interested in hearing different thoughts about what is the best way to go about unit testing XNA Game/Applications. Astute googlers can probably figure out why I'm asking, but I didn't want to bias the topic:-) | I would that this question is geared more toward the approach of unit testing in game development. I mean, XNA is a framework. Plug in NUnit, and begin writing test cases while you develop. Here is a post on SO about unit testing a game. It'll give you a little insight into how you need to think while progressing. | XNA Unit Testing So I'm interested in hearing different thoughts about what is the best way to go about unit testing XNA Game/Applications. Astute googlers can probably figure out why I'm asking, but I didn't want to bias the topic:-) | TITLE:
XNA Unit Testing
QUESTION:
So I'm interested in hearing different thoughts about what is the best way to go about unit testing XNA Game/Applications. Astute googlers can probably figure out why I'm asking, but I didn't want to bias the topic:-)
ANSWER:
I would that this question is geared more toward the approach of unit testing in game development. I mean, XNA is a framework. Plug in NUnit, and begin writing test cases while you develop. Here is a post on SO about unit testing a game. It'll give you a little insight into how you need to think while progressing. | [
"unit-testing",
"xna"
] | 10 | 2 | 4,854 | 6 | 0 | 2008-08-28T17:12:57.887000 | 2008-08-28T17:25:52.333000 |
32,845 | 32,995 | Creating System Restore Points - Thoughts? | Is it "taboo" to programatically create system restore points? I would be doing this before I perform a software update. If there is a better method to create a restore point with just my software's files and data, please let me know. I would like a means by which I can get the user back to a known working state if everything goes kaput during an update (closes/kills the update app, power goes out, user pulls the plug, etc.) private void CreateRestorePoint(string description) { ManagementScope oScope = new ManagementScope("\\\\localhost\\root\\default"); ManagementPath oPath = new ManagementPath("SystemRestore"); ObjectGetOptions oGetOp = new ObjectGetOptions(); ManagementClass oProcess = new ManagementClass(oScope, oPath, oGetOp);
ManagementBaseObject oInParams = oProcess.GetMethodParameters("CreateRestorePoint"); oInParams["Description"] = description; oInParams["RestorePointType"] = 12; // MODIFY_SETTINGS oInParams["EventType"] = 100;
ManagementBaseObject oOutParams = oProcess.InvokeMethod("CreateRestorePoint", oInParams, null); } | Is it "taboo" to programatically create system restore points? No. That's why the API is there; so that you can have pseudo-atomic updates of the system. | Creating System Restore Points - Thoughts? Is it "taboo" to programatically create system restore points? I would be doing this before I perform a software update. If there is a better method to create a restore point with just my software's files and data, please let me know. I would like a means by which I can get the user back to a known working state if everything goes kaput during an update (closes/kills the update app, power goes out, user pulls the plug, etc.) private void CreateRestorePoint(string description) { ManagementScope oScope = new ManagementScope("\\\\localhost\\root\\default"); ManagementPath oPath = new ManagementPath("SystemRestore"); ObjectGetOptions oGetOp = new ObjectGetOptions(); ManagementClass oProcess = new ManagementClass(oScope, oPath, oGetOp);
ManagementBaseObject oInParams = oProcess.GetMethodParameters("CreateRestorePoint"); oInParams["Description"] = description; oInParams["RestorePointType"] = 12; // MODIFY_SETTINGS oInParams["EventType"] = 100;
ManagementBaseObject oOutParams = oProcess.InvokeMethod("CreateRestorePoint", oInParams, null); } | TITLE:
Creating System Restore Points - Thoughts?
QUESTION:
Is it "taboo" to programatically create system restore points? I would be doing this before I perform a software update. If there is a better method to create a restore point with just my software's files and data, please let me know. I would like a means by which I can get the user back to a known working state if everything goes kaput during an update (closes/kills the update app, power goes out, user pulls the plug, etc.) private void CreateRestorePoint(string description) { ManagementScope oScope = new ManagementScope("\\\\localhost\\root\\default"); ManagementPath oPath = new ManagementPath("SystemRestore"); ObjectGetOptions oGetOp = new ObjectGetOptions(); ManagementClass oProcess = new ManagementClass(oScope, oPath, oGetOp);
ManagementBaseObject oInParams = oProcess.GetMethodParameters("CreateRestorePoint"); oInParams["Description"] = description; oInParams["RestorePointType"] = 12; // MODIFY_SETTINGS oInParams["EventType"] = 100;
ManagementBaseObject oOutParams = oProcess.InvokeMethod("CreateRestorePoint", oInParams, null); }
ANSWER:
Is it "taboo" to programatically create system restore points? No. That's why the API is there; so that you can have pseudo-atomic updates of the system. | [
"system-restore"
] | 5 | 5 | 1,630 | 6 | 0 | 2008-08-28T17:16:54.650000 | 2008-08-28T18:19:49.850000 |
32,851 | 72,557 | Multicasting, Messaging, ActiveMQ vs. MSMQ? | I'm working on a messaging/notification system for our products. Basic requirements are: Fire and forget Persistent set of messages, possibly updating, to stay there until the sender says to remove them The libraries will be written in C#. Spring.NET just released a milestone build with lots of nice messaging abstraction, which is great - I plan on using it extensively. My basic question comes down to the question of message brokers. My architecture will look something like app -> message broker queue -> server app that listens, dispatches all messages to where they need to go, and handles the life cycle of those long-lived messages -> message broker queue or topic -> listening apps. Finally, the question: Which message broker should I use? I am biased towards ActiveMQ - We used it on our last project and loved it. I can't really think of a single strike against it, except that it's Java, and will require java to be installed on a server somewhere, and that might be a hard sell to some of the people that will be using this service. The other option I've been looking at is MSMQ. I am biased against it for some unknown reason, and it also doesn't seem to have great multicast support. Has anyone used MSMQ for something like this? Any pros or cons, stuff that might sway the vote one way or the other? One last thing, we are using.NET 2.0. | I'm kinda biased as I work on ActiveMQ but pretty much all of benefits listed for MSMQ above also apply to ActiveMQ really. Some more benefits of ActiveMQ include great support for cross language client access and multi protocol support excellent support for enterprise integration patterns a ton of advanced features like exclusive queues and message groups The main downside you mention is that the ActiveMQ broker is written in Java; but you can run it on IKVM as a.net assembly if you really want - or run it as a windows service, or compile it to a DLL/EXE via GCJ. MSMQ may or may not be written in.NET - but it doesn't really matter much how its implemented right? Irrespective of whether you choose MSMQ or ActiveMQ I'd recommend at least considering using the NMS API which as you say is integrated great into Spring.NET. There is an MSMQ implementation of this API as well as implementations for TibCo, ActiveMQ and STOMP which will support any other JMS provider via StompConnect. So by choosing NMS as your API you will avoid lockin to any proprietary technology - and you can then easily switch messaging providers at any point in time; rather than locking your code all into a proprietary API | Multicasting, Messaging, ActiveMQ vs. MSMQ? I'm working on a messaging/notification system for our products. Basic requirements are: Fire and forget Persistent set of messages, possibly updating, to stay there until the sender says to remove them The libraries will be written in C#. Spring.NET just released a milestone build with lots of nice messaging abstraction, which is great - I plan on using it extensively. My basic question comes down to the question of message brokers. My architecture will look something like app -> message broker queue -> server app that listens, dispatches all messages to where they need to go, and handles the life cycle of those long-lived messages -> message broker queue or topic -> listening apps. Finally, the question: Which message broker should I use? I am biased towards ActiveMQ - We used it on our last project and loved it. I can't really think of a single strike against it, except that it's Java, and will require java to be installed on a server somewhere, and that might be a hard sell to some of the people that will be using this service. The other option I've been looking at is MSMQ. I am biased against it for some unknown reason, and it also doesn't seem to have great multicast support. Has anyone used MSMQ for something like this? Any pros or cons, stuff that might sway the vote one way or the other? One last thing, we are using.NET 2.0. | TITLE:
Multicasting, Messaging, ActiveMQ vs. MSMQ?
QUESTION:
I'm working on a messaging/notification system for our products. Basic requirements are: Fire and forget Persistent set of messages, possibly updating, to stay there until the sender says to remove them The libraries will be written in C#. Spring.NET just released a milestone build with lots of nice messaging abstraction, which is great - I plan on using it extensively. My basic question comes down to the question of message brokers. My architecture will look something like app -> message broker queue -> server app that listens, dispatches all messages to where they need to go, and handles the life cycle of those long-lived messages -> message broker queue or topic -> listening apps. Finally, the question: Which message broker should I use? I am biased towards ActiveMQ - We used it on our last project and loved it. I can't really think of a single strike against it, except that it's Java, and will require java to be installed on a server somewhere, and that might be a hard sell to some of the people that will be using this service. The other option I've been looking at is MSMQ. I am biased against it for some unknown reason, and it also doesn't seem to have great multicast support. Has anyone used MSMQ for something like this? Any pros or cons, stuff that might sway the vote one way or the other? One last thing, we are using.NET 2.0.
ANSWER:
I'm kinda biased as I work on ActiveMQ but pretty much all of benefits listed for MSMQ above also apply to ActiveMQ really. Some more benefits of ActiveMQ include great support for cross language client access and multi protocol support excellent support for enterprise integration patterns a ton of advanced features like exclusive queues and message groups The main downside you mention is that the ActiveMQ broker is written in Java; but you can run it on IKVM as a.net assembly if you really want - or run it as a windows service, or compile it to a DLL/EXE via GCJ. MSMQ may or may not be written in.NET - but it doesn't really matter much how its implemented right? Irrespective of whether you choose MSMQ or ActiveMQ I'd recommend at least considering using the NMS API which as you say is integrated great into Spring.NET. There is an MSMQ implementation of this API as well as implementations for TibCo, ActiveMQ and STOMP which will support any other JMS provider via StompConnect. So by choosing NMS as your API you will avoid lockin to any proprietary technology - and you can then easily switch messaging providers at any point in time; rather than locking your code all into a proprietary API | [
"msmq",
"messaging",
"activemq-classic"
] | 20 | 22 | 18,002 | 5 | 0 | 2008-08-28T17:21:21.627000 | 2008-09-16T14:00:06.540000 |
32,871 | 32,980 | How can I resize a swf during runtime to have the browser create html scrollbars? | I have a swf with loads text into a Sprite that resizes based on the content put into - I'd like though for the ones that are longer than the page to have the browser use its native scroll bars rather than handle it in actionscript (very much like http://www.nike.com/nikeskateboarding/v3/...) I did have a look at the stuff nike did but just wasn't able to pull it off. Any idea's? | I've never done it that way around but I think swffit might be able to pull it off. | How can I resize a swf during runtime to have the browser create html scrollbars? I have a swf with loads text into a Sprite that resizes based on the content put into - I'd like though for the ones that are longer than the page to have the browser use its native scroll bars rather than handle it in actionscript (very much like http://www.nike.com/nikeskateboarding/v3/...) I did have a look at the stuff nike did but just wasn't able to pull it off. Any idea's? | TITLE:
How can I resize a swf during runtime to have the browser create html scrollbars?
QUESTION:
I have a swf with loads text into a Sprite that resizes based on the content put into - I'd like though for the ones that are longer than the page to have the browser use its native scroll bars rather than handle it in actionscript (very much like http://www.nike.com/nikeskateboarding/v3/...) I did have a look at the stuff nike did but just wasn't able to pull it off. Any idea's?
ANSWER:
I've never done it that way around but I think swffit might be able to pull it off. | [
"javascript",
"apache-flex",
"actionscript-3",
"flash"
] | 7 | 1 | 4,512 | 5 | 0 | 2008-08-28T17:31:13.960000 | 2008-08-28T18:15:32.527000 |
32,875 | 3,980,775 | Browsers' default CSS stylesheets | Are there any lists of default CSS stylesheets for different browsers? (browser stylesheets in tabular form) I want to know the default font of text areas across all browsers for future reference. | Not tabular, but the source CSS may be helpful if you're looking for something specific: Firefox default HTML stylesheet WebKit default HTML stylesheet You're on your own with IE and Opera though. | Browsers' default CSS stylesheets Are there any lists of default CSS stylesheets for different browsers? (browser stylesheets in tabular form) I want to know the default font of text areas across all browsers for future reference. | TITLE:
Browsers' default CSS stylesheets
QUESTION:
Are there any lists of default CSS stylesheets for different browsers? (browser stylesheets in tabular form) I want to know the default font of text areas across all browsers for future reference.
ANSWER:
Not tabular, but the source CSS may be helpful if you're looking for something specific: Firefox default HTML stylesheet WebKit default HTML stylesheet You're on your own with IE and Opera though. | [
"css",
"browser",
"fonts",
"stylesheet",
"default"
] | 53 | 41 | 38,203 | 6 | 0 | 2008-08-28T17:36:29.080000 | 2010-10-20T17:48:40.120000 |
32,877 | 33,312 | How to remove "VsDebuggerCausalityData" data from SOAP message? | I've got a problem where incoming SOAP messages from one particular client are being marked as invalid and rejected by our XML firewall device. It appears extra payload data is being inserted by Visual Studio; we're thinking the extra data may be causing a problem b/c we're seeing "VsDebuggerCausalityData" in these messages but not in others sent from a different client who is not having a problem. It's a starting point, anyway. The question I have is how can the client remove this extra data and still run from VS? Why is VS putting it in there at all? Thanks. | A quick google reveals that this should get rid of it, get them to add it to the web.config or app.config for their application. The information is debug information that the receiving service can use to help trace things back to the client. (maybe, I am guessing a little) I have proposed a follow up question to determine were the magic switch actually comes from. | How to remove "VsDebuggerCausalityData" data from SOAP message? I've got a problem where incoming SOAP messages from one particular client are being marked as invalid and rejected by our XML firewall device. It appears extra payload data is being inserted by Visual Studio; we're thinking the extra data may be causing a problem b/c we're seeing "VsDebuggerCausalityData" in these messages but not in others sent from a different client who is not having a problem. It's a starting point, anyway. The question I have is how can the client remove this extra data and still run from VS? Why is VS putting it in there at all? Thanks. | TITLE:
How to remove "VsDebuggerCausalityData" data from SOAP message?
QUESTION:
I've got a problem where incoming SOAP messages from one particular client are being marked as invalid and rejected by our XML firewall device. It appears extra payload data is being inserted by Visual Studio; we're thinking the extra data may be causing a problem b/c we're seeing "VsDebuggerCausalityData" in these messages but not in others sent from a different client who is not having a problem. It's a starting point, anyway. The question I have is how can the client remove this extra data and still run from VS? Why is VS putting it in there at all? Thanks.
ANSWER:
A quick google reveals that this should get rid of it, get them to add it to the web.config or app.config for their application. The information is debug information that the receiving service can use to help trace things back to the client. (maybe, I am guessing a little) I have proposed a follow up question to determine were the magic switch actually comes from. | [
"visual-studio",
"web-services",
"soap"
] | 20 | 11 | 14,970 | 5 | 0 | 2008-08-28T17:38:07.907000 | 2008-08-28T20:27:38.450000 |
32,897 | 32,916 | Do Java multi-line comments account for strings? | This question would probably apply equally as well to other languages with C-like multi-line comments. Here's the problem I'm encountering. I'm working with Java code in Eclipse, and I wanted to comment out a block of code. However, there is a string that contains the character sequence "*/", and Eclipse thinks that the comment should end there, even though it is inside a string. It gives me tons of errors and fails to build. /*... some Java code...... "... */..."...... more Java code... */ Does the Java specification match with Eclipse's interpretation of my multi-line comment? I would like to think that Java and/or Eclipse would account for this sort of thing. | Eclipse is correct. There is no interpretation context inside a comment (no escaping, etc). See JLS §3.7. | Do Java multi-line comments account for strings? This question would probably apply equally as well to other languages with C-like multi-line comments. Here's the problem I'm encountering. I'm working with Java code in Eclipse, and I wanted to comment out a block of code. However, there is a string that contains the character sequence "*/", and Eclipse thinks that the comment should end there, even though it is inside a string. It gives me tons of errors and fails to build. /*... some Java code...... "... */..."...... more Java code... */ Does the Java specification match with Eclipse's interpretation of my multi-line comment? I would like to think that Java and/or Eclipse would account for this sort of thing. | TITLE:
Do Java multi-line comments account for strings?
QUESTION:
This question would probably apply equally as well to other languages with C-like multi-line comments. Here's the problem I'm encountering. I'm working with Java code in Eclipse, and I wanted to comment out a block of code. However, there is a string that contains the character sequence "*/", and Eclipse thinks that the comment should end there, even though it is inside a string. It gives me tons of errors and fails to build. /*... some Java code...... "... */..."...... more Java code... */ Does the Java specification match with Eclipse's interpretation of my multi-line comment? I would like to think that Java and/or Eclipse would account for this sort of thing.
ANSWER:
Eclipse is correct. There is no interpretation context inside a comment (no escaping, etc). See JLS §3.7. | [
"java",
"eclipse",
"comments"
] | 5 | 9 | 1,551 | 6 | 0 | 2008-08-28T17:47:56.570000 | 2008-08-28T17:54:34.947000 |
32,899 | 32,939 | How do you generate dynamic (parameterized) unit tests in Python? | I have some kind of test data and want to create a unit test for each item. My first idea was to do it like this: import unittest
l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]]
class TestSequence(unittest.TestCase): def testsample(self): for name, a,b in l: print "test", name self.assertEqual(a,b)
if __name__ == '__main__': unittest.main() The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions? | This is called "parametrization". There are several tools that support this approach. E.g.: pytest's decorator parameterized The resulting code looks like this: from parameterized import parameterized
class TestSequence(unittest.TestCase): @parameterized.expand([ ["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"], ]) def test_sequence(self, name, a, b): self.assertEqual(a,b) Which will generate the tests: test_sequence_0_foo (__main__.TestSequence)... ok test_sequence_1_bar (__main__.TestSequence)... FAIL test_sequence_2_lee (__main__.TestSequence)... ok
====================================================================== FAIL: test_sequence_1_bar (__main__.TestSequence) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/parameterized/parameterized.py", line 233, in standalone_func = lambda *a: func(*(a + p.args), **p.kwargs) File "x.py", line 12, in test_sequence self.assertEqual(a,b) AssertionError: 'a'!= 'b' For historical reasons I'll leave the original answer circa 2008): I use something like this: import unittest
l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]]
class TestSequense(unittest.TestCase): pass
def test_generator(a, b): def test(self): self.assertEqual(a,b) return test
if __name__ == '__main__': for t in l: test_name = 'test_%s' % t[0] test = test_generator(t[1], t[2]) setattr(TestSequense, test_name, test) unittest.main() | How do you generate dynamic (parameterized) unit tests in Python? I have some kind of test data and want to create a unit test for each item. My first idea was to do it like this: import unittest
l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]]
class TestSequence(unittest.TestCase): def testsample(self): for name, a,b in l: print "test", name self.assertEqual(a,b)
if __name__ == '__main__': unittest.main() The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions? | TITLE:
How do you generate dynamic (parameterized) unit tests in Python?
QUESTION:
I have some kind of test data and want to create a unit test for each item. My first idea was to do it like this: import unittest
l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]]
class TestSequence(unittest.TestCase): def testsample(self): for name, a,b in l: print "test", name self.assertEqual(a,b)
if __name__ == '__main__': unittest.main() The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions?
ANSWER:
This is called "parametrization". There are several tools that support this approach. E.g.: pytest's decorator parameterized The resulting code looks like this: from parameterized import parameterized
class TestSequence(unittest.TestCase): @parameterized.expand([ ["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"], ]) def test_sequence(self, name, a, b): self.assertEqual(a,b) Which will generate the tests: test_sequence_0_foo (__main__.TestSequence)... ok test_sequence_1_bar (__main__.TestSequence)... FAIL test_sequence_2_lee (__main__.TestSequence)... ok
====================================================================== FAIL: test_sequence_1_bar (__main__.TestSequence) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/parameterized/parameterized.py", line 233, in standalone_func = lambda *a: func(*(a + p.args), **p.kwargs) File "x.py", line 12, in test_sequence self.assertEqual(a,b) AssertionError: 'a'!= 'b' For historical reasons I'll leave the original answer circa 2008): I use something like this: import unittest
l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]]
class TestSequense(unittest.TestCase): pass
def test_generator(a, b): def test(self): self.assertEqual(a,b) return test
if __name__ == '__main__': for t in l: test_name = 'test_%s' % t[0] test = test_generator(t[1], t[2]) setattr(TestSequense, test_name, test) unittest.main() | [
"python",
"unit-testing",
"parameterized-unit-test"
] | 376 | 301 | 225,311 | 25 | 0 | 2008-08-28T17:49:02.293000 | 2008-08-28T18:02:33.027000 |
32,914 | 32,936 | Is there a way to render svg data in a swf at runtime? | I'd like to render to svg data in a swf at runtime (not in Flex - not using degrafa) - how would I go about doing that? | The Ajaxian blog had a post about this today. http://ajaxian.com/archives/the-state-of-svg-browser-support-using-flash-for-svg-in-internet-explorer | Is there a way to render svg data in a swf at runtime? I'd like to render to svg data in a swf at runtime (not in Flex - not using degrafa) - how would I go about doing that? | TITLE:
Is there a way to render svg data in a swf at runtime?
QUESTION:
I'd like to render to svg data in a swf at runtime (not in Flex - not using degrafa) - how would I go about doing that?
ANSWER:
The Ajaxian blog had a post about this today. http://ajaxian.com/archives/the-state-of-svg-browser-support-using-flash-for-svg-in-internet-explorer | [
"actionscript-3",
"flash",
"svg"
] | 3 | 1 | 4,912 | 2 | 0 | 2008-08-28T17:54:10.957000 | 2008-08-28T18:00:42.873000 |
32,930 | 58,758 | What is a good dvd burning component for Windows or .Net? | I'd like to add dvd burning functionality to my.Net app (running on Windows Server 2003), are there any good components available? I've used the NeroCOM sdk that used to come with Nero but they no longer support the sdk in the latest versions of Nero. I learned that Microsoft has created an IMAPI2 upgrade for Windows XP/2003 and there is an example project at CodeProject but not having used it myself I can't say how easy/reliable it is to use. I'm not really worried about burning audio/video to DVD as this is for file backup purposes only. | I've used the code from the codeproject article and it works pretty well. It's a nice wrapper around the IMAPI2, so as longs as IMAPI2 supports what you need to do, the.NET wrapper will do it. | What is a good dvd burning component for Windows or .Net? I'd like to add dvd burning functionality to my.Net app (running on Windows Server 2003), are there any good components available? I've used the NeroCOM sdk that used to come with Nero but they no longer support the sdk in the latest versions of Nero. I learned that Microsoft has created an IMAPI2 upgrade for Windows XP/2003 and there is an example project at CodeProject but not having used it myself I can't say how easy/reliable it is to use. I'm not really worried about burning audio/video to DVD as this is for file backup purposes only. | TITLE:
What is a good dvd burning component for Windows or .Net?
QUESTION:
I'd like to add dvd burning functionality to my.Net app (running on Windows Server 2003), are there any good components available? I've used the NeroCOM sdk that used to come with Nero but they no longer support the sdk in the latest versions of Nero. I learned that Microsoft has created an IMAPI2 upgrade for Windows XP/2003 and there is an example project at CodeProject but not having used it myself I can't say how easy/reliable it is to use. I'm not really worried about burning audio/video to DVD as this is for file backup purposes only.
ANSWER:
I've used the code from the codeproject article and it works pretty well. It's a nice wrapper around the IMAPI2, so as longs as IMAPI2 supports what you need to do, the.NET wrapper will do it. | [
".net",
"windows",
"components",
"dvd"
] | 8 | 2 | 1,610 | 4 | 0 | 2008-08-28T17:59:11.567000 | 2008-09-12T11:45:42.620000 |
32,937 | 33,234 | Shorthand conditional in C# similar to SQL 'in' keyword | In C# is there a shorthand way to write this: public static bool IsAllowed(int userID) { return (userID == Personnel.JohnDoe || userID == Personnel.JaneDoe...); } Like: public static bool IsAllowed(int userID) { return (userID in Personnel.JohnDoe, Personnel.JaneDoe...); } I know I could also use switch, but there are probably 50 or so functions like this I have to write (porting a classic ASP site over to ASP.NET) so I'd like to keep them as short as possible. | How about this? public static class Extensions { public static bool In (this T testValue, params T[] values) { return values.Contains(testValue); } } Usage: Personnel userId = Personnel.JohnDoe;
if (userId.In(Personnel.JohnDoe, Personnel.JaneDoe)) { // Do something } I can't claim credit for this, but I also can't remember where I saw it. So, credit to you, anonymous Internet stranger. | Shorthand conditional in C# similar to SQL 'in' keyword In C# is there a shorthand way to write this: public static bool IsAllowed(int userID) { return (userID == Personnel.JohnDoe || userID == Personnel.JaneDoe...); } Like: public static bool IsAllowed(int userID) { return (userID in Personnel.JohnDoe, Personnel.JaneDoe...); } I know I could also use switch, but there are probably 50 or so functions like this I have to write (porting a classic ASP site over to ASP.NET) so I'd like to keep them as short as possible. | TITLE:
Shorthand conditional in C# similar to SQL 'in' keyword
QUESTION:
In C# is there a shorthand way to write this: public static bool IsAllowed(int userID) { return (userID == Personnel.JohnDoe || userID == Personnel.JaneDoe...); } Like: public static bool IsAllowed(int userID) { return (userID in Personnel.JohnDoe, Personnel.JaneDoe...); } I know I could also use switch, but there are probably 50 or so functions like this I have to write (porting a classic ASP site over to ASP.NET) so I'd like to keep them as short as possible.
ANSWER:
How about this? public static class Extensions { public static bool In (this T testValue, params T[] values) { return values.Contains(testValue); } } Usage: Personnel userId = Personnel.JohnDoe;
if (userId.In(Personnel.JohnDoe, Personnel.JaneDoe)) { // Do something } I can't claim credit for this, but I also can't remember where I saw it. So, credit to you, anonymous Internet stranger. | [
"c#",
"lambda",
"conditional-statements",
"if-statement"
] | 11 | 13 | 2,569 | 8 | 0 | 2008-08-28T18:01:42.763000 | 2008-08-28T19:51:51.407000 |
32,941 | 344,461 | SQL Server 2008 Reporting Services Control | Is the Sql Server 2008 control available for download? Does it yet support the 2008 RDL schema? | The ReportViewer control, http://www.microsoft.com/downloads/details.aspx?FamilyID=cc96c246-61e5-4d9e-bb5f-416d75a1b9ef&DisplayLang=en, supports 2005 RDL using LocalMode (ReportViewer.LocalReport) and 2008 from a Server (ReportViewer.ServerReport). | SQL Server 2008 Reporting Services Control Is the Sql Server 2008 control available for download? Does it yet support the 2008 RDL schema? | TITLE:
SQL Server 2008 Reporting Services Control
QUESTION:
Is the Sql Server 2008 control available for download? Does it yet support the 2008 RDL schema?
ANSWER:
The ReportViewer control, http://www.microsoft.com/downloads/details.aspx?FamilyID=cc96c246-61e5-4d9e-bb5f-416d75a1b9ef&DisplayLang=en, supports 2005 RDL using LocalMode (ReportViewer.LocalReport) and 2008 from a Server (ReportViewer.ServerReport). | [
"sql-server",
"reporting-services"
] | 1 | 0 | 516 | 3 | 0 | 2008-08-28T18:03:36.097000 | 2008-12-05T16:47:25.180000 |
32,964 | 32,976 | Should a wireless network be open? | Obviously there are security reasons to close a wireless network and it's not fun if someone is stealing your bandwidth. That would be a serious problem? To address the first concern: Does a device on the same wireless network have any special privileges or access that an other device on the internet has? Assumptions: Wireless network is connected to the internet The second seems like a community issue. If your neighbor is stealing bandwidth, you'd act just as if he were "borrowing" water or electricity. First, Talk to him about the problem and if that doesn't work, go to the authorities or lock stuff up. Am I missing something? | Bruce Schneier is famous for running an open wireless network at home ( see here ). He does it for two reasons: To be neighborly (you'd let your neighbor borrow a cup of sugar, wouldn't you? Why not a few megabits?) To keep away from the false sense of security that a firewall gives you. In other words, it forces him to make sure his hosts are secure. Personally, I would never run an open wireless network for one reason: accountability. If someone does something illegal on my network, I don't want to be held accountable. | Should a wireless network be open? Obviously there are security reasons to close a wireless network and it's not fun if someone is stealing your bandwidth. That would be a serious problem? To address the first concern: Does a device on the same wireless network have any special privileges or access that an other device on the internet has? Assumptions: Wireless network is connected to the internet The second seems like a community issue. If your neighbor is stealing bandwidth, you'd act just as if he were "borrowing" water or electricity. First, Talk to him about the problem and if that doesn't work, go to the authorities or lock stuff up. Am I missing something? | TITLE:
Should a wireless network be open?
QUESTION:
Obviously there are security reasons to close a wireless network and it's not fun if someone is stealing your bandwidth. That would be a serious problem? To address the first concern: Does a device on the same wireless network have any special privileges or access that an other device on the internet has? Assumptions: Wireless network is connected to the internet The second seems like a community issue. If your neighbor is stealing bandwidth, you'd act just as if he were "borrowing" water or electricity. First, Talk to him about the problem and if that doesn't work, go to the authorities or lock stuff up. Am I missing something?
ANSWER:
Bruce Schneier is famous for running an open wireless network at home ( see here ). He does it for two reasons: To be neighborly (you'd let your neighbor borrow a cup of sugar, wouldn't you? Why not a few megabits?) To keep away from the false sense of security that a firewall gives you. In other words, it forces him to make sure his hosts are secure. Personally, I would never run an open wireless network for one reason: accountability. If someone does something illegal on my network, I don't want to be held accountable. | [
"security",
"networking",
"wireless"
] | 10 | 16 | 1,714 | 16 | 0 | 2008-08-28T18:11:55.343000 | 2008-08-28T18:14:48.473000 |
32,986 | 33,256 | NSEnumerator performance vs for loop in Cocoa | I know that if you have a loop that modifies the count of the items in the loop, using the NSEnumerator on a set is the best way to make sure your code blows up, however I would like to understand the performance tradeoffs between the NSEnumerator class and just an old school for loop | Using the new for (... in...) syntax in Objective-C 2.0 is generally the fastest way to iterate over a collection because it can maintain a buffer on the stack and get batches of items into it. Using NSEnumerator is generally the slowest way because it often copies the collection being iterated; for immutable collections this can be cheap (equivalent to -retain ) but for mutable collections it can cause an immutable copy to be created. Doing your own iteration — for example, using -[NSArray objectAtIndex:] — will generally fall somewhere in between because while you won't have the potential copying overhead, you also won't be getting batches of objects from the underlying collection. (PS - This question should be tagged as Objective-C, not C, since NSEnumerator is a Cocoa class and the new for (... in...) syntax is specific to Objective-C.) | NSEnumerator performance vs for loop in Cocoa I know that if you have a loop that modifies the count of the items in the loop, using the NSEnumerator on a set is the best way to make sure your code blows up, however I would like to understand the performance tradeoffs between the NSEnumerator class and just an old school for loop | TITLE:
NSEnumerator performance vs for loop in Cocoa
QUESTION:
I know that if you have a loop that modifies the count of the items in the loop, using the NSEnumerator on a set is the best way to make sure your code blows up, however I would like to understand the performance tradeoffs between the NSEnumerator class and just an old school for loop
ANSWER:
Using the new for (... in...) syntax in Objective-C 2.0 is generally the fastest way to iterate over a collection because it can maintain a buffer on the stack and get batches of items into it. Using NSEnumerator is generally the slowest way because it often copies the collection being iterated; for immutable collections this can be cheap (equivalent to -retain ) but for mutable collections it can cause an immutable copy to be created. Doing your own iteration — for example, using -[NSArray objectAtIndex:] — will generally fall somewhere in between because while you won't have the potential copying overhead, you also won't be getting batches of objects from the underlying collection. (PS - This question should be tagged as Objective-C, not C, since NSEnumerator is a Cocoa class and the new for (... in...) syntax is specific to Objective-C.) | [
"objective-c",
"cocoa",
"nsenumerator"
] | 19 | 28 | 7,070 | 3 | 0 | 2008-08-28T18:16:54.443000 | 2008-08-28T19:59:48.500000 |
33,034 | 33,059 | How do banks remember "your computer"? | As many of you probably know, online banks nowadays have a security system whereby you are asked some personal questions before you even enter your password. Once you have answered them, you can choose for the bank to "remember this computer" so that in the future you can login by only entering your password. How does the "remember this computer" part work? I know it cannot be cookies, because the feature still works despite the fact that I clear all of my cookies. I thought it might be by IP address, but my friend with a dynamic IP claims it works for him, too (but maybe he's wrong). He thought it was MAC address or something, but I strongly doubt that! So, is there a concept of https-only cookies that I don't clear? Finally, the programming part of the question: how can I do something similar myself in, say, PHP? | In fact they most probably use cookies. An alternative for them would be to use " flash cookies " (officially called " Local Shared Objects "). They are similar to cookies in that they are tied to a website and have an upper size limit, but they are maintained by the flash player, so they are invisible to any browser tools. To clear them (and test this theory), you can use the instructions provided by Adobe. An other nifty (or maybe worrying, depending on your viewpoint) feature is that the LSO storage is shared by all browsers, so using LSO you can identify users even if they switched browser (as long as they are logged in as the same user). | How do banks remember "your computer"? As many of you probably know, online banks nowadays have a security system whereby you are asked some personal questions before you even enter your password. Once you have answered them, you can choose for the bank to "remember this computer" so that in the future you can login by only entering your password. How does the "remember this computer" part work? I know it cannot be cookies, because the feature still works despite the fact that I clear all of my cookies. I thought it might be by IP address, but my friend with a dynamic IP claims it works for him, too (but maybe he's wrong). He thought it was MAC address or something, but I strongly doubt that! So, is there a concept of https-only cookies that I don't clear? Finally, the programming part of the question: how can I do something similar myself in, say, PHP? | TITLE:
How do banks remember "your computer"?
QUESTION:
As many of you probably know, online banks nowadays have a security system whereby you are asked some personal questions before you even enter your password. Once you have answered them, you can choose for the bank to "remember this computer" so that in the future you can login by only entering your password. How does the "remember this computer" part work? I know it cannot be cookies, because the feature still works despite the fact that I clear all of my cookies. I thought it might be by IP address, but my friend with a dynamic IP claims it works for him, too (but maybe he's wrong). He thought it was MAC address or something, but I strongly doubt that! So, is there a concept of https-only cookies that I don't clear? Finally, the programming part of the question: how can I do something similar myself in, say, PHP?
ANSWER:
In fact they most probably use cookies. An alternative for them would be to use " flash cookies " (officially called " Local Shared Objects "). They are similar to cookies in that they are tied to a website and have an upper size limit, but they are maintained by the flash player, so they are invisible to any browser tools. To clear them (and test this theory), you can use the instructions provided by Adobe. An other nifty (or maybe worrying, depending on your viewpoint) feature is that the LSO storage is shared by all browsers, so using LSO you can identify users even if they switched browser (as long as they are logged in as the same user). | [
"https",
"onlinebanking",
"sessiontracking"
] | 24 | 20 | 13,064 | 10 | 0 | 2008-08-28T18:37:07.513000 | 2008-08-28T18:45:05.903000 |
33,042 | 33,071 | How can I measure CppUnit test coverage (on win32 and Unix)? | I have a very large code base that contains extensive unit tests (using CppUnit). I need to work out what percentage of the code is exercised by these tests, and (ideally) generate some sort of report that tells me on a per-library or per-file basis, how much of the code was exercised. Here's the kicker: this has to run completely unnatended (eventually inside a continuous integration build), and has to be cross platform (well, WIN32 and *nix at least). Can anyone suggest a tool, or set of tools that can help me do this? I can't change away from CppUnit (nor would I want to - it kicks ass), but otherwise I'm eager to hear any recommendations you might have. Cheers, | Which tool should I use? This article describes another developers frustrations searching for C++ code coverage tools. The author's final solution was Bullseye Coverage. Bullseye Coverage features: Cross Platform Support (win32, unix, and embedded), (supports linux gcc compilers and MSVC6) Easy to use (up and running in a few hours). Provides "best" metrics: Function Coverage and Condition/Decision Coverage. Uses source code instrumentation. As for hooking into your continuous integration, it depends on which CI solution you use, but you can likely hook the instrumentation / coverage measurement steps into the make file you use for automated testing. Testing Linux vs Windows? So long as all your tests run correctly in both environments, you should be fine measuring coverage on one or the other. (Though Bullseye appears to support both platforms ). But why aren't you doing continuous integration builds in both environments?? If you deliver to clients in both environments then you need to be testing in both. For that reason, it sounds like you might need to have two continuous build servers set up, one for a linux build and one for a windows build. Perhaps this can be easily accomplished with some virtualization software like vmware or virtualbox. You may not need to run code coverage metrics on both OSs, but you should definitely be running your unit tests on both. | How can I measure CppUnit test coverage (on win32 and Unix)? I have a very large code base that contains extensive unit tests (using CppUnit). I need to work out what percentage of the code is exercised by these tests, and (ideally) generate some sort of report that tells me on a per-library or per-file basis, how much of the code was exercised. Here's the kicker: this has to run completely unnatended (eventually inside a continuous integration build), and has to be cross platform (well, WIN32 and *nix at least). Can anyone suggest a tool, or set of tools that can help me do this? I can't change away from CppUnit (nor would I want to - it kicks ass), but otherwise I'm eager to hear any recommendations you might have. Cheers, | TITLE:
How can I measure CppUnit test coverage (on win32 and Unix)?
QUESTION:
I have a very large code base that contains extensive unit tests (using CppUnit). I need to work out what percentage of the code is exercised by these tests, and (ideally) generate some sort of report that tells me on a per-library or per-file basis, how much of the code was exercised. Here's the kicker: this has to run completely unnatended (eventually inside a continuous integration build), and has to be cross platform (well, WIN32 and *nix at least). Can anyone suggest a tool, or set of tools that can help me do this? I can't change away from CppUnit (nor would I want to - it kicks ass), but otherwise I'm eager to hear any recommendations you might have. Cheers,
ANSWER:
Which tool should I use? This article describes another developers frustrations searching for C++ code coverage tools. The author's final solution was Bullseye Coverage. Bullseye Coverage features: Cross Platform Support (win32, unix, and embedded), (supports linux gcc compilers and MSVC6) Easy to use (up and running in a few hours). Provides "best" metrics: Function Coverage and Condition/Decision Coverage. Uses source code instrumentation. As for hooking into your continuous integration, it depends on which CI solution you use, but you can likely hook the instrumentation / coverage measurement steps into the make file you use for automated testing. Testing Linux vs Windows? So long as all your tests run correctly in both environments, you should be fine measuring coverage on one or the other. (Though Bullseye appears to support both platforms ). But why aren't you doing continuous integration builds in both environments?? If you deliver to clients in both environments then you need to be testing in both. For that reason, it sounds like you might need to have two continuous build servers set up, one for a linux build and one for a windows build. Perhaps this can be easily accomplished with some virtualization software like vmware or virtualbox. You may not need to run code coverage metrics on both OSs, but you should definitely be running your unit tests on both. | [
"c++",
"unit-testing",
"cross-platform",
"code-coverage",
"cppunit"
] | 21 | 14 | 22,912 | 5 | 0 | 2008-08-28T18:40:00.033000 | 2008-08-28T18:49:37.500000 |
33,048 | 130,114 | How would you test observers with rSpec in a Ruby on Rails application? | Suppose you have an ActiveRecord::Observer in one of your Ruby on Rails applications - how do you test this observer with rSpec? | You are on the right track, but I have run into a number of frustrating unexpected message errors when using rSpec, observers, and mock objects. When I am spec testing my model, I don't want to have to handle observer behavior in my message expectations. In your example, there isn't a really good way to spec "set_status" on the model without knowledge of what the observer is going to do to it. Therefore, I like to use the "No Peeping Toms" plugin. Given your code above and using the No Peeping Toms plugin, I would spec the model like this: describe Person do it "should set status correctly" do @p = Person.new(:status => "foo") @p.set_status("bar") @p.save @p.status.should eql("bar") end end You can spec your model code without having to worry that there is an observer out there that is going to come in and clobber your value. You'd spec that separately in the person_observer_spec like this: describe PersonObserver do it "should clobber the status field" do @p = mock_model(Person,:status => "foo") @obs = PersonObserver.instance @p.should_receive(:set_status).with("aha!") @obs.after_save end end If you REALLY REALLY want to test the coupled Model and Observer class, you can do it like this: describe Person do it "should register a status change with the person observer turned on" do Person.with_observers(:person_observer) do lambda { @p = Person.new; @p.save }.should change(@p,:status).to("aha!) end end end 99% of the time, I'd rather spec test with the observers turned off. It's just easier that way. | How would you test observers with rSpec in a Ruby on Rails application? Suppose you have an ActiveRecord::Observer in one of your Ruby on Rails applications - how do you test this observer with rSpec? | TITLE:
How would you test observers with rSpec in a Ruby on Rails application?
QUESTION:
Suppose you have an ActiveRecord::Observer in one of your Ruby on Rails applications - how do you test this observer with rSpec?
ANSWER:
You are on the right track, but I have run into a number of frustrating unexpected message errors when using rSpec, observers, and mock objects. When I am spec testing my model, I don't want to have to handle observer behavior in my message expectations. In your example, there isn't a really good way to spec "set_status" on the model without knowledge of what the observer is going to do to it. Therefore, I like to use the "No Peeping Toms" plugin. Given your code above and using the No Peeping Toms plugin, I would spec the model like this: describe Person do it "should set status correctly" do @p = Person.new(:status => "foo") @p.set_status("bar") @p.save @p.status.should eql("bar") end end You can spec your model code without having to worry that there is an observer out there that is going to come in and clobber your value. You'd spec that separately in the person_observer_spec like this: describe PersonObserver do it "should clobber the status field" do @p = mock_model(Person,:status => "foo") @obs = PersonObserver.instance @p.should_receive(:set_status).with("aha!") @obs.after_save end end If you REALLY REALLY want to test the coupled Model and Observer class, you can do it like this: describe Person do it "should register a status change with the person observer turned on" do Person.with_observers(:person_observer) do lambda { @p = Person.new; @p.save }.should change(@p,:status).to("aha!) end end end 99% of the time, I'd rather spec test with the observers turned off. It's just easier that way. | [
"ruby-on-rails",
"ruby",
"activerecord",
"rspec",
"observer-pattern"
] | 38 | 35 | 13,192 | 4 | 0 | 2008-08-28T18:41:21.920000 | 2008-09-24T21:32:48.650000 |
33,055 | 33,064 | SVN repository backup strategies | What methods are available for backing up repositories in a Windows environment? | You could use something like (Linux): svnadmin dump repositorypath | gzip > backupname.svn.gz Since Windows does not support GZip it is just: svnadmin dump repositorypath > backupname.svn | SVN repository backup strategies What methods are available for backing up repositories in a Windows environment? | TITLE:
SVN repository backup strategies
QUESTION:
What methods are available for backing up repositories in a Windows environment?
ANSWER:
You could use something like (Linux): svnadmin dump repositorypath | gzip > backupname.svn.gz Since Windows does not support GZip it is just: svnadmin dump repositorypath > backupname.svn | [
"windows",
"svn",
"backup"
] | 197 | 181 | 145,424 | 19 | 0 | 2008-08-28T18:43:59.480000 | 2008-08-28T18:46:35.447000 |
33,063 | 33,112 | Looking for Regex to find quoted newlines in a big string (for C#) | I have a big string (let's call it a CSV file, though it isn't actually one, it'll just be easier for now) that I have to parse in C# code. The first step of the parsing process splits the file into individual lines by just using a StreamReader object and calling ReadLine until it's through the file. However, any given line might contain a quoted (in single quotes) literal with embedded newlines. I need to find those newlines and convert them temporarily into some other kind of token or escape sequence until I've split the file into an array of lines..then I can change them back. Example input data: 1,2,10,99,'Some text without a newline', true, false, 90 2,1,11,98,'This text has an embedded newline and continues here', true, true, 90 I could write all of the C# code needed to do this by using string.IndexOf to find the quoted sections and look within them for newlines, but I'm thinking a Regex might be a better choice (i.e. now I have two problems ) | Since this isn't a true CSV file, does it have any sort of schema? From your example, it looks like you have: int, int, int, int, string, bool, bool, int With that making up your record / object. Assuming that your data is well formed (I don't know enough about your source to know how valid this assumption is); you could: Read your line. Use a state machine to parse your data. If your line ends, and you're parsing a string, read the next line..and keep parsing. I'd avoid using a regex if possible. | Looking for Regex to find quoted newlines in a big string (for C#) I have a big string (let's call it a CSV file, though it isn't actually one, it'll just be easier for now) that I have to parse in C# code. The first step of the parsing process splits the file into individual lines by just using a StreamReader object and calling ReadLine until it's through the file. However, any given line might contain a quoted (in single quotes) literal with embedded newlines. I need to find those newlines and convert them temporarily into some other kind of token or escape sequence until I've split the file into an array of lines..then I can change them back. Example input data: 1,2,10,99,'Some text without a newline', true, false, 90 2,1,11,98,'This text has an embedded newline and continues here', true, true, 90 I could write all of the C# code needed to do this by using string.IndexOf to find the quoted sections and look within them for newlines, but I'm thinking a Regex might be a better choice (i.e. now I have two problems ) | TITLE:
Looking for Regex to find quoted newlines in a big string (for C#)
QUESTION:
I have a big string (let's call it a CSV file, though it isn't actually one, it'll just be easier for now) that I have to parse in C# code. The first step of the parsing process splits the file into individual lines by just using a StreamReader object and calling ReadLine until it's through the file. However, any given line might contain a quoted (in single quotes) literal with embedded newlines. I need to find those newlines and convert them temporarily into some other kind of token or escape sequence until I've split the file into an array of lines..then I can change them back. Example input data: 1,2,10,99,'Some text without a newline', true, false, 90 2,1,11,98,'This text has an embedded newline and continues here', true, true, 90 I could write all of the C# code needed to do this by using string.IndexOf to find the quoted sections and look within them for newlines, but I'm thinking a Regex might be a better choice (i.e. now I have two problems )
ANSWER:
Since this isn't a true CSV file, does it have any sort of schema? From your example, it looks like you have: int, int, int, int, string, bool, bool, int With that making up your record / object. Assuming that your data is well formed (I don't know enough about your source to know how valid this assumption is); you could: Read your line. Use a state machine to parse your data. If your line ends, and you're parsing a string, read the next line..and keep parsing. I'd avoid using a regex if possible. | [
"c#",
"regex"
] | 2 | 3 | 2,503 | 4 | 0 | 2008-08-28T18:46:24.417000 | 2008-08-28T19:00:02.280000 |
33,073 | 33,085 | Ignore Emacs auto-generated files in a diff | How do I make diff ignore temporary files like foo.c~? Is there a configuration file that will make ignoring temporaries the default? More generally: what's the best way to generate a "clean" patch off a tarball? I do this rarely enough (submitting a bug fix to an OSS project by email) that I always struggle with it... EDIT: OK, the short answer is diff -ruN -x *~... Is there a better answer? E.g., can this go in a configuration file? | This doesn't strictly answer your question, but you can avoid the problem by configuring Emacs to use a specific directory to keep the backup files in. There are different implementations for Emacs or XEmacs. In GNU Emacs (defvar user-temporary-file-directory (concat temporary-file-directory user-login-name "/")) (make-directory user-temporary-file-directory t) (setq backup-by-copying t) (setq backup-directory-alist `((".".,user-temporary-file-directory) (,tramp-file-name-regexp nil))) (setq auto-save-list-file-prefix (concat user-temporary-file-directory ".auto-saves-")) (setq auto-save-file-name-transforms `((".*",user-temporary-file-directory t))) In XEmacs (require 'auto-save) (require 'backup-dir)
(defvar user-temporary-file-directory (concat (temp-directory) "/" (user-login-name))) (make-directory user-temporary-file-directory t) (setq backup-by-copying t) (setq auto-save-directory user-temporary-file-directory) (setq auto-save-list-file-prefix (concat user-temporary-file-directory ".auto-saves-")) (setq bkup-backup-directory-info `((t,user-temporary-file-directory full-path))) You can also remove them all with a simple find command find. -name “*~” -delete Note that the asterisk and tilde are in double quotes to stop the shell expanding them. By the way, these aren't strictly temporary files. They are a backup of the previous version of the file, so you can manually "undo" your last edit at any time in the future. | Ignore Emacs auto-generated files in a diff How do I make diff ignore temporary files like foo.c~? Is there a configuration file that will make ignoring temporaries the default? More generally: what's the best way to generate a "clean" patch off a tarball? I do this rarely enough (submitting a bug fix to an OSS project by email) that I always struggle with it... EDIT: OK, the short answer is diff -ruN -x *~... Is there a better answer? E.g., can this go in a configuration file? | TITLE:
Ignore Emacs auto-generated files in a diff
QUESTION:
How do I make diff ignore temporary files like foo.c~? Is there a configuration file that will make ignoring temporaries the default? More generally: what's the best way to generate a "clean" patch off a tarball? I do this rarely enough (submitting a bug fix to an OSS project by email) that I always struggle with it... EDIT: OK, the short answer is diff -ruN -x *~... Is there a better answer? E.g., can this go in a configuration file?
ANSWER:
This doesn't strictly answer your question, but you can avoid the problem by configuring Emacs to use a specific directory to keep the backup files in. There are different implementations for Emacs or XEmacs. In GNU Emacs (defvar user-temporary-file-directory (concat temporary-file-directory user-login-name "/")) (make-directory user-temporary-file-directory t) (setq backup-by-copying t) (setq backup-directory-alist `((".".,user-temporary-file-directory) (,tramp-file-name-regexp nil))) (setq auto-save-list-file-prefix (concat user-temporary-file-directory ".auto-saves-")) (setq auto-save-file-name-transforms `((".*",user-temporary-file-directory t))) In XEmacs (require 'auto-save) (require 'backup-dir)
(defvar user-temporary-file-directory (concat (temp-directory) "/" (user-login-name))) (make-directory user-temporary-file-directory t) (setq backup-by-copying t) (setq auto-save-directory user-temporary-file-directory) (setq auto-save-list-file-prefix (concat user-temporary-file-directory ".auto-saves-")) (setq bkup-backup-directory-info `((t,user-temporary-file-directory full-path))) You can also remove them all with a simple find command find. -name “*~” -delete Note that the asterisk and tilde are in double quotes to stop the shell expanding them. By the way, these aren't strictly temporary files. They are a backup of the previous version of the file, so you can manually "undo" your last edit at any time in the future. | [
"emacs",
"backup",
"diff",
"patch",
"autosave"
] | 4 | 4 | 1,954 | 4 | 0 | 2008-08-28T18:50:31.383000 | 2008-08-28T18:55:05.333000 |
33,076 | 33,714 | Pattern recognition algorithms | In the past I had to develop a program which acted as a rule evaluator. You had an antecedent and some consecuents (actions) so if the antecedent evaled to true the actions where performed. At that time I used a modified version of the RETE algorithm (there are three versions of RETE only the first being public) for the antecedent pattern matching. We're talking about a big system here with million of operations per rule and some operators "repeated" in several rules. It's possible I'll have to implement it all over again in other language and, even though I'm experienced in RETE, does anyone know of other pattern matching algorithms? Any suggestions or should I keep using RETE? | The TREAT algorithm is similar to RETE, but doesn't record partial matches. As a result, it may use less memory than RETE in certain situations. Also, if you modify a significant number of the known facts, then TREAT can be much faster because you don't have to spend time on retractions. There's also RETE* which balances between RETE and TREAT by saving some join node state depending on how much memory you want to use. So you still save some assertion time, but also get memory and retraction time savings depending on how you tune your system. You may also want to check out LEAPS, which uses a lazy evaluation scheme and incorporates elements of both RETE and TREAT. I only have personal experience with RETE, but it seems like RETE* or LEAPS are the better, more flexible choices. | Pattern recognition algorithms In the past I had to develop a program which acted as a rule evaluator. You had an antecedent and some consecuents (actions) so if the antecedent evaled to true the actions where performed. At that time I used a modified version of the RETE algorithm (there are three versions of RETE only the first being public) for the antecedent pattern matching. We're talking about a big system here with million of operations per rule and some operators "repeated" in several rules. It's possible I'll have to implement it all over again in other language and, even though I'm experienced in RETE, does anyone know of other pattern matching algorithms? Any suggestions or should I keep using RETE? | TITLE:
Pattern recognition algorithms
QUESTION:
In the past I had to develop a program which acted as a rule evaluator. You had an antecedent and some consecuents (actions) so if the antecedent evaled to true the actions where performed. At that time I used a modified version of the RETE algorithm (there are three versions of RETE only the first being public) for the antecedent pattern matching. We're talking about a big system here with million of operations per rule and some operators "repeated" in several rules. It's possible I'll have to implement it all over again in other language and, even though I'm experienced in RETE, does anyone know of other pattern matching algorithms? Any suggestions or should I keep using RETE?
ANSWER:
The TREAT algorithm is similar to RETE, but doesn't record partial matches. As a result, it may use less memory than RETE in certain situations. Also, if you modify a significant number of the known facts, then TREAT can be much faster because you don't have to spend time on retractions. There's also RETE* which balances between RETE and TREAT by saving some join node state depending on how much memory you want to use. So you still save some assertion time, but also get memory and retraction time savings depending on how you tune your system. You may also want to check out LEAPS, which uses a lazy evaluation scheme and incorporates elements of both RETE and TREAT. I only have personal experience with RETE, but it seems like RETE* or LEAPS are the better, more flexible choices. | [
"algorithm",
"pattern-recognition"
] | 9 | 5 | 11,075 | 1 | 0 | 2008-08-28T18:51:32.097000 | 2008-08-29T00:42:18.040000 |
33,080 | 33,147 | Setting the height of a DIV dynamically | In a web application, I have a page that contains a DIV that has an auto-width depending on the width of the browser window. I need an auto-height for the object. The DIV starts about 300px from the top screen, and its height should make it stretch to the bottom of the browser screen. I have a max height for the container DIV, so there would have to be minimum-height for the div. I believe I can just restrict that in CSS, and use Javascript to handle the resizing of the DIV. My javascript isn't nearly as good as it should be. Is there an easy script I could write that would do this for me? Edit: The DIV houses a control that does it's own overflow handling (implements its own scroll bar). | Try this simple, specific function: function resizeElementHeight(element) { var height = 0; var body = window.document.body; if (window.innerHeight) { height = window.innerHeight; } else if (body.parentElement.clientHeight) { height = body.parentElement.clientHeight; } else if (body && body.clientHeight) { height = body.clientHeight; } element.style.height = ((height - element.offsetTop) + "px"); } It does not depend on the current distance from the top of the body being specified (in case your 300px changes). EDIT: By the way, you would want to call this on that div every time the user changed the browser's size, so you would need to wire up the event handler for that, of course. | Setting the height of a DIV dynamically In a web application, I have a page that contains a DIV that has an auto-width depending on the width of the browser window. I need an auto-height for the object. The DIV starts about 300px from the top screen, and its height should make it stretch to the bottom of the browser screen. I have a max height for the container DIV, so there would have to be minimum-height for the div. I believe I can just restrict that in CSS, and use Javascript to handle the resizing of the DIV. My javascript isn't nearly as good as it should be. Is there an easy script I could write that would do this for me? Edit: The DIV houses a control that does it's own overflow handling (implements its own scroll bar). | TITLE:
Setting the height of a DIV dynamically
QUESTION:
In a web application, I have a page that contains a DIV that has an auto-width depending on the width of the browser window. I need an auto-height for the object. The DIV starts about 300px from the top screen, and its height should make it stretch to the bottom of the browser screen. I have a max height for the container DIV, so there would have to be minimum-height for the div. I believe I can just restrict that in CSS, and use Javascript to handle the resizing of the DIV. My javascript isn't nearly as good as it should be. Is there an easy script I could write that would do this for me? Edit: The DIV houses a control that does it's own overflow handling (implements its own scroll bar).
ANSWER:
Try this simple, specific function: function resizeElementHeight(element) { var height = 0; var body = window.document.body; if (window.innerHeight) { height = window.innerHeight; } else if (body.parentElement.clientHeight) { height = body.parentElement.clientHeight; } else if (body && body.clientHeight) { height = body.clientHeight; } element.style.height = ((height - element.offsetTop) + "px"); } It does not depend on the current distance from the top of the body being specified (in case your 300px changes). EDIT: By the way, you would want to call this on that div every time the user changed the browser's size, so you would need to wire up the event handler for that, of course. | [
"javascript",
"html",
"css"
] | 33 | 40 | 169,728 | 8 | 0 | 2008-08-28T18:52:53.060000 | 2008-08-28T19:11:28.617000 |
33,086 | 33,100 | ensuring uploaded files are safe | My boss has come to me and asked how to enure a file uploaded through web page is safe. He wants people to be able to upload pdfs and tiff images (and the like) and his real concern is someone embedding a virus in a pdf that is then viewed/altered (and the virus executed). I just read something on a procedure that could be used to destroy stenographic information emebedded in images by altering least sifnificant bits. Could a similar process be used to enusre that a virus isn't implanted? Does anyone know of any programs that can scrub files? Update: So the team argued about this a little bit, and one developer found a post about letting the file download to the file system and having the antivirus software that protects the network check the files there. The poster essentially said that it was too difficult to use the API or the command line for a couple of products. This seems a little kludgy to me, because we are planning on storing the files in the db, but I haven't had to scan files for viruses before. Does anyone have any thoughts or expierence with this? http://www.softwarebyrob.com/2008/05/15/virus-scanning-from-code/ | I'd recommend running your uploaded files through antivirus software such as ClamAV. I don't know about scrubbing files to remove viruses, but this will at least allow you to detect and delete infected files before you view them. | ensuring uploaded files are safe My boss has come to me and asked how to enure a file uploaded through web page is safe. He wants people to be able to upload pdfs and tiff images (and the like) and his real concern is someone embedding a virus in a pdf that is then viewed/altered (and the virus executed). I just read something on a procedure that could be used to destroy stenographic information emebedded in images by altering least sifnificant bits. Could a similar process be used to enusre that a virus isn't implanted? Does anyone know of any programs that can scrub files? Update: So the team argued about this a little bit, and one developer found a post about letting the file download to the file system and having the antivirus software that protects the network check the files there. The poster essentially said that it was too difficult to use the API or the command line for a couple of products. This seems a little kludgy to me, because we are planning on storing the files in the db, but I haven't had to scan files for viruses before. Does anyone have any thoughts or expierence with this? http://www.softwarebyrob.com/2008/05/15/virus-scanning-from-code/ | TITLE:
ensuring uploaded files are safe
QUESTION:
My boss has come to me and asked how to enure a file uploaded through web page is safe. He wants people to be able to upload pdfs and tiff images (and the like) and his real concern is someone embedding a virus in a pdf that is then viewed/altered (and the virus executed). I just read something on a procedure that could be used to destroy stenographic information emebedded in images by altering least sifnificant bits. Could a similar process be used to enusre that a virus isn't implanted? Does anyone know of any programs that can scrub files? Update: So the team argued about this a little bit, and one developer found a post about letting the file download to the file system and having the antivirus software that protects the network check the files there. The poster essentially said that it was too difficult to use the API or the command line for a couple of products. This seems a little kludgy to me, because we are planning on storing the files in the db, but I haven't had to scan files for viruses before. Does anyone have any thoughts or expierence with this? http://www.softwarebyrob.com/2008/05/15/virus-scanning-from-code/
ANSWER:
I'd recommend running your uploaded files through antivirus software such as ClamAV. I don't know about scrubbing files to remove viruses, but this will at least allow you to detect and delete infected files before you view them. | [
"security",
"antivirus"
] | 10 | 4 | 3,154 | 6 | 0 | 2008-08-28T18:55:06.177000 | 2008-08-28T18:58:09.773000 |
33,103 | 33,130 | How Do Sites Suppress Pasting Text? | I've noticed that some sites (usually banks) suppress the ability to paste text into text fields. How is this done? I know that JavaScript can be used to swallow the keyboard shortcut for paste, but what about the right-click menu item? | Probably using the onpaste event, and either return false from it or use e.preventDefault() on the Event object. Note that onpaste is non standard, don't rely on it for production sites, because it will not be there forever. $(document).on("paste",function(e){
console.log("paste")
e.preventDefault()
return false;
}) | How Do Sites Suppress Pasting Text? I've noticed that some sites (usually banks) suppress the ability to paste text into text fields. How is this done? I know that JavaScript can be used to swallow the keyboard shortcut for paste, but what about the right-click menu item? | TITLE:
How Do Sites Suppress Pasting Text?
QUESTION:
I've noticed that some sites (usually banks) suppress the ability to paste text into text fields. How is this done? I know that JavaScript can be used to swallow the keyboard shortcut for paste, but what about the right-click menu item?
ANSWER:
Probably using the onpaste event, and either return false from it or use e.preventDefault() on the Event object. Note that onpaste is non standard, don't rely on it for production sites, because it will not be there forever. $(document).on("paste",function(e){
console.log("paste")
e.preventDefault()
return false;
}) | [
"javascript",
"browser",
"web-applications",
"clipboard"
] | 7 | 10 | 431 | 2 | 0 | 2008-08-28T18:58:36.090000 | 2008-08-28T19:04:28.167000 |
33,104 | 33,123 | Communicating between websites (using Javascript or ?) | Here's my problem - I'd like to communicate between two websites and I'm looking for a clean solution. The current solution uses Javascript but there are nasty workarounds because of (understandable) cross-site scripting restrictions. At the moment, website A opens a modal window containing website B using a jQuery plug-in called jqModal. Website B does some work and returns some results to website A. To return that information we have to work around cross-site scripting restrictions - website B creates an iframe that refers to a page on website A and includes *fragment identifiers" containing the information to be returned. The iframe is polled by website A to detect the returned information. It's a common technique but it's hacky. There are variations such as CrossSite and I could perhaps use an HTTP POST from website B to website A but I'm trying to avoid page refreshes. Does anyone have any alternatives? EDIT: I'd like to avoid having to save state on website B. | My best suggestion would be to create a webservice on each site that the other could call with the information that needs to get passed. If security is necessary, it's easy to add an SSL-like authentication scheme (or actual SSL even, if you like) to this system to ensure that only the two servers are able to talk to their respective web services. This would let you avoid the hackiness that's inherent in any scheme that involves one site opening windows on the other. | Communicating between websites (using Javascript or ?) Here's my problem - I'd like to communicate between two websites and I'm looking for a clean solution. The current solution uses Javascript but there are nasty workarounds because of (understandable) cross-site scripting restrictions. At the moment, website A opens a modal window containing website B using a jQuery plug-in called jqModal. Website B does some work and returns some results to website A. To return that information we have to work around cross-site scripting restrictions - website B creates an iframe that refers to a page on website A and includes *fragment identifiers" containing the information to be returned. The iframe is polled by website A to detect the returned information. It's a common technique but it's hacky. There are variations such as CrossSite and I could perhaps use an HTTP POST from website B to website A but I'm trying to avoid page refreshes. Does anyone have any alternatives? EDIT: I'd like to avoid having to save state on website B. | TITLE:
Communicating between websites (using Javascript or ?)
QUESTION:
Here's my problem - I'd like to communicate between two websites and I'm looking for a clean solution. The current solution uses Javascript but there are nasty workarounds because of (understandable) cross-site scripting restrictions. At the moment, website A opens a modal window containing website B using a jQuery plug-in called jqModal. Website B does some work and returns some results to website A. To return that information we have to work around cross-site scripting restrictions - website B creates an iframe that refers to a page on website A and includes *fragment identifiers" containing the information to be returned. The iframe is polled by website A to detect the returned information. It's a common technique but it's hacky. There are variations such as CrossSite and I could perhaps use an HTTP POST from website B to website A but I'm trying to avoid page refreshes. Does anyone have any alternatives? EDIT: I'd like to avoid having to save state on website B.
ANSWER:
My best suggestion would be to create a webservice on each site that the other could call with the information that needs to get passed. If security is necessary, it's easy to add an SSL-like authentication scheme (or actual SSL even, if you like) to this system to ensure that only the two servers are able to talk to their respective web services. This would let you avoid the hackiness that's inherent in any scheme that involves one site opening windows on the other. | [
"javascript",
"jquery",
"web",
"xss"
] | 10 | 5 | 2,137 | 4 | 0 | 2008-08-28T18:58:39.990000 | 2008-08-28T19:02:25.580000 |
33,113 | 33,290 | Is there any way to override the drag/drop or copy/paste behavior of an existing app in Windows? | I would like to extend some existing applications' drag and drop behavior, and I'm wondering if there is any way to hack on drag and drop support or changes to drag and drop behavior by monitoring the app's message loop and injecting my own messages. It would also work to monitor for when a paste operation is executed, basically to create a custom behavior when a control only supports pasting text and an image is pasted. I'm thinking Detours might be my best bet, but one problem is that I would have to write custom code for each app I wanted to extend. If only Windows was designed with extensibility in mind! On another note, is there any OS that supports extensibility of this nature? | If you're willing to do in-memory diddling while the application is loaded, you could probably finagle that. But if you're looking for an easy way to just inject code you want into another window's message pump, you're not going to find it. The skills required to accomplish something like this are formidable (unless someone has wrapped all of this up in an application/library that I'm unaware of, but I doubt it). It's like clipboard hooking, writ-large: it's frowned upon, there are tons of gotchas, and you're extremely likely to introduce significant instability into your system if you don't really know what you're doing. | Is there any way to override the drag/drop or copy/paste behavior of an existing app in Windows? I would like to extend some existing applications' drag and drop behavior, and I'm wondering if there is any way to hack on drag and drop support or changes to drag and drop behavior by monitoring the app's message loop and injecting my own messages. It would also work to monitor for when a paste operation is executed, basically to create a custom behavior when a control only supports pasting text and an image is pasted. I'm thinking Detours might be my best bet, but one problem is that I would have to write custom code for each app I wanted to extend. If only Windows was designed with extensibility in mind! On another note, is there any OS that supports extensibility of this nature? | TITLE:
Is there any way to override the drag/drop or copy/paste behavior of an existing app in Windows?
QUESTION:
I would like to extend some existing applications' drag and drop behavior, and I'm wondering if there is any way to hack on drag and drop support or changes to drag and drop behavior by monitoring the app's message loop and injecting my own messages. It would also work to monitor for when a paste operation is executed, basically to create a custom behavior when a control only supports pasting text and an image is pasted. I'm thinking Detours might be my best bet, but one problem is that I would have to write custom code for each app I wanted to extend. If only Windows was designed with extensibility in mind! On another note, is there any OS that supports extensibility of this nature?
ANSWER:
If you're willing to do in-memory diddling while the application is loaded, you could probably finagle that. But if you're looking for an easy way to just inject code you want into another window's message pump, you're not going to find it. The skills required to accomplish something like this are formidable (unless someone has wrapped all of this up in an application/library that I'm unaware of, but I doubt it). It's like clipboard hooking, writ-large: it's frowned upon, there are tons of gotchas, and you're extremely likely to introduce significant instability into your system if you don't really know what you're doing. | [
"windows",
"detours"
] | 0 | 0 | 378 | 3 | 0 | 2008-08-28T19:00:40.547000 | 2008-08-28T20:12:24.603000 |
33,117 | 33,343 | Building a custom Linux Live CD | Can anyone point me to a good tutorial on creating a bootable Linux CD from scratch? I need help with a fairly specialized problem: my firm sells an expansion card that requires custom firmware. Currently we use an extremely old live CD image of RH7.2 that we update with current firmware. Manufacturing puts the cards in a machine, boots off the CD, the CD writes the firmware, they power off and pull the cards. Because of this cycle, it's essential that the CD boot and shut down as quickly as possible. The problem is that with the next generation of cards, I have to update the CD to a 2.6 kernel. It's easy enough to acquire a pre-existing live CD - but those all are designed for showing off Linux on the desktop - which means they take forever to boot. Can anyone fix me up with a current How-To? Update: So, just as a final update for anyone reading this later - the tool I ended up using was "livecd-creator". My reason for choosing this tool was that it is available for RedHat-based distributions like CentOs, Fedora and RHEL - which are all distributions that my company supports already. In addition, while the project is very poorly documented it is extremely customizable. I was able to create a minimal LiveCD and edit the boot sequence so that it booted directly into the firmware updater instead of a bash shell. The whole job would have only taken an hour or two if there had been a README explaining the configuration file! | One key piece of advice I can give is that most LiveCDs use a compressed filesystem called squashfs to cram as much data on the CD as possible. Since you don't need compression, you could run the mksquashfs step (present in most tutorials) with -noDataCompression and -noFragmentCompression to save on decompression time. You may even be able to drop the squashfs approach entirely, but this would require some restructuring. This may actually be slower depending on your CD-ROM read speed vs. CPU speed, but it's worth looking into. This Ubuntu tutorial was effective enough for me to build a LiveCD based on 8.04. It may be useful for getting the feel of how a LiveCD is composed, but I would probably not recommend using an Ubuntu LiveCD. If at all possible, find a minimal LiveCD and build up with only minimal stripping out, rather than stripping down a huge LiveCD like Ubuntu. There are some situations in which the smaller distros are using smaller/faster alternatives rather than just leaving something out. If you want to get seriously hardcore, you could look at Linux From Scratch, and include only what you want, but that's probably more time than you want to spend. | Building a custom Linux Live CD Can anyone point me to a good tutorial on creating a bootable Linux CD from scratch? I need help with a fairly specialized problem: my firm sells an expansion card that requires custom firmware. Currently we use an extremely old live CD image of RH7.2 that we update with current firmware. Manufacturing puts the cards in a machine, boots off the CD, the CD writes the firmware, they power off and pull the cards. Because of this cycle, it's essential that the CD boot and shut down as quickly as possible. The problem is that with the next generation of cards, I have to update the CD to a 2.6 kernel. It's easy enough to acquire a pre-existing live CD - but those all are designed for showing off Linux on the desktop - which means they take forever to boot. Can anyone fix me up with a current How-To? Update: So, just as a final update for anyone reading this later - the tool I ended up using was "livecd-creator". My reason for choosing this tool was that it is available for RedHat-based distributions like CentOs, Fedora and RHEL - which are all distributions that my company supports already. In addition, while the project is very poorly documented it is extremely customizable. I was able to create a minimal LiveCD and edit the boot sequence so that it booted directly into the firmware updater instead of a bash shell. The whole job would have only taken an hour or two if there had been a README explaining the configuration file! | TITLE:
Building a custom Linux Live CD
QUESTION:
Can anyone point me to a good tutorial on creating a bootable Linux CD from scratch? I need help with a fairly specialized problem: my firm sells an expansion card that requires custom firmware. Currently we use an extremely old live CD image of RH7.2 that we update with current firmware. Manufacturing puts the cards in a machine, boots off the CD, the CD writes the firmware, they power off and pull the cards. Because of this cycle, it's essential that the CD boot and shut down as quickly as possible. The problem is that with the next generation of cards, I have to update the CD to a 2.6 kernel. It's easy enough to acquire a pre-existing live CD - but those all are designed for showing off Linux on the desktop - which means they take forever to boot. Can anyone fix me up with a current How-To? Update: So, just as a final update for anyone reading this later - the tool I ended up using was "livecd-creator". My reason for choosing this tool was that it is available for RedHat-based distributions like CentOs, Fedora and RHEL - which are all distributions that my company supports already. In addition, while the project is very poorly documented it is extremely customizable. I was able to create a minimal LiveCD and edit the boot sequence so that it booted directly into the firmware updater instead of a bash shell. The whole job would have only taken an hour or two if there had been a README explaining the configuration file!
ANSWER:
One key piece of advice I can give is that most LiveCDs use a compressed filesystem called squashfs to cram as much data on the CD as possible. Since you don't need compression, you could run the mksquashfs step (present in most tutorials) with -noDataCompression and -noFragmentCompression to save on decompression time. You may even be able to drop the squashfs approach entirely, but this would require some restructuring. This may actually be slower depending on your CD-ROM read speed vs. CPU speed, but it's worth looking into. This Ubuntu tutorial was effective enough for me to build a LiveCD based on 8.04. It may be useful for getting the feel of how a LiveCD is composed, but I would probably not recommend using an Ubuntu LiveCD. If at all possible, find a minimal LiveCD and build up with only minimal stripping out, rather than stripping down a huge LiveCD like Ubuntu. There are some situations in which the smaller distros are using smaller/faster alternatives rather than just leaving something out. If you want to get seriously hardcore, you could look at Linux From Scratch, and include only what you want, but that's probably more time than you want to spend. | [
"linux"
] | 23 | 3 | 19,591 | 6 | 0 | 2008-08-28T19:01:03.290000 | 2008-08-28T20:38:27.440000 |
33,144 | 33,267 | Windows Mobile 6 Development, alternatives to visual studio? | I am looking to start writing apps for my Windows Mobile 6.1 professional device (Sprint Mogul/HTC Titan). I use the copy of Visual Studio 2003 that I bought in college for all of my current contracting work, (all of my day job work is done on a company laptop). From what I can tell from MSDN in order to develop using windows Mobile 5 or 6 SDK I need to have at least Visual Studio 2005 Standard and I really don't feel like shelling out that much cash just to be able to develop for my phone. Are there any free tools available to develop for Windows mobile? Or is there an affordable way to get VS that I am overlooking? | I looked into more affordable ways to do back in the VS 2003 days, but couldn't find anything. My guess is that you still need VS to do it. @MartinHN You CAN NOT use version older than 2005 or less then Pro for Windows Mobile 5/6 device development. | Windows Mobile 6 Development, alternatives to visual studio? I am looking to start writing apps for my Windows Mobile 6.1 professional device (Sprint Mogul/HTC Titan). I use the copy of Visual Studio 2003 that I bought in college for all of my current contracting work, (all of my day job work is done on a company laptop). From what I can tell from MSDN in order to develop using windows Mobile 5 or 6 SDK I need to have at least Visual Studio 2005 Standard and I really don't feel like shelling out that much cash just to be able to develop for my phone. Are there any free tools available to develop for Windows mobile? Or is there an affordable way to get VS that I am overlooking? | TITLE:
Windows Mobile 6 Development, alternatives to visual studio?
QUESTION:
I am looking to start writing apps for my Windows Mobile 6.1 professional device (Sprint Mogul/HTC Titan). I use the copy of Visual Studio 2003 that I bought in college for all of my current contracting work, (all of my day job work is done on a company laptop). From what I can tell from MSDN in order to develop using windows Mobile 5 or 6 SDK I need to have at least Visual Studio 2005 Standard and I really don't feel like shelling out that much cash just to be able to develop for my phone. Are there any free tools available to develop for Windows mobile? Or is there an affordable way to get VS that I am overlooking?
ANSWER:
I looked into more affordable ways to do back in the VS 2003 days, but couldn't find anything. My guess is that you still need VS to do it. @MartinHN You CAN NOT use version older than 2005 or less then Pro for Windows Mobile 5/6 device development. | [
"windows-mobile"
] | 8 | 1 | 12,538 | 8 | 0 | 2008-08-28T19:10:51.317000 | 2008-08-28T20:06:44.630000 |
33,150 | 33,179 | How to pass method name to custom server control in asp.net? | I am working on a Customer Server Control that extends another control. There is no problem with attaching to other controls on the form. in vb.net: Parent.FindControl(TargetControlName) I would like to pass a method to the control in the ASPX markup. for example: So, I tried using reflection to access the given method name from the Parent. Something like (in VB) Dim pageType As Type = Page.GetType Dim CallbackMethodInfo As MethodInfo = pageType.GetMethod( "MethodName" )
'Also tried sender.Parent.GetType.GetMethod("MethodName") sender.Parent.Parent.GetType.GetMethod("MethodName") The method isn't found, because it just isn't apart of the Page. Where should I be looking? I'm fairly sure this is possible because I've seen other controls do similar. I forgot to mention, my work-around is to give the control events and attaching to them in the Code-behind. | If you want to be able to pass a method in the ASPX markup, you need to use the Browsable attribute in your code on the event. VB.NET Public Event InitializeStuffCallback C# [Browsable(true)] public event EventHandler InitializeStuffCallback; Reference: Design-Time Attributes for Components and BrowsableAttribute Class All the events, properties, or whatever need to be in the code-behind of the control with the browsable attribute to make it so you can change it in the tag code. | How to pass method name to custom server control in asp.net? I am working on a Customer Server Control that extends another control. There is no problem with attaching to other controls on the form. in vb.net: Parent.FindControl(TargetControlName) I would like to pass a method to the control in the ASPX markup. for example: So, I tried using reflection to access the given method name from the Parent. Something like (in VB) Dim pageType As Type = Page.GetType Dim CallbackMethodInfo As MethodInfo = pageType.GetMethod( "MethodName" )
'Also tried sender.Parent.GetType.GetMethod("MethodName") sender.Parent.Parent.GetType.GetMethod("MethodName") The method isn't found, because it just isn't apart of the Page. Where should I be looking? I'm fairly sure this is possible because I've seen other controls do similar. I forgot to mention, my work-around is to give the control events and attaching to them in the Code-behind. | TITLE:
How to pass method name to custom server control in asp.net?
QUESTION:
I am working on a Customer Server Control that extends another control. There is no problem with attaching to other controls on the form. in vb.net: Parent.FindControl(TargetControlName) I would like to pass a method to the control in the ASPX markup. for example: So, I tried using reflection to access the given method name from the Parent. Something like (in VB) Dim pageType As Type = Page.GetType Dim CallbackMethodInfo As MethodInfo = pageType.GetMethod( "MethodName" )
'Also tried sender.Parent.GetType.GetMethod("MethodName") sender.Parent.Parent.GetType.GetMethod("MethodName") The method isn't found, because it just isn't apart of the Page. Where should I be looking? I'm fairly sure this is possible because I've seen other controls do similar. I forgot to mention, my work-around is to give the control events and attaching to them in the Code-behind.
ANSWER:
If you want to be able to pass a method in the ASPX markup, you need to use the Browsable attribute in your code on the event. VB.NET Public Event InitializeStuffCallback C# [Browsable(true)] public event EventHandler InitializeStuffCallback; Reference: Design-Time Attributes for Components and BrowsableAttribute Class All the events, properties, or whatever need to be in the code-behind of the control with the browsable attribute to make it so you can change it in the tag code. | [
"c#",
"asp.net",
"vb.net",
"custom-server-controls",
"web-controls"
] | 1 | 2 | 2,446 | 5 | 0 | 2008-08-28T19:11:34.217000 | 2008-08-28T19:24:26.793000 |
33,166 | 33,170 | How do I keep my Login.aspx page's ReturnUrl parameter from overriding my ASP.NET Login control's DestinationPageUrl property? | I'm using the ASP.NET Login Controls and Forms Authentication for membership/credentials for an ASP.NET web application. I've got pages such as PasswordRecovery.aspx that are accessable to only Anonymous users. When I click my login link from such a page, the login page has a ReturnUrl parameter in the address bar: http://www.example.com/Login.aspx?ReturnUrl=PasswordRecovery.aspx And then after a successful login, users are returned to the PasswordRecovery.aspx page specified in the ReturnUrl parameter to which they no longer have access. | I found the answer on Velocity Reviews. I handled the LoggedIn event to force a redirection to the DestinationPageUrl page. Public Partial Class Login Inherits System.Web.UI.Page
Protected Sub Login1_LoggedIn(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Login1.LoggedIn 'overrides ReturnUrl page parameter Response.Redirect(Login1.DestinationPageUrl) End Sub
End Class | How do I keep my Login.aspx page's ReturnUrl parameter from overriding my ASP.NET Login control's DestinationPageUrl property? I'm using the ASP.NET Login Controls and Forms Authentication for membership/credentials for an ASP.NET web application. I've got pages such as PasswordRecovery.aspx that are accessable to only Anonymous users. When I click my login link from such a page, the login page has a ReturnUrl parameter in the address bar: http://www.example.com/Login.aspx?ReturnUrl=PasswordRecovery.aspx And then after a successful login, users are returned to the PasswordRecovery.aspx page specified in the ReturnUrl parameter to which they no longer have access. | TITLE:
How do I keep my Login.aspx page's ReturnUrl parameter from overriding my ASP.NET Login control's DestinationPageUrl property?
QUESTION:
I'm using the ASP.NET Login Controls and Forms Authentication for membership/credentials for an ASP.NET web application. I've got pages such as PasswordRecovery.aspx that are accessable to only Anonymous users. When I click my login link from such a page, the login page has a ReturnUrl parameter in the address bar: http://www.example.com/Login.aspx?ReturnUrl=PasswordRecovery.aspx And then after a successful login, users are returned to the PasswordRecovery.aspx page specified in the ReturnUrl parameter to which they no longer have access.
ANSWER:
I found the answer on Velocity Reviews. I handled the LoggedIn event to force a redirection to the DestinationPageUrl page. Public Partial Class Login Inherits System.Web.UI.Page
Protected Sub Login1_LoggedIn(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Login1.LoggedIn 'overrides ReturnUrl page parameter Response.Redirect(Login1.DestinationPageUrl) End Sub
End Class | [
"asp.net",
"forms-authentication"
] | 12 | 14 | 6,176 | 1 | 0 | 2008-08-28T19:18:33.407000 | 2008-08-28T19:19:29.877000 |
33,174 | 33,235 | Accessing Sharepoint from outside the WebUI | Is it possible to access the database backend of a sharepoint server? My company uses Sharepoint to store data and pictures of various assets. Ideally I would be able to access the data and display it in my application to allow users both methods of access. Before I go talk to the IT department I would like to find out if this is even possible? Edit: From rails on linux? (Yes, I know I'm crazy) | Agree with Adam. Querying the Sharepoint Database is a big no-no, as Microsoft does not guarantee that the Schema is in any way stable. Only access the database if there is really no other way. As for Sharepoint, usually the Lists.asmx Web Service is what you want to look at first. http://www.c-sharpcorner.com/UploadFile/mahesh/WSSInNet01302007093018AM/WSSInNet.aspx http://geekswithblogs.net/mcassell/archive/2007/08/22/Accessing-Sharepoint-Data-through-Web-Services.aspx | Accessing Sharepoint from outside the WebUI Is it possible to access the database backend of a sharepoint server? My company uses Sharepoint to store data and pictures of various assets. Ideally I would be able to access the data and display it in my application to allow users both methods of access. Before I go talk to the IT department I would like to find out if this is even possible? Edit: From rails on linux? (Yes, I know I'm crazy) | TITLE:
Accessing Sharepoint from outside the WebUI
QUESTION:
Is it possible to access the database backend of a sharepoint server? My company uses Sharepoint to store data and pictures of various assets. Ideally I would be able to access the data and display it in my application to allow users both methods of access. Before I go talk to the IT department I would like to find out if this is even possible? Edit: From rails on linux? (Yes, I know I'm crazy)
ANSWER:
Agree with Adam. Querying the Sharepoint Database is a big no-no, as Microsoft does not guarantee that the Schema is in any way stable. Only access the database if there is really no other way. As for Sharepoint, usually the Lists.asmx Web Service is what you want to look at first. http://www.c-sharpcorner.com/UploadFile/mahesh/WSSInNet01302007093018AM/WSSInNet.aspx http://geekswithblogs.net/mcassell/archive/2007/08/22/Accessing-Sharepoint-Data-through-Web-Services.aspx | [
"sql-server",
"ruby-on-rails",
"ruby",
"sharepoint"
] | 1 | 3 | 1,248 | 4 | 0 | 2008-08-28T19:20:38.737000 | 2008-08-28T19:52:22.293000 |
33,199 | 33,208 | What's the "condition" in C interview test? | Would it be possible to print Hello twice using single condition? if "condition" printf ("Hello"); else printf("World"); | if ( printf("Hello") == 0 ) printf ("Hello"); else printf ("World");:-) | What's the "condition" in C interview test? Would it be possible to print Hello twice using single condition? if "condition" printf ("Hello"); else printf("World"); | TITLE:
What's the "condition" in C interview test?
QUESTION:
Would it be possible to print Hello twice using single condition? if "condition" printf ("Hello"); else printf("World");
ANSWER:
if ( printf("Hello") == 0 ) printf ("Hello"); else printf ("World");:-) | [
"c",
"conditional-statements"
] | 30 | 85 | 11,871 | 30 | 0 | 2008-08-28T19:37:33.343000 | 2008-08-28T19:41:32.740000 |
33,204 | 33,246 | When to commit changes? | Using Oracle 10g, accessed via Perl DBI, I have a table with a few tens of million rows being updated a few times per second while being read from much more frequently form another process. Soon the update frequency will increase by an order of magnitude (maybe two). Someone suggested that committing every N updates instead of after every update will help performance. I have a few questions: Will that be faster or slower or it depends (planning to benchmark both way as soon as can get a decent simulation of the new load) Why will it help / hinder performance. If "it depends...", on what? If it helps what's the best value of N? Why can't my local DBA have an helpful straight answer when I need one? (Actually I know the answer to that one):-) EDIT: @codeslave: Thanks, btw losing uncommited changes is not a problem, I don't delete the original data used for updating till I am sure everything is fine, btw cleaning lady did unplugs the server, TWICE:-) Some googling showed it might help because of issue related to rollback segments, but I still don't know a rule of thumb for N every few tens? hundreds? thousand? @diciu: Great info, I'll definitely look into that. | A commit results in Oracle writing stuff to the disk - i.e. in the redo log file so that whatever the transaction being commited has done can be recoverable in the event of a power failure, etc. Writing in file is slower than writing in memory so a commit will be slower if performed for many operations in a row rather then for a set of coalesced updates. In Oracle 10g there's an asynchronous commit that makes it much faster but less reliable: https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-6158695.html PS I know for sure that, in a scenario I've seen in a certain application, changing the number of coalesced updates from 5K to 50K makes it faster by an order of magnitude (10 times faster). | When to commit changes? Using Oracle 10g, accessed via Perl DBI, I have a table with a few tens of million rows being updated a few times per second while being read from much more frequently form another process. Soon the update frequency will increase by an order of magnitude (maybe two). Someone suggested that committing every N updates instead of after every update will help performance. I have a few questions: Will that be faster or slower or it depends (planning to benchmark both way as soon as can get a decent simulation of the new load) Why will it help / hinder performance. If "it depends...", on what? If it helps what's the best value of N? Why can't my local DBA have an helpful straight answer when I need one? (Actually I know the answer to that one):-) EDIT: @codeslave: Thanks, btw losing uncommited changes is not a problem, I don't delete the original data used for updating till I am sure everything is fine, btw cleaning lady did unplugs the server, TWICE:-) Some googling showed it might help because of issue related to rollback segments, but I still don't know a rule of thumb for N every few tens? hundreds? thousand? @diciu: Great info, I'll definitely look into that. | TITLE:
When to commit changes?
QUESTION:
Using Oracle 10g, accessed via Perl DBI, I have a table with a few tens of million rows being updated a few times per second while being read from much more frequently form another process. Soon the update frequency will increase by an order of magnitude (maybe two). Someone suggested that committing every N updates instead of after every update will help performance. I have a few questions: Will that be faster or slower or it depends (planning to benchmark both way as soon as can get a decent simulation of the new load) Why will it help / hinder performance. If "it depends...", on what? If it helps what's the best value of N? Why can't my local DBA have an helpful straight answer when I need one? (Actually I know the answer to that one):-) EDIT: @codeslave: Thanks, btw losing uncommited changes is not a problem, I don't delete the original data used for updating till I am sure everything is fine, btw cleaning lady did unplugs the server, TWICE:-) Some googling showed it might help because of issue related to rollback segments, but I still don't know a rule of thumb for N every few tens? hundreds? thousand? @diciu: Great info, I'll definitely look into that.
ANSWER:
A commit results in Oracle writing stuff to the disk - i.e. in the redo log file so that whatever the transaction being commited has done can be recoverable in the event of a power failure, etc. Writing in file is slower than writing in memory so a commit will be slower if performed for many operations in a row rather then for a set of coalesced updates. In Oracle 10g there's an asynchronous commit that makes it much faster but less reliable: https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-6158695.html PS I know for sure that, in a scenario I've seen in a certain application, changing the number of coalesced updates from 5K to 50K makes it faster by an order of magnitude (10 times faster). | [
"sql",
"oracle",
"commit"
] | 5 | 4 | 3,602 | 6 | 0 | 2008-08-28T19:40:55.193000 | 2008-08-28T19:55:51.023000 |
33,207 | 33,236 | What is the best way to unit test Objective-C code? | What frameworks exist to unit test Objective-C code? I would like a framework that integrates nicely with Apple Xcode. | Xcode includes XCTest, which is similar to OCUnit, an Objective-C unit testing framework, and has full support for running XCTest-based unit tests as part of your project's build process. Xcode's unit testing support is described in the Xcode Overview: Using Unit Tests. Back in the Xcode 2 days, I wrote a series of weblog posts about how to perform some common tasks with Xcode unit testing: Unit testing Cocoa frameworks Debugging Cocoa framework unit tests Unit testing Cocoa applications Debugging Cocoa application unit tests Despite using OCUnit rather than XCTest, the concepts are largely the same. Finally, I also wrote a few posts on how to write tests for Cocoa user interfaces; the way Cocoa is structured makes it relatively straightforward, because you don't have to spin an event loop or anything like that in most cases. Trust, but verify. Unit testing Cocoa user interfaces: Target-Action Unit testing Cocoa user interfaces: Cocoa Bindings This makes it possible to do test-driven development for not just your model-level code but also your controller-level and even view-level code. | What is the best way to unit test Objective-C code? What frameworks exist to unit test Objective-C code? I would like a framework that integrates nicely with Apple Xcode. | TITLE:
What is the best way to unit test Objective-C code?
QUESTION:
What frameworks exist to unit test Objective-C code? I would like a framework that integrates nicely with Apple Xcode.
ANSWER:
Xcode includes XCTest, which is similar to OCUnit, an Objective-C unit testing framework, and has full support for running XCTest-based unit tests as part of your project's build process. Xcode's unit testing support is described in the Xcode Overview: Using Unit Tests. Back in the Xcode 2 days, I wrote a series of weblog posts about how to perform some common tasks with Xcode unit testing: Unit testing Cocoa frameworks Debugging Cocoa framework unit tests Unit testing Cocoa applications Debugging Cocoa application unit tests Despite using OCUnit rather than XCTest, the concepts are largely the same. Finally, I also wrote a few posts on how to write tests for Cocoa user interfaces; the way Cocoa is structured makes it relatively straightforward, because you don't have to spin an event loop or anything like that in most cases. Trust, but verify. Unit testing Cocoa user interfaces: Target-Action Unit testing Cocoa user interfaces: Cocoa Bindings This makes it possible to do test-driven development for not just your model-level code but also your controller-level and even view-level code. | [
"objective-c",
"cocoa",
"unit-testing",
"xcode"
] | 333 | 317 | 76,485 | 17 | 0 | 2008-08-28T19:41:30.307000 | 2008-08-28T19:52:25.617000 |
33,217 | 33,221 | How can you implement trackbacks on a custom-coded blog (written in C#)? | How can you implement trackbacks on a custom-coded blog (written in C#)? | The TrackBack specification was created by Six Apart back in the day for their Movable Type blogging system. After some corporate changes it seems to be no longer available, but here's an archived version: http://web.archive.org/web/20081228043036/http://www.sixapart.com/pronet/docs/trackback_spec | How can you implement trackbacks on a custom-coded blog (written in C#)? How can you implement trackbacks on a custom-coded blog (written in C#)? | TITLE:
How can you implement trackbacks on a custom-coded blog (written in C#)?
QUESTION:
How can you implement trackbacks on a custom-coded blog (written in C#)?
ANSWER:
The TrackBack specification was created by Six Apart back in the day for their Movable Type blogging system. After some corporate changes it seems to be no longer available, but here's an archived version: http://web.archive.org/web/20081228043036/http://www.sixapart.com/pronet/docs/trackback_spec | [
"c#",
"blogs",
"trackback"
] | 0 | 2 | 453 | 3 | 0 | 2008-08-28T19:45:03.543000 | 2008-08-28T19:46:39.610000 |
33,222 | 950,946 | Compact Framework - Lightweight GUI Framework? | Winform on CF is a bit heavy, initialising a lot of windows handles takes serious time and memory. Another issue is the lack of inbuilt double buffering and lack of control you have over the UI rendering means that during processor intensive operations the UI might leave the user staring at a half rendered screen. Nice! To alleviate this issue I would seek a lightweight control framework, is there one kicking about already or would one have to homebrew? By lightweight I mean a control library that enables one to fully control painting of controls and doesn't use many expensive windows handles. NOTE: Please don't suggest that I am running too much on the UI thread. That is not the case. | I ran across this the other day, which might be helpful at least as a starting point: Fuild - Windows Mobile.NET Touch Controls. The look and feel is nice, but there is no design time support. I don't know too much about memory footprint, etc but everything is double buffered and the performance appears to be pretty good. | Compact Framework - Lightweight GUI Framework? Winform on CF is a bit heavy, initialising a lot of windows handles takes serious time and memory. Another issue is the lack of inbuilt double buffering and lack of control you have over the UI rendering means that during processor intensive operations the UI might leave the user staring at a half rendered screen. Nice! To alleviate this issue I would seek a lightweight control framework, is there one kicking about already or would one have to homebrew? By lightweight I mean a control library that enables one to fully control painting of controls and doesn't use many expensive windows handles. NOTE: Please don't suggest that I am running too much on the UI thread. That is not the case. | TITLE:
Compact Framework - Lightweight GUI Framework?
QUESTION:
Winform on CF is a bit heavy, initialising a lot of windows handles takes serious time and memory. Another issue is the lack of inbuilt double buffering and lack of control you have over the UI rendering means that during processor intensive operations the UI might leave the user staring at a half rendered screen. Nice! To alleviate this issue I would seek a lightweight control framework, is there one kicking about already or would one have to homebrew? By lightweight I mean a control library that enables one to fully control painting of controls and doesn't use many expensive windows handles. NOTE: Please don't suggest that I am running too much on the UI thread. That is not the case.
ANSWER:
I ran across this the other day, which might be helpful at least as a starting point: Fuild - Windows Mobile.NET Touch Controls. The look and feel is nice, but there is no design time support. I don't know too much about memory footprint, etc but everything is double buffered and the performance appears to be pretty good. | [
"compact-framework",
"gdi+",
"windows-ce"
] | 4 | 2 | 2,619 | 4 | 0 | 2008-08-28T19:47:24.710000 | 2009-06-04T14:26:46.510000 |
33,223 | 33,243 | Is elegant, semantic CSS with ASP.Net still a pipe dream? | I know Microsoft has made efforts in the direction of semantic and cross-browser compliant XHTML and CSS, but it still seems like a PitA to pull off elegant markup. I've downloaded and tweaked the CSS Friendly Adapters and all that. But I still find myself frustrated with bloated and unattractive code. Is elegant, semantic CSS with ASP.Net still a pipe dream? Or is it finally possible, I just need more practice? | The easiest way to generate elegant HTML and CSS is to use MVC framework, where you have much more control over HTML generation than with Web Forms. | Is elegant, semantic CSS with ASP.Net still a pipe dream? I know Microsoft has made efforts in the direction of semantic and cross-browser compliant XHTML and CSS, but it still seems like a PitA to pull off elegant markup. I've downloaded and tweaked the CSS Friendly Adapters and all that. But I still find myself frustrated with bloated and unattractive code. Is elegant, semantic CSS with ASP.Net still a pipe dream? Or is it finally possible, I just need more practice? | TITLE:
Is elegant, semantic CSS with ASP.Net still a pipe dream?
QUESTION:
I know Microsoft has made efforts in the direction of semantic and cross-browser compliant XHTML and CSS, but it still seems like a PitA to pull off elegant markup. I've downloaded and tweaked the CSS Friendly Adapters and all that. But I still find myself frustrated with bloated and unattractive code. Is elegant, semantic CSS with ASP.Net still a pipe dream? Or is it finally possible, I just need more practice?
ANSWER:
The easiest way to generate elegant HTML and CSS is to use MVC framework, where you have much more control over HTML generation than with Web Forms. | [
"asp.net",
"css",
"xhtml",
"semantics"
] | 9 | 13 | 831 | 8 | 0 | 2008-08-28T19:47:58.187000 | 2008-08-28T19:54:02.727000 |
33,226 | 33,285 | In SQL Server 2000, is there a sysobjects query that will retrieve user views and not system views? | Assuming such a query exists, I would greatly appreciate the help. I'm trying to develop a permissions script that will grant "select" and "references" permissions on the user tables and views in a database. My hope is that executing the "grant" commands on each element in such a set will make it easier to keep permissions current when new tables and views are added to the database. | select * from information_schema.tables WHERE OBJECTPROPERTY(OBJECT_ID(table_name),'IsMSShipped') =0 Will exclude dt_properties and system tables add where table_type = 'view' if you just want the view | In SQL Server 2000, is there a sysobjects query that will retrieve user views and not system views? Assuming such a query exists, I would greatly appreciate the help. I'm trying to develop a permissions script that will grant "select" and "references" permissions on the user tables and views in a database. My hope is that executing the "grant" commands on each element in such a set will make it easier to keep permissions current when new tables and views are added to the database. | TITLE:
In SQL Server 2000, is there a sysobjects query that will retrieve user views and not system views?
QUESTION:
Assuming such a query exists, I would greatly appreciate the help. I'm trying to develop a permissions script that will grant "select" and "references" permissions on the user tables and views in a database. My hope is that executing the "grant" commands on each element in such a set will make it easier to keep permissions current when new tables and views are added to the database.
ANSWER:
select * from information_schema.tables WHERE OBJECTPROPERTY(OBJECT_ID(table_name),'IsMSShipped') =0 Will exclude dt_properties and system tables add where table_type = 'view' if you just want the view | [
"sql-server-2000",
"sysobjects"
] | 5 | 6 | 11,126 | 3 | 0 | 2008-08-28T19:48:49.527000 | 2008-08-28T20:11:35.087000 |
33,233 | 33,247 | Integrating a custom gui framework with the VS designer | Imagine you homebrew a custom gui framework that doesn't use windows handles (compact framework, so please don't argue with "whys"). One of the main disadvantages of developing such a framework is that you lose compatability with the winform designer. So my question is to all of you who know a lot about VS customisation, would there be a clever mechanism by which one could incorperate the gui framework into the designer and get it to spit out your custom code instead of the standard windows stuff in the InitialiseComponent() method? | I recently watched a video of these guys who built a WoW AddOn designer for Visual Studio. They overcame the task of getting their completely custom controls to render correctly in the designer. I'm not sure if this is exactly what you need, but might be worth looking at. It's open-source: http://www.codeplex.com/WarcraftAddOnStudio | Integrating a custom gui framework with the VS designer Imagine you homebrew a custom gui framework that doesn't use windows handles (compact framework, so please don't argue with "whys"). One of the main disadvantages of developing such a framework is that you lose compatability with the winform designer. So my question is to all of you who know a lot about VS customisation, would there be a clever mechanism by which one could incorperate the gui framework into the designer and get it to spit out your custom code instead of the standard windows stuff in the InitialiseComponent() method? | TITLE:
Integrating a custom gui framework with the VS designer
QUESTION:
Imagine you homebrew a custom gui framework that doesn't use windows handles (compact framework, so please don't argue with "whys"). One of the main disadvantages of developing such a framework is that you lose compatability with the winform designer. So my question is to all of you who know a lot about VS customisation, would there be a clever mechanism by which one could incorperate the gui framework into the designer and get it to spit out your custom code instead of the standard windows stuff in the InitialiseComponent() method?
ANSWER:
I recently watched a video of these guys who built a WoW AddOn designer for Visual Studio. They overcame the task of getting their completely custom controls to render correctly in the designer. I'm not sure if this is exactly what you need, but might be worth looking at. It's open-source: http://www.codeplex.com/WarcraftAddOnStudio | [
"visual-studio",
"gui-designer"
] | 1 | 1 | 314 | 2 | 0 | 2008-08-28T19:51:37.617000 | 2008-08-28T19:56:48.337000 |
33,250 | 39,091 | Caching Active Directory Data | In one of my applications, I am querying active directory to get a list of all users below a given user (using the "Direct Reports" thing). So basically, given the name of the person, it is looked up in AD, then the Direct Reports are read. But then for every direct report, the tool needs to check the direct reports of the direct reports. Or, more abstract: The Tool will use a person as the root of the tree and then walk down the complete tree to get the names of all the leaves (can be several hundred) Now, my concern is obviously performance, as this needs to be done quite a few times. My idea is to manually cache that (essentially just put all the names in a long string and store that somewhere and update it once a day). But I just wonder if there is a more elegant way to first get the information and then cache it, possibly using something in the System.DirectoryServices Namespace? | In order to take control over the properties that you want to be cached you can call 'RefreshCache()' passing the properties that you want to hang around: System.DirectoryServices.DirectoryEntry entry = new System.DirectoryServices.DirectoryEntry();
// Push the property values from AD back to cache.
entry.RefreshCache(new string[] {"cn", "www" }); | Caching Active Directory Data In one of my applications, I am querying active directory to get a list of all users below a given user (using the "Direct Reports" thing). So basically, given the name of the person, it is looked up in AD, then the Direct Reports are read. But then for every direct report, the tool needs to check the direct reports of the direct reports. Or, more abstract: The Tool will use a person as the root of the tree and then walk down the complete tree to get the names of all the leaves (can be several hundred) Now, my concern is obviously performance, as this needs to be done quite a few times. My idea is to manually cache that (essentially just put all the names in a long string and store that somewhere and update it once a day). But I just wonder if there is a more elegant way to first get the information and then cache it, possibly using something in the System.DirectoryServices Namespace? | TITLE:
Caching Active Directory Data
QUESTION:
In one of my applications, I am querying active directory to get a list of all users below a given user (using the "Direct Reports" thing). So basically, given the name of the person, it is looked up in AD, then the Direct Reports are read. But then for every direct report, the tool needs to check the direct reports of the direct reports. Or, more abstract: The Tool will use a person as the root of the tree and then walk down the complete tree to get the names of all the leaves (can be several hundred) Now, my concern is obviously performance, as this needs to be done quite a few times. My idea is to manually cache that (essentially just put all the names in a long string and store that somewhere and update it once a day). But I just wonder if there is a more elegant way to first get the information and then cache it, possibly using something in the System.DirectoryServices Namespace?
ANSWER:
In order to take control over the properties that you want to be cached you can call 'RefreshCache()' passing the properties that you want to hang around: System.DirectoryServices.DirectoryEntry entry = new System.DirectoryServices.DirectoryEntry();
// Push the property values from AD back to cache.
entry.RefreshCache(new string[] {"cn", "www" }); | [
"c#",
"asp.net",
"active-directory"
] | 4 | 3 | 5,615 | 4 | 0 | 2008-08-28T19:58:10.597000 | 2008-09-02T09:26:14.133000 |
33,252 | 34,465 | Getting files and their version numbers from sharepoint | As a temporary stopgap until all the designers are in place we are currently hand-cranking a whole bunch of xml configuration files at work. One of the issues with this is file-versioning because people forget to update version numbers when updating the files (which is to be expected as humans generally suck at perfection). Therefore I figure that as we store the files in Sharepoint I should be able to write a script to pull the files down from Sharepoint, get the version number and automatically enter/update the version number from Sharepoint into the file. This means when someone wants the "latest" files they can run the script and get the latest files with the version numbers correct (there is slightly more to it than this so the reason for using the script isn't just the benefit of auto-versioning). Does anyone know how to get the files + version numbers from Sharepoint? | There is a way to do it thru web services, but I have done more with implementing custom event handlers. Here is a bit of code that will do what you want. Keep in mind, you can only execute this from the server, so you may want to wrap this up in a web service to allow access from your embedded devices. Also, you will need to reference the Microsoft.SharePoint.dll in this code. using (SPSite site = new SPSite("http://yoursitename/subsite")) { using (SPWeb web = site.OpenWeb()) { SPListItemCollection list = web.Lists["MyDocumentLibrary"].GetItems(new SPQuery()); foreach(SPListItem itm in list) { Stream inStream = itm.File.OpenBinaryStream(); XmlTextReader reader = new XmlTextReader(inStream); XmlDocument xd = new XmlDocument(); xd.Load(reader); //from here you can read whatever XML node that contains your version info reader.Close(); inStream.Close(); } } } The using() statements are to ensure that you do not create a memory leak, as the SPSite and SPWeb are unmanaged objects. Edit: If the version number has been promoted to a library field, you can access it by the following within the for loop above: itm["FieldName"] | Getting files and their version numbers from sharepoint As a temporary stopgap until all the designers are in place we are currently hand-cranking a whole bunch of xml configuration files at work. One of the issues with this is file-versioning because people forget to update version numbers when updating the files (which is to be expected as humans generally suck at perfection). Therefore I figure that as we store the files in Sharepoint I should be able to write a script to pull the files down from Sharepoint, get the version number and automatically enter/update the version number from Sharepoint into the file. This means when someone wants the "latest" files they can run the script and get the latest files with the version numbers correct (there is slightly more to it than this so the reason for using the script isn't just the benefit of auto-versioning). Does anyone know how to get the files + version numbers from Sharepoint? | TITLE:
Getting files and their version numbers from sharepoint
QUESTION:
As a temporary stopgap until all the designers are in place we are currently hand-cranking a whole bunch of xml configuration files at work. One of the issues with this is file-versioning because people forget to update version numbers when updating the files (which is to be expected as humans generally suck at perfection). Therefore I figure that as we store the files in Sharepoint I should be able to write a script to pull the files down from Sharepoint, get the version number and automatically enter/update the version number from Sharepoint into the file. This means when someone wants the "latest" files they can run the script and get the latest files with the version numbers correct (there is slightly more to it than this so the reason for using the script isn't just the benefit of auto-versioning). Does anyone know how to get the files + version numbers from Sharepoint?
ANSWER:
There is a way to do it thru web services, but I have done more with implementing custom event handlers. Here is a bit of code that will do what you want. Keep in mind, you can only execute this from the server, so you may want to wrap this up in a web service to allow access from your embedded devices. Also, you will need to reference the Microsoft.SharePoint.dll in this code. using (SPSite site = new SPSite("http://yoursitename/subsite")) { using (SPWeb web = site.OpenWeb()) { SPListItemCollection list = web.Lists["MyDocumentLibrary"].GetItems(new SPQuery()); foreach(SPListItem itm in list) { Stream inStream = itm.File.OpenBinaryStream(); XmlTextReader reader = new XmlTextReader(inStream); XmlDocument xd = new XmlDocument(); xd.Load(reader); //from here you can read whatever XML node that contains your version info reader.Close(); inStream.Close(); } } } The using() statements are to ensure that you do not create a memory leak, as the SPSite and SPWeb are unmanaged objects. Edit: If the version number has been promoted to a library field, you can access it by the following within the for loop above: itm["FieldName"] | [
"sharepoint",
"versioning"
] | 1 | 1 | 1,924 | 2 | 0 | 2008-08-28T19:58:58.673000 | 2008-08-29T15:35:09.350000 |
33,262 | 33,283 | How do I load an org.w3c.dom.Document from XML in a string? | I have a complete XML document in a string and would like a Document object. Google turns up all sorts of garbage. What is the simplest solution? (In Java 1.5) Solution Thanks to Matt McMinn, I have settled on this implementation. It has the right level of input flexibility and exception granularity for me. (It's good to know if the error came from malformed XML - SAXException - or just bad IO - IOException.) public static org.w3c.dom.Document loadXMLFrom(String xml) throws org.xml.sax.SAXException, java.io.IOException { return loadXMLFrom(new java.io.ByteArrayInputStream(xml.getBytes())); }
public static org.w3c.dom.Document loadXMLFrom(java.io.InputStream is) throws org.xml.sax.SAXException, java.io.IOException { javax.xml.parsers.DocumentBuilderFactory factory = javax.xml.parsers.DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); javax.xml.parsers.DocumentBuilder builder = null; try { builder = factory.newDocumentBuilder(); } catch (javax.xml.parsers.ParserConfigurationException ex) { } org.w3c.dom.Document doc = builder.parse(is); is.close(); return doc; } | This works for me in Java 1.5 - I stripped out specific exceptions for readability. import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import java.io.ByteArrayInputStream;
public Document loadXMLFromString(String xml) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(new ByteArrayInputStream(xml.getBytes())); } | How do I load an org.w3c.dom.Document from XML in a string? I have a complete XML document in a string and would like a Document object. Google turns up all sorts of garbage. What is the simplest solution? (In Java 1.5) Solution Thanks to Matt McMinn, I have settled on this implementation. It has the right level of input flexibility and exception granularity for me. (It's good to know if the error came from malformed XML - SAXException - or just bad IO - IOException.) public static org.w3c.dom.Document loadXMLFrom(String xml) throws org.xml.sax.SAXException, java.io.IOException { return loadXMLFrom(new java.io.ByteArrayInputStream(xml.getBytes())); }
public static org.w3c.dom.Document loadXMLFrom(java.io.InputStream is) throws org.xml.sax.SAXException, java.io.IOException { javax.xml.parsers.DocumentBuilderFactory factory = javax.xml.parsers.DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); javax.xml.parsers.DocumentBuilder builder = null; try { builder = factory.newDocumentBuilder(); } catch (javax.xml.parsers.ParserConfigurationException ex) { } org.w3c.dom.Document doc = builder.parse(is); is.close(); return doc; } | TITLE:
How do I load an org.w3c.dom.Document from XML in a string?
QUESTION:
I have a complete XML document in a string and would like a Document object. Google turns up all sorts of garbage. What is the simplest solution? (In Java 1.5) Solution Thanks to Matt McMinn, I have settled on this implementation. It has the right level of input flexibility and exception granularity for me. (It's good to know if the error came from malformed XML - SAXException - or just bad IO - IOException.) public static org.w3c.dom.Document loadXMLFrom(String xml) throws org.xml.sax.SAXException, java.io.IOException { return loadXMLFrom(new java.io.ByteArrayInputStream(xml.getBytes())); }
public static org.w3c.dom.Document loadXMLFrom(java.io.InputStream is) throws org.xml.sax.SAXException, java.io.IOException { javax.xml.parsers.DocumentBuilderFactory factory = javax.xml.parsers.DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); javax.xml.parsers.DocumentBuilder builder = null; try { builder = factory.newDocumentBuilder(); } catch (javax.xml.parsers.ParserConfigurationException ex) { } org.w3c.dom.Document doc = builder.parse(is); is.close(); return doc; }
ANSWER:
This works for me in Java 1.5 - I stripped out specific exceptions for readability. import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import java.io.ByteArrayInputStream;
public Document loadXMLFromString(String xml) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(new ByteArrayInputStream(xml.getBytes())); } | [
"java",
"xml",
"document",
"w3c"
] | 108 | 83 | 140,234 | 4 | 0 | 2008-08-28T20:03:19.477000 | 2008-08-28T20:11:00.160000 |
33,265 | 33,391 | What's the false operator in C# good for? | There are two weird operators in C#: the true operator the false operator If I understand this right these operators can be used in types which I want to use instead of a boolean expression and where I don't want to provide an implicit conversion to bool. Let's say I have a following class: public class MyType { public readonly int Value;
public MyType(int value) { Value = value; }
public static bool operator true (MyType mt) { return mt.Value > 0; }
public static bool operator false (MyType mt) { return mt.Value < 0; }
} So I can write the following code: MyType mTrue = new MyType(100); MyType mFalse = new MyType(-100); MyType mDontKnow = new MyType(0);
if (mTrue) { // Do something. }
while (mFalse) { // Do something else. }
do { // Another code comes here. } while (mDontKnow) However for all the examples above only the true operator is executed. So what's the false operator in C# good for? Note: More examples can be found here, here and here. | You can use it to override the && and || operators. The && and || operators can't be overridden, but if you override |, &, true and false in exactly the right way the compiler will call | and & when you write || and &&. For example, look at this code (from http://ayende.com/blog/1574/nhibernate-criteria-api-operator-overloading - where I found out about this trick; archived version by @BiggsTRC): public static AbstractCriterion operator &(AbstractCriterion lhs, AbstractCriterion rhs) { return new AndExpression(lhs, rhs); }
public static AbstractCriterion operator |(AbstractCriterion lhs, AbstractCriterion rhs) { return new OrExpression(lhs, rhs); }
public static bool operator false(AbstractCriterion criteria) { return false; } public static bool operator true(AbstractCriterion criteria) { return false; } This is obviously a side effect and not the way it's intended to be used, but it is useful. | What's the false operator in C# good for? There are two weird operators in C#: the true operator the false operator If I understand this right these operators can be used in types which I want to use instead of a boolean expression and where I don't want to provide an implicit conversion to bool. Let's say I have a following class: public class MyType { public readonly int Value;
public MyType(int value) { Value = value; }
public static bool operator true (MyType mt) { return mt.Value > 0; }
public static bool operator false (MyType mt) { return mt.Value < 0; }
} So I can write the following code: MyType mTrue = new MyType(100); MyType mFalse = new MyType(-100); MyType mDontKnow = new MyType(0);
if (mTrue) { // Do something. }
while (mFalse) { // Do something else. }
do { // Another code comes here. } while (mDontKnow) However for all the examples above only the true operator is executed. So what's the false operator in C# good for? Note: More examples can be found here, here and here. | TITLE:
What's the false operator in C# good for?
QUESTION:
There are two weird operators in C#: the true operator the false operator If I understand this right these operators can be used in types which I want to use instead of a boolean expression and where I don't want to provide an implicit conversion to bool. Let's say I have a following class: public class MyType { public readonly int Value;
public MyType(int value) { Value = value; }
public static bool operator true (MyType mt) { return mt.Value > 0; }
public static bool operator false (MyType mt) { return mt.Value < 0; }
} So I can write the following code: MyType mTrue = new MyType(100); MyType mFalse = new MyType(-100); MyType mDontKnow = new MyType(0);
if (mTrue) { // Do something. }
while (mFalse) { // Do something else. }
do { // Another code comes here. } while (mDontKnow) However for all the examples above only the true operator is executed. So what's the false operator in C# good for? Note: More examples can be found here, here and here.
ANSWER:
You can use it to override the && and || operators. The && and || operators can't be overridden, but if you override |, &, true and false in exactly the right way the compiler will call | and & when you write || and &&. For example, look at this code (from http://ayende.com/blog/1574/nhibernate-criteria-api-operator-overloading - where I found out about this trick; archived version by @BiggsTRC): public static AbstractCriterion operator &(AbstractCriterion lhs, AbstractCriterion rhs) { return new AndExpression(lhs, rhs); }
public static AbstractCriterion operator |(AbstractCriterion lhs, AbstractCriterion rhs) { return new OrExpression(lhs, rhs); }
public static bool operator false(AbstractCriterion criteria) { return false; } public static bool operator true(AbstractCriterion criteria) { return false; } This is obviously a side effect and not the way it's intended to be used, but it is useful. | [
"c#",
".net",
"syntax"
] | 108 | 66 | 11,298 | 5 | 0 | 2008-08-28T20:06:01.840000 | 2008-08-28T21:02:48.333000 |
33,288 | 33,295 | Protecting API Secret Keys in a Thick Client application | Within an application, I've got Secret Keys uses to calculate a hash for an API call. In a.NET application it's fairly easy to use a program like Reflector to pull out information from the assembly to include these keys. Is obfuscating the assembly a good way of securing these keys? | Probably not. Look into cryptography and Windows' built-in information-hiding mechanisms (DPAPI and storing the keys in an ACL-restricted registry key, for example). That's as good as you're going to get for security you need to keep on the same system as your application. If you are looking for a way to stop someone physically sitting at the machine from getting your information, forget it. If someone is determined, and has unrestricted access to a computer that is not under your control, there is no way to be 100% certain that the data is protected under all circumstances. Someone who is determined will get at it if they want to. | Protecting API Secret Keys in a Thick Client application Within an application, I've got Secret Keys uses to calculate a hash for an API call. In a.NET application it's fairly easy to use a program like Reflector to pull out information from the assembly to include these keys. Is obfuscating the assembly a good way of securing these keys? | TITLE:
Protecting API Secret Keys in a Thick Client application
QUESTION:
Within an application, I've got Secret Keys uses to calculate a hash for an API call. In a.NET application it's fairly easy to use a program like Reflector to pull out information from the assembly to include these keys. Is obfuscating the assembly a good way of securing these keys?
ANSWER:
Probably not. Look into cryptography and Windows' built-in information-hiding mechanisms (DPAPI and storing the keys in an ACL-restricted registry key, for example). That's as good as you're going to get for security you need to keep on the same system as your application. If you are looking for a way to stop someone physically sitting at the machine from getting your information, forget it. If someone is determined, and has unrestricted access to a computer that is not under your control, there is no way to be 100% certain that the data is protected under all circumstances. Someone who is determined will get at it if they want to. | [
"web-services",
"security",
"api"
] | 4 | 8 | 2,329 | 4 | 0 | 2008-08-28T20:11:54.867000 | 2008-08-28T20:14:55.063000 |
33,301 | 33,440 | Call onresize from ASP.NET content page | I have a JavaScript method that I need to run on one of my pages, in particular, the onresize event. However, I don't see how I can set that event from my content page. I wish I could just put it on my master page, but I don't have the need for the method to be called on all pages that use that master page. Any help would be appreciated. | Place the following in your content page: That code should give you the basic idea of what you need to do. Hopefully you are using a library that already has code to help you write up event handlers and such. | Call onresize from ASP.NET content page I have a JavaScript method that I need to run on one of my pages, in particular, the onresize event. However, I don't see how I can set that event from my content page. I wish I could just put it on my master page, but I don't have the need for the method to be called on all pages that use that master page. Any help would be appreciated. | TITLE:
Call onresize from ASP.NET content page
QUESTION:
I have a JavaScript method that I need to run on one of my pages, in particular, the onresize event. However, I don't see how I can set that event from my content page. I wish I could just put it on my master page, but I don't have the need for the method to be called on all pages that use that master page. Any help would be appreciated.
ANSWER:
Place the following in your content page: That code should give you the basic idea of what you need to do. Hopefully you are using a library that already has code to help you write up event handlers and such. | [
"asp.net",
"javascript",
"master-pages",
"onresize"
] | 4 | 4 | 6,815 | 3 | 0 | 2008-08-28T20:24:04.887000 | 2008-08-28T21:25:35.003000 |
33,306 | 33,313 | C++ STL question: allocators | I have a (potentially dumb) question about the C++ STL. When I make a container (vector, set, map, etc), is it allocated on the stack or on the heap? If I make a set and put 5 million strings, will I have to worry about a stack overflow? | STL classes by default allocate their internal buffers from the heap, although these classes also allow custom allocators that allow a user to specify an alternate location to allocate from - e.g. a shared memory pool. | C++ STL question: allocators I have a (potentially dumb) question about the C++ STL. When I make a container (vector, set, map, etc), is it allocated on the stack or on the heap? If I make a set and put 5 million strings, will I have to worry about a stack overflow? | TITLE:
C++ STL question: allocators
QUESTION:
I have a (potentially dumb) question about the C++ STL. When I make a container (vector, set, map, etc), is it allocated on the stack or on the heap? If I make a set and put 5 million strings, will I have to worry about a stack overflow?
ANSWER:
STL classes by default allocate their internal buffers from the heap, although these classes also allow custom allocators that allow a user to specify an alternate location to allocate from - e.g. a shared memory pool. | [
"c++",
"stl"
] | 6 | 9 | 1,480 | 3 | 0 | 2008-08-28T20:26:14.193000 | 2008-08-28T20:28:13.177000 |
33,334 | 33,683 | How do you find what debug switches are available? Or given a switch find out what is being disabled? | In this question the answer was to flip on a switch that is picked up by the debugger disabling the extraneous header that was causing the problem. The Microsoft help implies these switched are user generated and does not list any switches. What I would like to know is where the value "Remote.Disable" comes from and how find out what other things can be switched on or off. Currently it is just some config magic, and I don't like magic. | As you suspected, Remote.Disable stops the app from attaching debug info to remote requests. It's defined inside the.NET framework methods that make the SOAP request. The basic situation is that these switches can be defined anywhere in code, you just need to create a new System.Diagnostics.BooleanSwitch with the name given and the config file can control them. This particular one is defined in System.ComponentModel.CompModSwitches.DisableRemoteDebugging: public static BooleanSwitch DisableRemoteDebugging { get { if (disableRemoteDebugging == null) { disableRemoteDebugging = new BooleanSwitch("Remote.Disable", "Disable remote debugging for web methods."); } return disableRemoteDebugging; } } In your case it's probably being called from System.Web.Services.Protocols.RemoteDebugger.IsClientCallOutEnabled(), which is being called by System.Web.Services.Protocols.WebClientProtocol.NotifyClientCallOut which is in turn being called by the Invoke method of System.Web.Services.Protocols.SoapHttpClientProtocol Unfortunately, to my knowledge, short of decompiling the framework & seaching for new BooleanSwitch or any of the other inheritors of the System.Diagnostics.Switch class, there's no easy way to know what switches are defined. It seems to be a case of searching msdn/google/stack overflow for the specific case In this case I just used Reflector & searched for the Remote.Disable string | How do you find what debug switches are available? Or given a switch find out what is being disabled? In this question the answer was to flip on a switch that is picked up by the debugger disabling the extraneous header that was causing the problem. The Microsoft help implies these switched are user generated and does not list any switches. What I would like to know is where the value "Remote.Disable" comes from and how find out what other things can be switched on or off. Currently it is just some config magic, and I don't like magic. | TITLE:
How do you find what debug switches are available? Or given a switch find out what is being disabled?
QUESTION:
In this question the answer was to flip on a switch that is picked up by the debugger disabling the extraneous header that was causing the problem. The Microsoft help implies these switched are user generated and does not list any switches. What I would like to know is where the value "Remote.Disable" comes from and how find out what other things can be switched on or off. Currently it is just some config magic, and I don't like magic.
ANSWER:
As you suspected, Remote.Disable stops the app from attaching debug info to remote requests. It's defined inside the.NET framework methods that make the SOAP request. The basic situation is that these switches can be defined anywhere in code, you just need to create a new System.Diagnostics.BooleanSwitch with the name given and the config file can control them. This particular one is defined in System.ComponentModel.CompModSwitches.DisableRemoteDebugging: public static BooleanSwitch DisableRemoteDebugging { get { if (disableRemoteDebugging == null) { disableRemoteDebugging = new BooleanSwitch("Remote.Disable", "Disable remote debugging for web methods."); } return disableRemoteDebugging; } } In your case it's probably being called from System.Web.Services.Protocols.RemoteDebugger.IsClientCallOutEnabled(), which is being called by System.Web.Services.Protocols.WebClientProtocol.NotifyClientCallOut which is in turn being called by the Invoke method of System.Web.Services.Protocols.SoapHttpClientProtocol Unfortunately, to my knowledge, short of decompiling the framework & seaching for new BooleanSwitch or any of the other inheritors of the System.Diagnostics.Switch class, there's no easy way to know what switches are defined. It seems to be a case of searching msdn/google/stack overflow for the specific case In this case I just used Reflector & searched for the Remote.Disable string | [
".net",
"app-config"
] | 4 | 2 | 3,125 | 2 | 0 | 2008-08-28T20:35:07.060000 | 2008-08-28T23:57:57.460000 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.