问:
What's the simplest way to provide a portable, locally running webservice server application?
We have a large website running that offers a JsonRpc web service.

For offline demonstration purposes, I want to realize a portable, locally running webserver with a minimalistic feature replication of the live webservice, and bundle this together with Html files which do Ajax requests to it.
This local server executable should have as little dependencies as possible.

It's going to be run and presented by non-devs on non-dev Windows machines, so I would prefer having a simple executable plus the service code.  The language would need to be .NET, PHP or Java.

I'll need a small database behind which probably will be Sqlite.

It's important to say that, for reasons I won't get into here, we cannot use the original web service code, but we have to rewrite it new for the local demo server. This is why I want to put minimal effort in the local server tech.

An installer for distribution is not mandatory, it's okay to have a zip file with an executable in it which starts up the local webserver.

What would you recommend realizing these requirements?

答:
Tomcat is a great stand-alone web server for Java apps.  It's small, fast, and the reference implementation for the Java Servlet Specification.

I don't know enough about PHP and .NET to suggest small web servers servers that are especially friendly to those technologies.


答:
Jetty is a good choice if you can package your files as a WAR.

Jetty provides an HTTP server, HTTP client, and javax.servlet
  container. These components are open source and available for
  commercial use and distribution.

--From Jetty's website

ContentLicense: CC BY-SA 3.0

Title: What's the simplest way to provide a portable, locally running webservice server application?

Body:
We have a large website running that offers a JsonRpc web service.

For offline demonstration purposes, I want to realize a portable, locally running webserver with a minimalistic feature replication of the live webservice, and bundle this together with Html files which do Ajax requests to it.
This local server executable should have as little dependencies as possible.

It's going to be run and presented by non-devs on non-dev Windows machines, so I would prefer having a simple executable plus the service code.  The language would need to be .NET, PHP or Java.

I'll need a small database behind which probably will be Sqlite.

It's important to say that, for reasons I won't get into here, we cannot use the original web service code, but we have to rewrite it new for the local demo server. This is why I want to put minimal effort in the local server tech.

An installer for distribution is not mandatory, it's okay to have a zip file with an executable in it which starts up the local webserver.

What would you recommend realizing these requirements?


答: If you want to go the .NET route, a few lines of code is all it takes to spin up a Self-Hosted  Web API instance. It can be run in a console app, or with a few more lines of code  it can be installed as a Windows Service.


问:
How do I Export to excel on aspx page?
I am trying to take data that I request from an access database and put it into and excel file on the client computer.

I usually use ajax to request a summary of the data I need. It is formatted into an html table.

I need that table to be in an excel format for the user to download.

What I have tried already is to use the vb.net code to open excel and silently save the data to a file, however I realized it's the server side that opens excel, not the client side, in my locally testing of the code, excel would open on my machine and create the file.

When running this on the network, I realized excel isn't on the server, I am not sure if I should just install it or try stream the file?

答:
You should look into using a library that doesn't require Excel to be installed; one such example is EPPlus.

There are others, as mentioned in this SO question:
How to programmatically create a “true” Excel file

Title: How do I Export to excel on aspx page?


问:
Coded ui to measure performance
I have been tasked with using coded UI to measure performance on a proprietary windows desktop application.  The need is to measure how long it takes for the next page/screen to display after a user clicks on a control.

For example - a user enters their ID and PW and clicks sign-in.  The need is to measure how long it takes for the next screen to display when the user clicks the sign-in button.  I understand the need to define what indicates the screen is loaded and ready for use.  One approach is to use control.WaitForControlReady and use BeginTimer/EndTimer.

Is coded ui a dependable and accurate way of measuring time?

Is WaitForControlReady the best method to determine when a control is ready for use?

答:
Hard: Log Total Time

If you have a

OwnerDisplayName: Mike Weber

Title: Coded ui to measure performance

Body:
Hard: Log Total Time

If you have a <script> section at the end of your HTML page, it won't get executed until the rest of the page is fully loaded and probably rendered (but check me on that).  Note that the client and server probably won't have the same clock time, but you could have a <script> tag at the end of your document send an AJAX request back to the server with a built-in unique token telling the server, "Request (request-identifier) is complete and displayed by the browser."

On the server side, the requests you want to time would have to put a hashtable of the original request-identifiers and timestamps in the user's session.  The "request-complete" message from that user will come in as a new request which should look up the request-identifier for the request in the session, get the start time-stamp, and write the end-time minus start-time difference to a log or whatever.  Then it should remove that request-identifier from the hashtable.

Actually, you may need to clean up the hashtable, especially if the user cancels a request (it will never complete) or logs out, or just closes their browser.  Also if the user requests anything that doesn't end in your all-done JavaScript, such as images, pages you forgot to add the tag to, etc.  This probably isn't something you want to leave running in production code.

Simpler: Log Request Time and Rendering Time Separately

Something easier to measure and probably just about as useful from a business perspective is how long it takes the web server to serve the request.  The main method of our master-servlet starts with:

// Start timing the request
long startMs = System.currentTimeMillis();

And ends with:

long elapsedMs = System.currentTimeMillis() - startMs;

if (elapsedMs > LONG_TIME) {
    logger.error("Done REALLY SLOWLY: " + elapsedMs + "ms");
} else if (elapsedMs > PRETTY_LONG_TIME) {
    logger.warn("Done SLOWLY: " + elapsedMs + "ms");
} else {
    logger.info("Done: " + elapsedMs + "ms");
}

Now your application logs on your server have errors for long requests.  You could even have it page you if something is slow!  To tell the difference between browser time and server time, just use the built-in tools in Chrome or Firefox that show how long each part of a page building took.  There's a timeline graph and other great stuff built-in there.

Maybe if you have an all-AJAX application it's an issue, but you can build this same timing into your server-side and send a timing result to the server.


答:
Then you want a self-contained binary. That means you really want to write your code using a web service library that can be compiled into your program.

Now you just need to decide which one! You could use node.js, but that requires node + some javascript codefiles to be deployed. However, as you already have html files you only have to deploy a directory with an batch file to run it all. Node is a good choice if you want to emulate a client too as it can come with a heap of nice javascript libs such as express.

You could write it in .NET but you'd have to be careful of using the .NET runtime that goes with the server you're running it on - you do not want a huge .NET framework download, nor do you want to have to deploy all the windows updates for it (but you do want to deploy all the security updates, obviously).

You could write it in C++ using Windows Web Services or gSoap (nice and fast too) and deploy just a single .exe, but I've never seen one deployed with all html and resources compiled into a single exe - its possible though, serve these files from inside the exe resource block.

SQLite is an excellent choice BTW.


问:
Why does Javascript use JSON.stringify instead of JSON.serialize?
I'm just wondering about "stringify" vs "serialize". To me they're the same thing (though I could be wrong), but in my past experience (mostly with asp.net) I use Serialize() and never use Stringify().

I know I can create a simple alias in Javascript,

```<code>// either
JSON.serialize = function(input) {
    return JSON.stringify(input);
};

// or
JSON.serialize = JSON.stringify;
</code>```

http://jsfiddle.net/HKKUb/

but I'm just wondering about the difference between the two and why stringify was chosen.

for comparison purpose, here's how you serialize XML to a String in C#

```<code>public static string SerializeObject<T>(this T toSerialize)
{
    XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
    StringWriter textWriter = new StringWriter();

    xmlSerializer.Serialize(textWriter, toSerialize);
    return textWriter.ToString();
}
</code>```

答:
Take a closer look at the two comments you've put onto the question:

I suppose after re-reading my question, I'm seeing that in my C#
  example, I'm serializing the XML and THEN converting the serialized
  object ToString();. There inlies the rub.

and

I guess for continuity, it would be better (for me) to have a method
  that looks like this... JSON.serialize(obj).toString(); or
  jsonObject().toString();... this way it would look much like my C#...
  but now I'm over complicating it.

Now remember that in Javascript, an object is a hash (rather, if using Prototype or another framework, it should be qualified as a "special kind of hash" - but the simple form works for this example):

```<code>var obj = {
   foo: 1,
   bar: function() { console.log(this.foo); }
}
obj.foo; // 1
obj.bar; // function reference
obj.bar(); // function call
obj['foo']; // 1
obj['bar']; // function reference
obj['bar'](); // function call
</code>```

The only reason a serialize() might be necessary in Javascript is to cut out the functions, references to other objects, etc.

So, to go back to your C# example - we've just cut out .Serialize() as unnecessary.  An object is a hash, it's already serialized, further "serialization" would have to be done manually in your own code anyway.  All that leaves you is .ToString().

Does .stringify() make more sense now?

Body:
Take a closer look at the two comments you've put onto the question:

I suppose after re-reading my question, I'm seeing that in my C#
  example, I'm serializing the XML and THEN converting the serialized
  object ToString();. There inlies the rub.

and

I guess for continuity, it would be better (for me) to have a method
  that looks like this... JSON.serialize(obj).toString(); or
  jsonObject().toString();... this way it would look much like my C#...
  but now I'm over complicating it.

Now remember that in Javascript, an object is a hash (rather, if using Prototype or another framework, it should be qualified as a "special kind of hash" - but the simple form works for this example):

var obj = {
   foo: 1,
   bar: function() { console.log(this.foo); }
}
obj.foo; // 1
obj.bar; // function reference
obj.bar(); // function call
obj['foo']; // 1
obj['bar']; // function reference
obj['bar'](); // function call

The only reason a serialize() might be necessary in Javascript is to cut out the functions, references to other objects, etc.

So, to go back to your C# example - we've just cut out .Serialize() as unnecessary.  An object is a hash, it's already serialized, further "serialization" would have to be done manually in your own code anyway.  All that leaves you is .ToString().

Does .stringify() make more sense now?


答: If you're fine with it being PHP and only being on Windows, I can definitely recommend Server2Go (http://www.server2go-web.de/). It let's you run a full WAMP stack, with options to, for example, keep changes to the DB over time or reset it each time the application is run, plus auto loading a browser if you want. </p>


问:
Review before or after code commit, which is better?
Traditionally we performed code review before commit, I had an argument with my colleague today, who preferred code review after commit.

First, here's some background,

We have some experienced developers and we also have new hires with almost zero programming experience.

We'd like to perform fast and short iterations to release our product.

All team members are located at the same site.

The advantages of code review before commit I've learned:

Mentor new hires

Try to prevent errors, failures, bad designs early in the development cycle

Learn from others

Knowledge backup if someone quits

But I've also had some bad experiences:

Low efficiency, some changes may be reviewed over days

Hard to balance speed and quality, especially for newbies

One team member felt distrust

As to post-commit review, I know little about this, but the thing I'm most worried about is the risk of losing control due to lack of review.
Any opinions?

UPDATE:

We're using Perforce for VCS

We code and commit in the same branches (trunk or bug fixing branches)

To improve efficiency, we've tried to split code into small changes. We've also tried some live dialog review, but not everyone followed the rule. This is another problem though.

答:
Do both :

pre commit - do this kind of reviews when it is something very important, like a very reusable code piece, or major design decision

post commit - do this kind of a reviews when you want to get opinion on a piece of code that might be improved


问:
Is deserializing complex objects instead of creating them a good idea, in test setup?
I'm writing tests for a component that takes very complex objects as input. These tests are mixes of tests against already existing components, and test-first tests for new features.

Instead of re-creating my input objects (this would be a large chunk of code) or reading one from our data store, I had the thought to serialize a live instance of one of these objects, and just deserialize it into test setup.

I can't decide if this is a reasonable idea that will save effort in long run, or whether it's the worst idea that I've ever had, causing those that will maintain this code will hunt me down as soon as they read it.

Is deserialization of inputs a valid means of test setup in some cases?

To give a sense of scale of what I'm dealing with, the size of serialization output for one of these input objects is 93KB. Obtained by, in C#:

new BinaryFormatter().Serialize((Stream)fileStream, myObject);

答:
The biggest issue you will face with this scheme is that of versioning - if any of the types in your serialized graph changes (property added/removed/renamed for instance), serialization is likely to fail as will all the tests that rely on the object graph that was serialized.

For that reason alone I would avoid serialization. Use a builder method instead.


问:
Entity Framework with large systems - how to divide models?
I'm working with a SQL Server database with 1000+ tables, another few hundred views, and several thousand stored procedures.  We are looking to start using Entity Framework for our newer projects, and we are working on our strategy for doing so.  The thing I'm hung up on is how best to split the tables into different models (EDMX or DbContext if we go code first).  I can think of a few strategies right off the bat:

Split by schema

We have our tables split across probably a dozen schemas.  We could do one model per schema.  This isn't perfect, though, because dbo still ends up being very large, with 500+ tables / views.  Another problem is that certain units of work will end up having to do transactions that span multiple models, which adds to complexity, although I assume EF makes this fairly straightforward.

Split by intent

Instead of worrying about schemas, split the models by intent.  So we'll have different models for each application, or project, or module, or screen, depending on how granular we want to get.  The problem I see with this is that there are certain tables that inevitably have to be used in every case, such as User or AuditHistory.  Do we add those to every model (violates DRY I think), or are those in a separate model that is used by every project?

Don't split at all - one giant model

This is obviously simple from a development perspective but from my research and my intuition this seems like it could perform terribly, both at design time, compile time, and possibly run time.

What is the best practice for using EF against such a large database?  Specifically what strategies do people use in designing models against this volume of DB objects?  Are there options that I'm not thinking of that work better than what I have above?

Also, is this a problem in other ORMs such as NHibernate?  If so have they come up with any better solutions than EF?

答:
Personally, I've tried making one huge schema for all my entities on a fairly complex but small project(~300 tables) . We had an extremely normalized database (5th form normalization (I say that loosely)) with many "many to many" relationships and extreme referential integrity enforcement.

We also used a "single instance per request" strategy which I'm not convinced helped either.

When doing simple, reasonably flat "explicitly defined" listings, lookups and saves the performance was generally acceptable. But when we started digging into deep relationships the performance seemed to take drastic dips. Compared to a stored proc in this instance, there was no comparison (of course). I'm sure we could've tweaked the code base here and there to get the performance improved, however, in this case we just needed performance boost without analysis due to time constraints, and we fell back to the stored proc (still mapped it through EF, because EF provided strongly typed results), we only needed that as a fall back in a few area's. When we had to traverse all over the database to create a collection (using .include() unsparingly), the performance was noticeably degrading, but maybe we were asking too much..

So based on my experience, i would recommend creating a separate .edmx per intent. Only generate what you'll be using based on the scope of that need. You may have some smaller scoped .edmx files for purposed tasks, and then some large ones where you need to traverse complex relationships to build objects. I'm not sure where that magic spot is, but I'm sure there is one... lol...

Honestly though, aside from a few pitfalls which we kind of saw coming (complex traversing), the huge .edmx worked fine from a "working" perspective. But you'll have to watch out for the "fixup" magic that the context does behind the scene's if you don't explicitly disable it. As well as keeping the .edmx in sync when changes to the database are made.. it was sometimes easier to wipe the entire surface and re-create the entities, which took like 3 minutes so it wasn't a big deal.

This was all with EntityFramework 4.1. I'd be really interested in hearing about your end choice and experience as well.

And regarding you're question on nHibernate, that's a can of worms question in my opinion, you'll get barking on both sides of the fence... I hear a lot of people bashing EF for the sake of bashing without working through the challenges and understanding the nuances unique to EF itself.. and although I've never used nHibernate in production, generally, if you have to manually and explicitly create things like mappings, you're going to get more finite control, however, if you can drag n' drop , generate, and start CRUD'ing and querying using LINQ, I could give a crap about granularity.

I hope this helps.


答:
Creating objects manually tests the code involved in creating the object. Traditionally, this area of the code is very poorly exercised in tests, especially if compared to the code of your business logic. Going the serialization route is definitely possible, but you should keep in mind that you may need to add more tests to verify the object creation code through the regular non-serialization API.

If you do decide to use serialized instances, try making the format human-readable (XML? JSON?), perhaps at the cost of producing a larger file. This will let you deal with small insignificant version changes better than with the binary-serialized objects.

Title: Is deserializing complex objects instead of creating them a good idea, in test setup?

Body:
I'm writing tests for a component that takes very complex objects as input. These tests are mixes of tests against already existing components, and test-first tests for new features.

Instead of re-creating my input objects (this would be a large chunk of code) or reading one from our data store, I had the thought to serialize a live instance of one of these objects, and just deserialize it into test setup.

I can't decide if this is a reasonable idea that will save effort in long run, or whether it's the worst idea that I've ever had, causing those that will maintain this code will hunt me down as soon as they read it.

Is deserialization of inputs a valid means of test setup in some cases?

To give a sense of scale of what I'm dealing with, the size of serialization output for one of these input objects is 93KB. Obtained by, in C#:

new BinaryFormatter().Serialize((Stream)fileStream, myObject);


答:
Let me start by simple clarification: I don't have experience with such large database so the rest of my answer is not based on the real world example.

So you have a BIG database and you want to use it with ORM / EF. I would go with the second choice. Here is my simple explanation why:

Mapping adds complexity. There is no need to add complexity with entities your current application / project / module never needs but don't make granularity too low level. Having separate mapping set per screen will not help you as well.

You want to achieve unit of work. You should be able to specify what tables module needs in the most cases (not necessary in all cases). If you put these tables into single mapping set you will be able to handle reading and data modification by single context instance - that is what should be your ultimate target.

I'm not sure what exactly you mean by model but even with different mapping sets you can share classes between mapping sets using same entity types. So if you use User table in two modules you don't need two User classes to represent the same. You can still use single table and in case of code mapping (aka code-first) you can even define mapping once and load it to multiple mapping sets so the DRY principle is not violated but the code-first approach has more limitations when it comes to views and stored procedures. EDMX makes this harder. You can still reuse classes but reusing mapping impossible.

What about cross module queries? These queries may happen but to be honest not everything must be handled by EF. You can take advantage of EF for common cases to simplify regular data access but if you have somewhere need for special query which joins tables belonging to 5 different modules you can simply execute it directly or wrap it in stored procedure. 100% replacement of native data access can be hard, complex and contra-productive.

The last point is simply practical: I don't believe that VS tooling is ready to work with such large set of objects - not in designer, not even with importing tool. I used to work on very large database with traditional data access and SQL Database project in VS2008 - the user experience with a complex project was very bad. You must keep the number of used tables low - the cap for designer should be somewhere between 100-200 but even 100 tables handled by single context (mapping set) sounds like too much responsibility for one class (suppose that you will have 100 set properties exposed on the context - it doesn't look like a good design).

Title: Entity Framework with large systems - how to divide models?

Body:
I'm working with a SQL Server database with 1000+ tables, another few hundred views, and several thousand stored procedures.  We are looking to start using Entity Framework for our newer projects, and we are working on our strategy for doing so.  The thing I'm hung up on is how best to split the tables into different models (EDMX or DbContext if we go code first).  I can think of a few strategies right off the bat:

Split by schema

We have our tables split across probably a dozen schemas.  We could do one model per schema.  This isn't perfect, though, because dbo still ends up being very large, with 500+ tables / views.  Another problem is that certain units of work will end up having to do transactions that span multiple models, which adds to complexity, although I assume EF makes this fairly straightforward.

Split by intent

Instead of worrying about schemas, split the models by intent.  So we'll have different models for each application, or project, or module, or screen, depending on how granular we want to get.  The problem I see with this is that there are certain tables that inevitably have to be used in every case, such as User or AuditHistory.  Do we add those to every model (violates DRY I think), or are those in a separate model that is used by every project?

Don't split at all - one giant model

This is obviously simple from a development perspective but from my research and my intuition this seems like it could perform terribly, both at design time, compile time, and possibly run time.

What is the best practice for using EF against such a large database?  Specifically what strategies do people use in designing models against this volume of DB objects?  Are there options that I'm not thinking of that work better than what I have above?

Also, is this a problem in other ORMs such as NHibernate?  If so have they come up with any better solutions than EF?


问:
Should Git be used for documentation and project management? Should the code be in a separate repository?
I'm starting up a Git repository for a group project. Does it make sense to store documents in the same Git repository as code - it seems like this conflicts with the nature of the git revision flow.

Here is a summary of my question(s):

Is the Git revisioning style going to be confusing if both code and documents are checked into the same repository? Experiences with this?

Is Git a good fit for documentation revision control?

I am NOT asking if a Revision Control System in general should or shouldn't be used for documentation - it should.

Thanks for the feedback so far!

答:
Having more than just source code in a repository is a very good thing.

It groups all of your resources together and turns the project into a cohesive, centralized entity rather than a scattered collection of files. Contributors/employees know where to find everything, rather than sending "Where do I change the documentation for feature x?" emails.

You'll want to keep things organized. Have a system for separating the src from the images from the docs. You can always add a .gitignore to a directory to keep the repository and history clean. Because Git commits are file-based,* you can decouple source changes from documentation changes as strongly as you like.

As others have said, Git is great for documentation versioning as long as it's text-based.

I completely agree; documentation should be versioned right alongside the code.

My credibility comes from being a GitHub user and contributing to one project and exploring many others. In my experience, a complete, unified project is easy to tell from a half-missing one. I try to contain all of my projects within single directories whenever possible.

* This isn't quite accurate, because there are ways to specify parts of a file to be committed (here's one example).

OwnerDisplayName: EmpireJones


问:
How much Ruby should I learn before moving to Rails?
Just a quick question..

I can never get a definitive answer when googling this, either. Some people say you can learn Rails without knowing any Ruby, but at some point you'll run into a brick wall and wish you knew Ruby and will have to go back to learn it..and some say to learn the "basics" of Ruby before learning Rails and it will make your life that much easier..

My current knowledge is low. I'm not a beginner, but I'm not pro, either. I went through the Learn Python The Hard Way online book in about a month, but I stopped once I got to the OOP side of Python (I know booleans, elif/if/else/statements, for loops, while loops, functions)

I agree with learning the "basics" of Ruby before learning Rails, but what exactly are the "basics" of Ruby? Would I need to learn the whole OOP side of Ruby before I went on to Rails? Or would I just need to learn the Ruby syntax up to where I learned Python (booleans, elif/if/else/statements, for loops, while loops, functions) before I went on to Rails?
Thanks!

答:
I am very happy that I went Ruby,  Sinatra,  Rake,  then Rails.

Sinatra is a very useful micro framework that you will keep using even after you master Rails. Rake is an integral piece of Rails and understanding it prior to diving into Rails is beneficial.

I would suggest a similar route to anyone else.


答:
In my opinion, code peer review works best if done post-commit.

I would recommend adjusting your branching strategy. Using a developer branch or feature branch has a number of benefits... not the least of which is facilitating post-commit code reviews.

A tool like Crucible will smooth and automate the review process. You can select one or more committed changesets to include in the review. Crucible it will show which files were touched in the selected changesets, keep track of which files each reviewer has already read (showing a % complete overall) and let the reviewers easily make comments.

http://www.atlassian.com/software/crucible/overview

Some other benefits of user/feature branches:

Developers get the benefits of version control (back up changes, restore from history, diff changes) with less worry about breaking the system for everyone else.

Changes which cause defects or don't get finished on time can be backed out, re-prioritized, or shelved if necessary.

For inexperienced developers, regular consultation with a mentor and/or pair programming is a good idea, but I wouldn't consider this a "code review".

Title: Review before or after code commit, which is better?

Body:
Traditionally we performed code review before commit, I had an argument with my colleague today, who preferred code review after commit.

First, here's some background,

We have some experienced developers and we also have new hires with almost zero programming experience.

We'd like to perform fast and short iterations to release our product.

All team members are located at the same site.

The advantages of code review before commit I've learned:

Mentor new hires

Try to prevent errors, failures, bad designs early in the development cycle

Learn from others

Knowledge backup if someone quits

But I've also had some bad experiences:

Low efficiency, some changes may be reviewed over days

Hard to balance speed and quality, especially for newbies

One team member felt distrust

As to post-commit review, I know little about this, but the thing I'm most worried about is the risk of losing control due to lack of review.
Any opinions?

UPDATE:

We're using Perforce for VCS

We code and commit in the same branches (trunk or bug fixing branches)

To improve efficiency, we've tried to split code into small changes. We've also tried some live dialog review, but not everyone followed the rule. This is another problem though.


答:
we actually do a hybrid on LedgerSMB.  Committers commit changes that get reviewed after.  Non-committers submit changes to committers to be reviewed before.  This tends to mean two tiers of review.  First you get a mentor to review and mentor you. Then that mentor gets the code reviewed a second time after he or she's signed off on it and feedback circulates.  New committers usually spend a lot of time reviewing other people's commits at first.

It works pretty well.  The thing though is a review after is usually more cursory than a review before, so you want to make sure that review after is reserved for those who have proven themselves.  But if you have a two tier review for the new folks it does mean that problems are more likely to be caught and discussions had.


问:
Breaking 1NF to model subset constraints. Does this sound sane?
My first question here.  Appologize if it is in the wrong forum but this seems pretty conceptual.  I am looking at doing something that goes against conventional wisdom and want to get some feedback as to whether this is totally insane or will result in problems, so critique away!  I am on PostgreSQL 9.1 but may be moving to 9.2 for this part of this project.

To re-iterate:  Does it seem sane to break 1NF in this way?  I am not looking for debugging code so much as where people see problems that this might lead.

The Problem

In double entry accounting, financial transactions are journal entries with an arbitrary number of lines.  Each line has either a left value (debit) or a right value (credit) which can be modelled as a single value with negatives as debits and positives as credits or vice versa.  The sum of all debits and credits must equal zero (so if we go with a single amount field, sum(amount) must equal zero for each financial journal entry).  SQL-based databases, pretty much required for this sort of work, have no way to express this sort of constraint natively and so any approach to enforcing it in the database seems rather complex.

The Write Model

The journal entries are append only.  There is a possibility we will add a delete model but it will be subject to a different set of restrictions and so is not applicable here.  If and when we allow deletes, we will probably do them using a simple ON DELETE CASCADE designation on the foreign key, and require that deletes go through a dedicated stored procedure which can enforce the other constraints.  So inserts and selects have to be accommodated but updates and deletes do not for this task.

My Proposed Solution

My proposed solution is to break first normal form and model constraints on arrays of tuples, with a trigger that breaks the rows out into another table.

```<code>CREATE TABLE journal_line (
    entry_id bigserial primary key,
    account_id int not null references account(id),
    journal_entry_id bigint not null, -- adding references later
    amount numeric not null
);
</code>```

I would then add "table methods" to extract debits and credits for reporting purposes:

```<code>CREATE OR REPLACE FUNCTION debits(journal_line) RETURNS numeric
LANGUAGE sql IMMUTABLE AS $$
SELECT CASE WHEN $1.amount < 0 THEN $1.amount * -1 ELSE NULL END; $$;

CREATE OR REPLACE FUNCTION credits(journal_line) RETURNS numeric
LANGUAGE sql IMMUTABLE AS $$
SELECT CASE WHEN $1.amount > 0 THEN $1.amount ELSE NULL END; $$;
</code>```

Then the journal entry table (simplified for this example):

```<code>CREATE TABLE journal_entry (
    entry_id bigserial primary key, -- no natural keys :-(
    journal_id int not null references journal(id),
    date_posted date not null,
    reference text not null,
    description text not null,
    journal_lines journal_line[] not null
);
</code>```

Then a table method and and check constraints:

```<code>CREATE OR REPLACE FUNCTION running_total(journal_entry) returns numeric
language sql immutable as $$
SELECT sum(amount) FROM unnest($1.journal_lines); $$;

ALTER TABLE journal_entry
ADD CONSTRAINT CHECK (((journal_entry.running_total) = 0));

ALTER TABLE journal_line
ADD FOREIGN KEY journal_entry_id REFERENCES journal_entry(entry_id);
</code>```

And finally we'd have a breakout trigger:

```<code>CREATE OR REPLACE FUNCTION je_breakout() RETURNS TRIGGER
LANGUAGE PLPGSQL AS $$
 BEGIN
   IF TG_OP = 'INSERT' THEN
      INSERT INTO journal_line (journal_entry_id, account_id, amount)
      SELECT NEW.id, account_id, amount
        FROM unnest(NEW.journal_lines);
      RETURN NEW;
   ELSE
      RAISE EXCEPTION 'Operation Not Allowed';
   END IF;
 END;
$$;
</code>```

And finally

```<code>CREATE TRIGGER AFTER INSERT OR UPDATE OR DELETE ON journal_entry
FOR EACH ROW EXECUTE_PROCEDURE je_breaout();
</code>```

Of course the example above is simplified.  There will be a status table that will track approval status allowing for separation of duties, etc.  However the goal here is to prevent unbalanced transactions.

Any feedback? Does this sound entirely insane?

Standard Solutions?

In getting to this point I have to say I have looked at four different current ERP solutions to this problems:

Represent every line item as a debit and a credit against different accounts.

Use of foreign keys against the line item table to enforce an eventual running total of 0

Use of constraint triggers in PostgreSQL

Forcing all validation here solely through the app logic.

My concerns are that #1 is pretty limiting and very hard to audit internally.  It's not programmer transparent and so it strikes me as being difficult to work with in the future.  The second strikes me as being very complex and required a series of contraints and foreign keys against self to make work, and therefore it strikes me as complex, hard to sort out at least in my mind, and thus hard to work with.

The fourth could be done as we force all access through stored procedures anyway and this is the most common solution (have the app total things up and throw an error otherwise).  However, I think proof that a constraint is followed is superior to test cases, and so the question becomes whether this in fact generates insert anomilies rather than solving them.

If this is a solved problem it isn't the case that everyone agrees on the solution....

答:
"SQL-based databases" are fully capable of handling this problem without breaking normalization. Oracle has BEFORE triggers, SQL Server has INSTEAD OF triggers, and postgres has constraint triggers. All of these can query the entry table (indexed by transaction) and raise an error if the sum of entries for a specific transaction is nonzero, which satisfies the DE rule as you've defined it (more on this later).

Of course, it's highly unlikely that this is actually appropriate behaviour. Double-entry bookkeeping is a constraint on the domain, whereas constraint and/or trigger systems in the DBMS are meant for constraints on the data.

Referential integrity is an actual data constraint - the data cannot be in a valid state if a row references a primary key that does not exist. Other legitimate constraints might refine a primitive data type, for example restricting a character column to 'Y' or 'N'. But the balancing rule here is just a business rule. If violated, the data itself is still valid, it would just represent a bug or misconfiguration in the system that might be resolvable without data loss. Or worse, it might just represent a temporary state while some deferred business rules are being applied.

Most likely, you'll just end up with an obnoxious, unmaintainable, poorly-performing system that is a pain to develop against.

Of course, your proposal also ignores many of the actual DE rules and thus isn't very useful in practice even if works on a technical level, for example:

In the British system, matching entries for one type have to be made against another ledger of the same type, and for a different account. For example, you don't debit a nominal account after crediting a personal account, and it would make no sense to credit and debit the same account for the same amount.

In the American system, entries follow the accounting equation. Matching entries don't have to have opposite signs unless the entirety of the transaction is in the same category. A cash purchase will have positive and negative assets entries, but taking out a loan will add to both assets and liabilities.

Generally speaking, the "running total" is not going to be zero. What actually matters at the end of the day is that the different types of ledgers are all balanced according to some particular set of business rules.

I am not an accountant, and obviously you've spent more time working on accounting systems than I have, so maybe I'm missing something above; but as far as I can tell, this is wrong both from a technical and business perspective, so don't do it. Accounting systems are a solved problem; please don't reinvent the square wheel.


问:
What are the drawbacks of Python?
Python seems all the rage these days, and not undeservingly - for it is truly a language with which one almost enjoys being given a new problem to solve. But, as a wise man once said (calling him a wise man only because I've no idea as to who actually said it; not sure whether he was that wise at all), to really know a language one does not only know its syntax, design, etc., advantages but also its drawbacks. No language is perfect, some are just better than others.

So, what would be in your opinion, objective drawbacks of Python.

Note: I'm not asking for a language comparison here (i.e. C# is better than Python because ... yadda yadda yadda) - more of an objective (to some level) opinion which language features are badly designed, whether, what are maybe some you're missing in it and so on. If must use another language as a comparison, but only to illustrate a point which would be hard to elaborate on otherwise (i.e. for ease of understanding)

答:
Multiple dispatch does not integrate well with the established single-dispatch type system and is not very performant.

Dynamic loading is a massive problem on parallel file systems where POSIX-like semantics lead to catastrophic slow-downs for metadata-intensive operations. I have colleagues that have burned a quarter million core-hours just getting Python (with numpy, mpi4py, petsc4py, and other extension modules) loaded on 65k cores. (The simulation delivered a significant new science results, so it was worth it, but it is a problem when more than a barrel of oil is burned to load Python once.) Inability to link statically has forced us to go to great contortions to get reasonable load times at scale, including patching libc-rtld to make dlopen perform collective file system access.

Title: What are the drawbacks of Python?


答:
"Immutability" is not exactly it's strong point. AFAIK numbers, tuples and strings are immutable, everything else (i.e. objects) is mutable. Compare that to functional languages like Erlang or Haskell where everything is immutable (by default, at least).

However, Immutability really really shines with concurrency*, which is also not Python's strong point, so at least it's consequent.

(*= For the nitpickers: I mean concurrency which is at least partially parallel. I guess Python is ok with "single-threaded" concurrency, in which immutability is not as important. (Yes, FP-lovers, I know that immutability is great even without concurrency.))

Title: What are the drawbacks of Python?

Body:
Python seems all the rage these days, and not undeservingly - for it is truly a language with which one almost enjoys being given a new problem to solve. But, as a wise man once said (calling him a wise man only because I've no idea as to who actually said it; not sure whether he was that wise at all), to really know a language one does not only know its syntax, design, etc., advantages but also its drawbacks. No language is perfect, some are just better than others.

So, what would be in your opinion, objective drawbacks of Python.

Note: I'm not asking for a language comparison here (i.e. C# is better than Python because ... yadda yadda yadda) - more of an objective (to some level) opinion which language features are badly designed, whether, what are maybe some you're missing in it and so on. If must use another language as a comparison, but only to illustrate a point which would be hard to elaborate on otherwise (i.e. for ease of understanding)


答:
I find python's combination of object-oriented this.method() and procedural/functional method(this) syntax very unsettling:

```<code>x = [0, 1, 2, 3, 4]
x.count(1)
len(x)
any(x)
x.reverse()
reversed(x)
x.sort()
sorted(x)
</code>```

This is particularly bad because a large number of the functions (rather than methods) are just dumped into the global namespace: methods relating to lists, strings, numbers, constructors, metaprogramming, all mixed up in one big alphabetically-sorted list.

At the very least, functional languages like F# have all the functions properly namespaced in modules:

```<code>List.map(x)
List.reversed(x)
List.any(x)
</code>```

So they aren't all together. Furthermore, this is a standard followed throughout the library, so at least it's consistent.

I understand the reasons for doing the function vs method thing, but i still think it's a bad idea to mix them up like this. I would be much happier if the method-syntax was followed, at least for the common operations:

```<code>x.count(1)
x.len()
x.any()
x.reverse()
x.reversed()
x.sort()
x.sorted()
</code>```

Whether the methods are mutating or not, having them as methods on the object has several advantages:

Single place to look up the "common" operations on a data-type: other libraries/etc. may have other fancy things they can do to the datatypes but the "default" operations are all in the object's methods.

No need to keep repeating the Module when calling Module.method(x). Taking the functional List example above, why do i have to keep saying List over and over? It should know that it's a List and I don't want to call the Navigation.map() function on it! Using the x.map() syntax keeps it DRY and still unambiguous.

And of course it has advantages over the put-everything-in-global-namespace way of doing it. It's not that the current way is incapable of getting things done. It's even pretty terse (len(lst)), since nothing is namespaced! I understand the advantages in using functions (default behavior, etc.) over methods, but I still don't like it.

It's just messy. And in big projects, messiness is your worst enemy.

Title: What are the drawbacks of Python?

Body:
I find python's combination of object-oriented this.method() and procedural/functional method(this) syntax very unsettling:

x = [0, 1, 2, 3, 4]
x.count(1)
len(x)
any(x)
x.reverse()
reversed(x)
x.sort()
sorted(x)

This is particularly bad because a large number of the functions (rather than methods) are just dumped into the global namespace: methods relating to lists, strings, numbers, constructors, metaprogramming, all mixed up in one big alphabetically-sorted list.

At the very least, functional languages like F# have all the functions properly namespaced in modules:

List.map(x)
List.reversed(x)
List.any(x)

So they aren't all together. Furthermore, this is a standard followed throughout the library, so at least it's consistent.

I understand the reasons for doing the function vs method thing, but i still think it's a bad idea to mix them up like this. I would be much happier if the method-syntax was followed, at least for the common operations:

x.count(1)
x.len()
x.any()
x.reverse()
x.reversed()
x.sort()
x.sorted()

Whether the methods are mutating or not, having them as methods on the object has several advantages:

Single place to look up the "common" operations on a data-type: other libraries/etc. may have other fancy things they can do to the datatypes but the "default" operations are all in the object's methods.

No need to keep repeating the Module when calling Module.method(x). Taking the functional List example above, why do i have to keep saying List over and over? It should know that it's a List and I don't want to call the Navigation.map() function on it! Using the x.map() syntax keeps it DRY and still unambiguous.

And of course it has advantages over the put-everything-in-global-namespace way of doing it. It's not that the current way is incapable of getting things done. It's even pretty terse (len(lst)), since nothing is namespaced! I understand the advantages in using functions (default behavior, etc.) over methods, but I still don't like it.

It's just messy. And in big projects, messiness is your worst enemy.


答:
Lack of homoiconicity.

Python had to wait for 3.x to add a "with" keyword.  In any homoiconic language it could have trivially been added in a library.

Most other issues I've seen in the answers are of one of 3 types:

1) Things that can be fixed with tooling (e.g. pyflakes)
2) Implementation details (GIL, performance)
3) Things that can be fixed with coding standards (i.e. features people wish weren't there)

#2 isn't a problem with the language, IMO #1 and #3 aren't serious problems.

Title: What are the drawbacks of Python?


答:
quite a bunch of very mainstream 3rd party libraries and software that are widely used, are quite not pythonic. A few examples : soaplib, openerp, reportlab. Critique is out-of-scope, it's there, it's widely used, but it makes the python culture confusing ( it hurts the motto that says " There should be one-- and preferably only one --obvious way to do it "). Known pythonic successes ( such as django or trac ) seem to be the exception.

the potentially unlimited depth of abstraction of instance, class, metaclass is conceptually beautiful and unique. But to master it you have to deeply know the interpreter ( in which order python code is interpreted, etc. ). It's not widely known and used ( or used correctly ), while similar black magic such as C# generics, that is conceptually more convoluted ( IMHO ) seems more widely known and used, proportionally.

to get a good grasp of memory and threading model, you have to be quite experienced with python, because there's no comprehensive spec. You just know what works, maybe because you read the interpreter's sources or experienced quirks and discovered how to fix them. For instance, there are only strong or weak references, not the soft and phantom refs of java. Java has a thread for garbage collection while there is no formal answer about when garbage collection happens in python ; you can just observe that garbage collection doesn't happen if no python code is executed, and conclude it's probably happening sometimes when trying to allocate memory. Can be tricky when you don't know why a locked resource wasn't released ( my experience about that was mod_python in freeswitch ).

Anyhow, python is my main language for 4 years now. Being fanboys, elitists or monomaniacs is not a part of the python culture.

Title: What are the drawbacks of Python?


答:
I'd love to have explicitly parallel constructs. More often than not, when I write a list comprehension like

```<code>[ f(x) for x in lots_of_sx ]
</code>```

I don't care the order in which the elements will be processed. Sometimes, I don't even care in which order they are returned.

Even if CPython can't do it well when my f is pure Python, behavior like this could be defined for other implementations to use.

Title: What are the drawbacks of Python?

Body:
I'd love to have explicitly parallel constructs. More often than not, when I write a list comprehension like

[ f(x) for x in lots_of_sx ]

I don't care the order in which the elements will be processed. Sometimes, I don't even care in which order they are returned.

Even if CPython can't do it well when my f is pure Python, behavior like this could be defined for other implementations to use.


答:
First, a caveat: there is no definitive answer to this question.

Rails is more than just a framework. It's a Domain Specific Language separate from Ruby, with its own keywords, culture, and idioms. A primary function of the Rails DSL is to hide things from you. Rails handles the abstraction between a model and the database, for example, so that you don't have to write a data access model. So in this sense, Rails is simpler than Ruby–if you had to build a web application without Rails, you would have a huge amount of work to do.

On the other hand, every syntactically correct Ruby statement is a syntactically correct Rails statement. So the application logic that you write in Rails is Ruby, which is one reason people might say that you are going to regret not knowing Ruby. Rails implements a lot of Ruby's metaprogramming features, so knowing what is actually going on in your Rails app requires some fairly advanced Ruby knowledge.

Another point is that the Rails framework implements the Model/View/Controller design pattern. Models are objects. Controllers are also objects. You simply can't implement Rails without writing objects and calling methods on those objects. Most of what you do in a Rails app is write methods. If you don't know what an object is, or what a method is, you might struggle with this. It might be good to understand objects before you try to understand a particular pattern of objects. On the other hand, it might be good to get a strict introduction to how to use a very specific pattern of objects before you try the general case.

On yet another hand, in my own experience as a guy who doesn't know Rails, not knowing Rails is not much of a barrier to writing applications using Rails. It's probably a barrier to writing good, well-designed applications in Rails, but if you know Ruby well, you can hack something together using any Ruby framework.

All of that said, the advice I would trust most on this is the advice at the Rails Tutorial Book website. The best piece of that advice is this:

a surprising number of beginners have used this tutorial to learn web development, so I suggest giving it a try

If you get lost, go back and learn some Ruby, or some HTML, or whatever you're lost on, and try again! Learning Rails first isn't going to stop you from learning Ruby later, and if you find that you need more Ruby, you can always put Rails down and pick it back up. There's no wrong way to do this–do whatever keeps your enthusiasm for learning up, and whatever keeps you moving forward. Expect this to be pretty hard, though, whatever route you take. If it was easy, they wouldn't pay us to do it.

Title: How much Ruby should I learn before moving to Rails?

Body:
Just a quick question..

I can never get a definitive answer when googling this, either. Some people say you can learn Rails without knowing any Ruby, but at some point you'll run into a brick wall and wish you knew Ruby and will have to go back to learn it..and some say to learn the "basics" of Ruby before learning Rails and it will make your life that much easier..

My current knowledge is low. I'm not a beginner, but I'm not pro, either. I went through the Learn Python The Hard Way online book in about a month, but I stopped once I got to the OOP side of Python (I know booleans, elif/if/else/statements, for loops, while loops, functions)

I agree with learning the "basics" of Ruby before learning Rails, but what exactly are the "basics" of Ruby? Would I need to learn the whole OOP side of Ruby before I went on to Rails? Or would I just need to learn the Ruby syntax up to where I learned Python (booleans, elif/if/else/statements, for loops, while loops, functions) before I went on to Rails?
Thanks!


问:
General programming techniques to speed up coding time
I am preparing for a programming contest where we have to code in C++ and it is all about producing working code in a short time. An example would be to use a macro to get the minimum of two ints or using memsets to initialize arrays (but I was told that you shouldn't use either here).

This leads to the question, what kind of coding techniques exist to use at a real job?

答:
In addition to knowing the language, know your tools, especially your editor. I've been coding for over 15 years professionally, and I've seen otherwise great programmers slowed down because the only editor commands they use are cursor keys and crtl-x/c/v..

Does your editor support a single keystroke to delete a line? To re-indent a line? Move between functions/methods? block select/paste? bookmarks? Move by word? Can the editor auto generate classes/methods/functions? Does it suport templates that you can create ahead of time? Quick refactoring? Macro recording?

Knowing your editor can greatly speed up development time.


问:
Why might an ASP.Net website load slowly?
Anecdotally, I've visited many .aspx website that require a significant amount of load time for each page.

Is my experience unique?

If not, why might an ASP.Net website load slowly?

Edit: It's now about 7 years later (12/29/2017). The good news is I don't see this problem much anymore, maybe because Google started penalizing sites that load too slowly. I now use ASP.NET MVC with good results, currently running on Vultr private virtual servers (Azure was way too slow when we tried it.) Some of the worst offenders I see now are the CMS systems like Wordpress and Drupal, probably running on hardware that's too slow or underspecced for the amount of traffic the site gets. -HK1

答:
The viewstate can really slow down the postbacks.  If you have sever large drop down lists on a page you should not use the view state on them.

The viewstate lets you pretend you're working on a stateful winforms app. That can get you into trouble sometimes.


问:
How does eMail encryption work?
I have been going over YouTube watching videos on eMail encryption and everyone seems to explain it from a different perspective. Some do it for a CompTIA exam while others just provide a primer.
Here is what I understood:

Step1: You compose an email that you want to send. Without encryption, it will be simple ASCII text that will be visible to anyone along the way.

Step2: You generate a digital signature to make sure  that nobody gets to re-transmit your email and claim it was you. Digital Signature is generated using Sender's private key which is usually a hash of the password and is then combined with the original message to form one long hash string. These signatures are one-time-use-only and a new one is calculated for every email.

Step 3: You encrypt the compose of your email using Receiver's public key so that the only person who can read it is the intended receiver using their private key

Step 4: When you hit the send the email, what is transmitted now is gibberish to everyone apart from the intended receiver who will decrypt is using their private key

And there are various ways to do it like PEM, PGP, etc.

Correct me where I am wrong or refine where necessary.

答:
Encryption and signing are two separate things. You can send a signed email that is not encrypted, and you can send an encrypted email that isn't signed.

For the most part, you are correct. But the entire email is not 'gibberish', only the contents. The header remains unaffected, with the exception that the content-type may change.

Title: How does eMail encryption work?


问:
Introducing a (new) test method to a team
A couple of months ago I was hired in a new job. (I'm fresh out of my Masters in software engineering)

The company mainly consists of ERP consultants, but I was hired in their fairly small web department (6 developers), our main task is ERP/ecom integration (ERP-integrated web shops).

The department is growing, and recently my manager asked me to start thinking about introducing tests to the team, I love a challenge, but frankly I'm a bit scared (I'm the least experienced member of the team).

Currently the method of testing is clicking around in the web shop and asking the customer if the products are there, if they look okay, and if orders are posted correctly to the ERP.

We are getting a lot of support cases on previous projects, where a customer or a customer's customer have run into errors, which - I suppose - is why my manager wants more structured testing.

Off the top of my head, I though of some (obvious?) improvements, like looking at the requirement specification, having an issue tracker, enabling team members to register their time on a "tests"-line on the budget, and to circulate tasks amongst members of the team.

But as I see it we have three main challenges:

general website testing. (javascript, C#, ASP.NET and CMS integration tests)

(live) ERP integration testing (customers rarely want to pay for test environments).

adopting a method in the team

I like the responsibility, but I am afraid that I'm in a little bit over my head.

I expect that my manager expects me to set up some kind of workshop for the team where I present some techniques and ideas and where we(the team) can find some solutions together.

What I learned in school was mostly unit testing and program verification, not so much testing across multiple systems and applications.

What I'm looking for here, is references/advice/pointers/anecdotes; anything that might help me to get smarter and to improve the current method of my team.

(TL;DR: read the bold parts)

答:
I think the first question here is what you expect to get out of testing. I use tests as a design tool–code that is easy to test is usually good code–and as a safety net. It sounds like what you want is a safety net.

If you want a safety net, you must have a test environment. You don't want to run tests in your production environment. For one thing, that means that you are deploying code that you think might be broken into production. For another, you can't control the data or control access as well. For yet another, that means you are deploying code that you think might broken into production. This is madness, pure and simple, and there are better ways.

The next question is what to test. The team has to have a testing strategy and when something is implemented, there has to be an understanding of what tests need to be written. One reason I'm a fan of Test Driven Development is that tests are written concurrently with code, so the tests aren't seen as a sort of overhead that everyone has to put up with, and you have some assurance that what needs to be tested is tested because everything is tested. You might consider whether it's plausible to implement TDD in your shop... is it possible that your fellow developers would consider this if writing and running tests was easy?

Anecdotally, I've been able to convince a team to go with TDD and CI simply by pointing out a couple of things: First, we all do TDD all the time anyway. Before you write code, you have intent, and after you write code, you generally check to see if it matches that intent. TDD is the process of putting your intent into a test so that you know that the code you write tomorrow doesn't violate the intent you had yesterday. Second: it's possible to avoid having your manager/customer bitch at you for breaking something by simply having a test environment. It removes a lot of hassle from your life when these people aren't complaining all the time.

If you have time/space to do so, you could consider setting up a proper CI environment that you can demonstrate to the group. Knowing that they can do it is not as cool as knowing that you can do it for them.

As far as implementation details, it sounds like you might benefit from reading "Continuous Integration in .NET" from Manning Publications and maybe this blog post from codebetter on selenium testing with .net. For TDD, check out "Test Driven Development in Microsoft .net" from Microsoft.


问:
Can I assume interface oriented programming as a good object oriented programming?
I have been programming for decades but I have not been used to object oriented programming. But for recenet years, I had a great opportunity to learn OOP, its principles, and a lot of patterns that are great.

Since I've learned OOP, I tried to apply them to a couple of projects and found those projects successful. Unfortunately I didn't follow extreme programming that suggests writing test first, mainly because their time frame were tight. What I did for those projects were

Identify all necessary classes and create them with proper properties and methods

whenever there is dependency between classes, write interface between them

see if there is any patterns for certain relationships between classes to replace

By successful, I meant that it was quick development effort, the classes can be reused better, and flexible enough so that another programmer does not have to change something else to fix another part.

But I wonder if this is a good practice. Of course, I know I need to put writing unit tests first in my work process. But other than that, is there any problem with this approach - creating lots of interfaces - in long term?

答:
Yes .. Using interfaces in Object Oriented Programming would be good practice. Benefits of using interfaces in your model :

Interfaces provides asynchronous development without defining Class implementations.

Multiple class implementations of a particular behavior/operation.

Interfaces provides a defined set of standards that must be followed by implementation classes.

If you are writing a API a utility package you must expose the operations using interfaces so that a user of that API can easily integrate.

These features pointed above are automatically included with your model in case of using interfaces but in case of direct class implementations you need to take care of these manually.

However there are some disadvantages also :

New development members needs to follow the standards defined by interfaces if they are developing new implementations. It is bit complicated and takes time to develop code by new members.

In case of changing the interface standards we need to change into all the class implementations as well.


答:
You've got a number of options, but here's where I'd start.  Mind you, I come from the java world, but a website should be a website, really.

Website testing:  Selenium is a fantastic tool for scripting tests against websites.

Virtualize:  You can duplicate your environments in VMware or VirtualBox, and save them.  When you want to do your system/integration tests, load the appropriate environment and run the tests.

Methodology: Agile Testing: A Practical Guide for Testers and Agile Teams  has a lot of good advice on this front.  I'd suggest starting with something pretty simple, see how it goes, and revise appropriately.

Title: Introducing a (new) test method to a team

Body:
A couple of months ago I was hired in a new job. (I'm fresh out of my Masters in software engineering)

The company mainly consists of ERP consultants, but I was hired in their fairly small web department (6 developers), our main task is ERP/ecom integration (ERP-integrated web shops).

The department is growing, and recently my manager asked me to start thinking about introducing tests to the team, I love a challenge, but frankly I'm a bit scared (I'm the least experienced member of the team).

Currently the method of testing is clicking around in the web shop and asking the customer if the products are there, if they look okay, and if orders are posted correctly to the ERP.

We are getting a lot of support cases on previous projects, where a customer or a customer's customer have run into errors, which - I suppose - is why my manager wants more structured testing.

Off the top of my head, I though of some (obvious?) improvements, like looking at the requirement specification, having an issue tracker, enabling team members to register their time on a "tests"-line on the budget, and to circulate tasks amongst members of the team.

But as I see it we have three main challenges:

general website testing. (javascript, C#, ASP.NET and CMS integration tests)

(live) ERP integration testing (customers rarely want to pay for test environments).

adopting a method in the team

I like the responsibility, but I am afraid that I'm in a little bit over my head.

I expect that my manager expects me to set up some kind of workshop for the team where I present some techniques and ideas and where we(the team) can find some solutions together.

What I learned in school was mostly unit testing and program verification, not so much testing across multiple systems and applications.

What I'm looking for here, is references/advice/pointers/anecdotes; anything that might help me to get smarter and to improve the current method of my team.

(TL;DR: read the bold parts)


问:
How to take a step back and look at code with fresh eyes?
I've spent the last year as a one-man team developing a rich-client application (35,000+ LoC, for what it's worth). It's currently stable and in production. However, I know that my skills were rusty at the beginning of the project, so without a doubt there are major issues in the code. At this point, most of the issues are in architecture, structure, and interactions -- the easy problems, even architecture/design problems, have already been weeded out.

Unfortunately, I've spent so much time with this project that I'm having a hard time thinking outside of it -- approaching it from a new perspective to see the flaws deeply buried or inherent in the design.

How do I step outside my head and outside my code so I can get a fresh look and make it better?

答:
Practice design patterns and Best practices

Choose a framework, tools, packages etc based on your app requirements and needs - for this you need to read lot of etch blogs and find solutions for each individual tech problem

Create design/architecture draft and discuss with someone who is good at technical/architectural stuff. Improve this draft using feedback and comments. keep doing this till you achieve stable state.

Implement code such that everything that app need is configurable and maintainable

re-architecture and reimplementing your project will definitely result app having better consistency, performance etc.


答:
In Ruby, I would consider OOP as a part of basics, because in Ruby, everything is an object. Definitely learn OOP (how to create a class, how inheritance works, class vs. instance methods, initializing objects...) before learning Rails. And modules - knowing how to create namespaces.

If you know Python, you should be able to pick up Ruby syntax in no time, it's very, very similar.


问:
Maintaining C/C++/Java skills as a web developer
When I was in college I learned how to program in C, C++, and Java. Currently, I'm a web developer using front end and back end technologies (HTML/CSS/JS, PHP, MYSQL). While the sorting algorithms and OOP concepts that I learned in college can be applied to web development, I'm looking for ways to keep up my knowledge of all languages. I enjoy programming in C-Style (C/C++/Java) languages and front-end/back-end technologies. Unfortunately, there aren't many options to use C-style languages to build websites. However, I would like to keep up my knowledge and skills in the languages I learned in college as I know they will continue to help me with my growth.

What resources are available to keep challenging myself in C-style languages that are relevant to web development? Would contract work for C-style languages be beneficial? Are there sites that offer algorithm challenges? Any help is appreciated. I'm also interested in how others that have asked themselves this have solved this problem.

答:
Subscribe to sites like Codechef.com, topcoder.com, etc. They will mail you twice-thrice a month about the latest algorithmic contests, take part in them using your the language of your choice

The best part is even if you are busy in web-dev their pinging will remind you writing code in C/C++ and the challenging puzzles will keep you thinking for a few days at least


答:
For the sake of brevity, I'll address C++, but most of what I say applies to Java as well (if not more so).

It's worth noting that C and C++ can be used for web development, and there are even several C++ web frameworks. The thing is that most shared hosts don't support that kind of stuff, but you can easily deploy it on Virtual Private Servers.

Now, what I've been doing is simply reading books about topics that interest me. For example, there's a ton of C++ books. Namely:

Inside the C++ Object Model

The Design and Evolution of C++

Effective C++

Effective STL

and many more.

You'll find, as I did, that these in-depth books will give you a theoretical knowledge of C++ that you might never forget. The Scott Meyers "Effective" books will also teach you about using the language idiomatically and "effectively".

Another thing you can do is make c++ a favorite tag over at Stack Overflow and check out questions every once in a while, and try to answer them, or at least check out popular answers.

And last but not least, even as a web developer, you might sometimes get ideas about non-web applications you might want to develop; in that case, pick C++ as your language of choice. If you're lucky, you'll encounter some non-trivial challenges which (meeting them) will leave an important mark on your experience and knowledge.

On top of all that, you can always go over to GitHub and see if you can help some open-source projects, or at least try to understand some interesting code bases, such as Node.js.

Good luck.

Title: Maintaining C/C++/Java skills as a web developer

Body:
When I was in college I learned how to program in C, C++, and Java. Currently, I'm a web developer using front end and back end technologies (HTML/CSS/JS, PHP, MYSQL). While the sorting algorithms and OOP concepts that I learned in college can be applied to web development, I'm looking for ways to keep up my knowledge of all languages. I enjoy programming in C-Style (C/C++/Java) languages and front-end/back-end technologies. Unfortunately, there aren't many options to use C-style languages to build websites. However, I would like to keep up my knowledge and skills in the languages I learned in college as I know they will continue to help me with my growth.

What resources are available to keep challenging myself in C-style languages that are relevant to web development? Would contract work for C-style languages be beneficial? Are there sites that offer algorithm challenges? Any help is appreciated. I'm also interested in how others that have asked themselves this have solved this problem.


答:
Evolving the Team's Culture

This might be the most difficult part of implementing testing processes in your organization.  Every team reacts to change differently.  Some people embrace the opportunity to try something new, and some are perfectly happy in their ways and see no reason to change.  I can tell you this: nobody likes a fascist.  Forcing people to do things a certain way will likely generate more resistance.

Here are some tips for presenting change in your organization:

Provide empirical evidence, such as "We caught bug X before delivering to the customer, and it took us 8 hours to patch it.  The customer caught bug Y one month after it was delivered, and it took us a week to patch it." Edit: I see that you mentioned that your client may be concerned with the costs of a test site.  See if you can prove that catching bugs early will save the client money.

Show the developers how new tools work.  A lot of us are developers because we think that technology is fun.  Try to share new testing tools/processes like new toys with which to play.

Don't set your heart on any single solution.  Let the team experiment with various technologies.  For automated UI testing, you can use TFS, Selenium, manually going through test scripts, or other options.  Keeping the door open to different technologies allows the team to find which tools are good fits, and it also encourages a democratic process that promotes a shared ownership of decision making.  Encourage open discussions with the development team.

DO NOT expect everything to change at once.  Try to focus on one thing at a time.  Here is an example of breaking change into smaller stages:

Write some unit tests for the server code that verify that system-critical functionality works as intended

Create a test VM that duplicates the operational environment of your product

Document use cases that can be used to test the GUI

Combine the server code and the client code into a single repository on TFS so that the most recent release is easily identifiable, testable, and able to be deployed

Start executing use case testing whenever new components are committed (automated or manually)

These are just some example tasks.  It may take weeks to get where you want to be; it may take months.  How exactly your team adopts testing processes is going to depend on your culture.  Last but not least,

DO NOT give up, but be polite and amiable about it.  If you keep suggesting ways to enhance testing processes, the development team might try some of your suggestions on a slow day just out of curiosity.

Technical Solution

I wish I could give you some better information on technical solutions for your situation.  I work part-time in a .NET shop, and I can tell you that we use TFS exclusively for continuous integration, i.e. version control for client code (EXTJS w/ ASP.NET MVC 3) and server code (C# w/ Entity Framework), automated UI and unit tests on the release branch, and automated deployment to a test site and a demo site (which will be our production site eventually).  As I mentioned above, your specific technical solution(s) will depend largely on your organization's culture.

Good luck!


答:
Maybe there are - most back-end servers have the option to be extended using C/C++ code, generally for performance reasons, but that doesn't mean you can't start writing some of your web-serving code using C++ extensions to the main glue language.

Of course, you could also use C++ to write webservice services and use them from your web site code. Using Windows Web Services, gsoap, mongoose, cppcms or any of the other C++ web framework or libraries would be good for you.

Especially check out the WWS link as it describes Microsoft's position. If WWS is twice as fast and uses 1/8th the memory then you can fit far more services on a server - that is a definite benefit to the cost of running the business.


答:
With email encryption there are two possible options (over-simplified):

End to End encryption

Point to Point encryption (eg TLS)

When to use each really depends on the purpose of encrypting the email. Do you want to prevent someone eavesdropping while your mail is being sent or to you want to ensure that only the intended recipient can read the email?

Point to Point

If you want to prevent someone on your network from eavesdropping than you would want to consider encrypting the transport. What this means is that the contents and the headers of the email still remain in plain-text, but the transmission between your mail software and your mail server are encrypted.

The mail server will likely store the plain-text email ready to be forwarded to the next mail sever in line for delivery. How this is done depends on the configuration of the mail server and the protocols available between it and the next mail server. It may be sent in plain text, over an un-encrypted channel.

The key to know here is that the email will be plain-text between you can all the intermediate mail servers that may handle the email.

End to End

If you want to prevent anyone other than the intended recipient than you want end-to-end encryption as you've described in your question.

This form of encryption is where you and the recipient agree on way that you will be securely communicating and use this method to perform the encryption and decryption. In your question you've described a PKI (public key infrastructure, asymmetrical encryption) way, but there is nothing preventing you from also using a pre-shared key and using symmetrical encryption.

There are a few plugins, such as PGP & GPG, that allow you to encrypt, sign, verify & decrypt email that has been sent using PKI methods.

Your scenario

You are essentially correct in your scenario.

Compose an email in your favourite email client.

Sign the email using your private key, this will add a digital signature block to the email.

Retrieve the recipient's public key using a number of methods:

Key server

Copy on local disk

Downloaded from a website

etc

Encrypt the contents of the email with the recipient's public key

When you hit send, the contents that was encrypted is now unknown to all that the email passes through. The sender, headers, recipient and other fields will still be available to someone eavesdropping over the wire, unless point-to-point encryption is employed as well. The mail server will always have a "plain-text" copy of this information as it needs it to be able to deliver the email.

Title: How does eMail encryption work?

Body:
I have been going over YouTube watching videos on eMail encryption and everyone seems to explain it from a different perspective. Some do it for a CompTIA exam while others just provide a primer.
Here is what I understood:

Step1: You compose an email that you want to send. Without encryption, it will be simple ASCII text that will be visible to anyone along the way.

Step2: You generate a digital signature to make sure  that nobody gets to re-transmit your email and claim it was you. Digital Signature is generated using Sender's private key which is usually a hash of the password and is then combined with the original message to form one long hash string. These signatures are one-time-use-only and a new one is calculated for every email.

Step 3: You encrypt the compose of your email using Receiver's public key so that the only person who can read it is the intended receiver using their private key

Step 4: When you hit the send the email, what is transmitted now is gibberish to everyone apart from the intended receiver who will decrypt is using their private key

And there are various ways to do it like PEM, PGP, etc.

Correct me where I am wrong or refine where necessary.


问:
What is a best practice tier structure of a Java EE 6/7 application?
I was attempting to find a best practice for modeling the tiers in a Java EE application yesterday and couldn't come up with anything current.  In the past, say java 1.4, it was four tiers:

Presentation Tier

Web Tier

Business Logic Tier

DAL (Data Access Layer ) which I always considered a tier and not a layer.

After working with Web Services and SOA I thought to add in a services tier, but that may fall under 3. the business logic tier.

I did searches for quite a while and reading articles.  It seems like Domain Driven Design is becoming more popular, but I couldn't find a diagram on it's tier structure.

Anyone have ideas or diagrams on what the proper tier structure is for newer Java EE applications or is it really the same, but more items are ranked under the four I've mentioned?

Aftermath:

Really, I should have reworded my question as my real intent was to ask where to put the business logic in a Java EE application?  In thinking along those terms, I somehow concluded that the tier structure had changed, when it had not.  However, with the advent of POJO programming and lightweight frameworks that I was using in my day to day work, I lost sight of all this.

The tier structure of Java EE apps still holds to the same, but now instead of heavy weight EJB2 type business logic in the middle tier I was using POJO's with services to implement business logic.

答:
After doing more research, I found another answer.

In a Spring application, the services tier can combine the business logic with the data access, eliminating the need for DAO's.  (Re: Apress Book: Pro Spring 3 page 50).  This in effect takes the traditional 4 tiers of a J2EE application that I mentioned above into a 3 tier architecture.
The picture below was how apps typically were structured in Java2EE that I worked on:

Then with the advent of the Spring Framework, services were added into the business logic middle tier and this is a typical structure for apps that I worked on later. This was what I thought had changed the structure of the Java applications, but really it was an evolving of the middle tier.  The tiers themselves were still present.


答:
I think the biggest hurdle you'll face (and constantly face for a while) is resistance. Years ago I introduced nightly builds and automated releases internally and stopped developers from checking in compiled binaries and tried to discourage them from moving code directly to client sites. I was surprised how much complaining they did about waiting for code to be tested by QC, reluctance to write any basic kind of unit test and how they continue to skirt around processes and move code manually. It can be discouraging to see how reluctant people can be to migrate towards a process that is actually better for product stability. But you have to stick with your plan. Moving code manually and not checking in changes is madness.

If management has your back you just need to proceed with one thing at a time. First get them to check in all changes to a single repository and have everything built from that repo. Seriously everything should be under version control. Everything should be compiled by a server. Once you get builds rolling then introduce automated testing.

The question is framed with testing help of which I'm still learning but it sounds like you don't even have a proper build and release process. Only one small part of our product uses any kind of automated testing and that's our Java stuff. A CI tasks runs and sends an email to the last developer to commit if a CI fails. Beyond that there is no other kind of automated testing.

So build and release is something I do have experience with. I had to write from scratch a build and release process for a shop that would check in compiled binaries and sql scripts to VSS and then push those binaries or scripts manually to clients. I used NAnt w/ NAntContrib for compiling vb6 and .Net and then Ant for our Java stuff. VSS was dumped for SVN. Initially I had CruiseControl.NET for managing CI but recently I switched to Jenkins. CC.Net wasn't handling CI very well and I switched out of frustration. I used NAnt to deploy the code to our dev and QC areas internally with nightly builds. WiX (Windows Installer XML) to install/update clients.

I came across a book which I'm going to read just to get some ideas, it's called How Google Tests Software by James Whittaker. I really want to get automated testing in to my company too and with all the other work I have to do it's an ongoing process.
Good luck to you dude!

(oh and we use JIRA for issue tracking and were previously using Serena TeamTrack. Neither really blows my mind but I think our JIRA stuff isn't implemented correctly)


问:
Understanding binary numbers in terms of real world objects
When I represent a number in the decimal system, I have an intuitive knowledge of what it amounts to. For example take the number '10': I understand that it means 10 apples or 10 people... i.e I can count in the real world.

But as soon as the number is converted to any other system, this understanding no longer applies. For example 10 when converted to binary will be 1010...now what does this represent? Is there a way to understand this number 1010 in terms of counting objects in the real world?

答:
"Io sono italiano" is the italian sentence for "I am italian". Barring issues with translation, the two sequence of letters mean to (a reader who is able to speak both) the same concept.

So a number expressed in the decimal system may, under some condition, represent a counting device (you can count with integer, but then think that zero is a strange number, negative numbers are even stranger, and rational and irrational and imaginary numbers also are interesting).

But the decimal system is just a notation, which happens to have gained some predominance (well, in the computing world the case could be made for binary, octal and hexadecimal).
It is by no means special: a given number can be written in whatever notation you decide to use.

So 1010 (in binary notation) is precisely the same as 0*2^0 + 1*2^1 + 0*2^2 + 1*2^3 = 10 in decimal notation. You can say that humans usually have 10 fingers on their two hands (decimal notation) or 1010 finger on their 10 hands (binary notation).

I will add a couple of comments:

in any base (in any notation) the number written as 10 is special

there are a lot  (to use an understatement)  of numbers which are properly expressed implicitly: think about e and pi which are surely very famous numbers whose representation we prefer to keep "in letters" rather than using a sequence of digits (which should be infinite to be precise).


问:
How should UI layer pass user input to BL layer?
I'm building an n-tier application, I have UI, BL, DAL & Entities (built from POCO) projects. (All projects have a reference to the Entities).

My question is - how should I pass user input from the UI to the BL, as a bunch of strings passed to the BL method and the BL will build the object from the parameters, or should I build the objects inside the UI submit_function and send objects as parameters?

EDIT: I wrote n-tier application, but what I actually meant was just layers.

答:
how should I pass user input from the UI to the BL, as a bunch of strings passed to the BL method and the BL will build the object from the parameters, or should I build the objects inside the UI submit_function and send objects as parameters?

Sending Objects as parameters are preferable by me. Advantages:

In case if we need more parameters in future, to be used by SL/BL layer we can include them without changing the method signatures in Service, Business and DAO layers.

Having a object with data can be reused by layers. If BL returns the same object type we can reuse the initialized object by changing its attributes.

More readable code. Suppose you have to pass 10-20 parameters, rather passing all those in separate fields I recommend a single Object as parameter.

Disadvantages:

We need to initialize a object that takes load time and memory.

We need to use lines of code to prepare and fetch object attributes.


问:
Algorithm to calculate trajectories from vector field
I have a two-dimensional vector field, i.e., for each point (x, y) I have a vector (u, v), whereas u and v are functions of x and y.

This vector field canonically defines a set of trajectories, i.e. a set of paths a particle would take if it follows along the vector field. In the following image, the vector field is depicted in red, and there are four trajectories which are partly visible, depicted in dark red:

I need an algorithm which efficiently calculates some trajectories for a given vector field. The trajectories must satisfy some kind of minimum denseness in the plane (for every point in the plane we must have a 'nearby' trajectory), or some other condition to get a reasonable set of trajectories.

I could not find anything useful on Google on this, and Stackexchange doesn't seem to handle the topic either.

Before I start devising such an algorithm by myself: Are there any known algorithms for this problem? What is their name, for which keywords do I have to search?

答:
This is about solution of differential equations.

In your case f(t) is position of particle in time moment t. f'(t) is velocity of point moving along this trajectory.

So if the vector field defines direction and magnitude of velocity, then the equation is f'(t)=V(f(t)).

To solve such equation you need some starting point. In "good" places where not many trajectories from different directions converge, it's OK to have even middle point and solve the equation in both directions.

So one of possible solutions for ensuring "denseness" is:

take random point

build trajectory for it

find point with maximal distance from existing trajectories

if this distance is small enough - we are done

build trajectory for this point

go to 3


答:
Obviously, you are dealing with a set of differential equations:

dx/dt = u(x, y)

dy/dt = v(x, y)

There a lot of algorithms, which can actually integrate such equations, but it will depend on the u and v (are they linear or not etc.). Can you provide some more info on this?

In relation to your requirement, is it correctly understood that you want to create multiple trajectories 'close to each other? Or do you mean something else?

EDIT:

I must have been a little confused when I wrote my original post. Obviously, the differential equations are linear, and the actual form of u and v are of less importance.

In fact, integrating these equations are quite simple. If the accuracy is less important, you could do a simple Euler integration - otherwise you might want to look into Runge-Kutta methods (for instance RK4 - fourth order Runge-Kutta).

Both of these are well known, thus I will not go into details here. Do a google search or check wiki:

Euler method

Runge-Kutta methods

Achieving denseness is somewhat more tricky I guess. As your differential equations are linear, slightly displacing the two initial positions will result in similar trajectories. Obviously, you can get the trajectories as similar as the computers precision allows. If you instead want the two trajectories to end in similar points, you can simply define the ending point and do the reverse integration.

Title: Algorithm to calculate trajectories from vector field

Body:
I have a two-dimensional vector field, i.e., for each point (x, y) I have a vector (u, v), whereas u and v are functions of x and y.

This vector field canonically defines a set of trajectories, i.e. a set of paths a particle would take if it follows along the vector field. In the following image, the vector field is depicted in red, and there are four trajectories which are partly visible, depicted in dark red:

I need an algorithm which efficiently calculates some trajectories for a given vector field. The trajectories must satisfy some kind of minimum denseness in the plane (for every point in the plane we must have a 'nearby' trajectory), or some other condition to get a reasonable set of trajectories.

I could not find anything useful on Google on this, and Stackexchange doesn't seem to handle the topic either.

Before I start devising such an algorithm by myself: Are there any known algorithms for this problem? What is their name, for which keywords do I have to search?


问:
Design patterns and multiple programming languages
I am referring here to the design patterns found in the GOF book. First, how I see it, there are a few peculiarities to design pattern and knowing multiple languages, for example in Java you really need a singleton but in Python you can do without it you write a module, I saw somewhere a wiki trying to write all GOF patterns for JavaScript and all the entries were empty, I guess because it might be a daunting task to do that adaptation.

If there is someone who is using design patterns and is programming multiple languages supporting the OOP paradigm and can give me a hint on how should I approach design patterns. An approach that might help me in all languages I use(Java, JavaScript, Python, Ruby):

Can I write good application without knowing exactly the GOF design patterns or I might need just some of them which might be crucial and if yes which one, are there alternatives to GOF for specific languages, and should a programmer or a team make their own design patterns set?

答:
First thing to understand is that design patterns are not a design tool. They're a communication tool. Can you write a good application without knowing the GOF design patterns? Absolutely. You'll probably find you use design patterns already, you just don't know it. After all, they are common solutions to common problems. But can you tell a colleague how to do something better? Not easily.

Second thing to understand is that some design patterns are so common that they're now built into most modern languages. For example, you don't need an Observer pattern in C#, you have events (which are the Observer pattern, but you never need to say to a C# developer "use an Observer there").

Third thing is that the GoF design patterns book was written several versions of Java many moons ago and was based very much on class-oriented languages. Javascript isn't a class-oriented language, it's a prototype-oriented language, and Python and Ruby are both dynamic. So some of the GoF patterns may be irrelevant to those languages (but some may not).

Much more useful nowadays are the patterns described in Martin Fowler's Patterns of Enterprise Application Architecture.

All this said, it's useful to understand the GoF patterns, if only to facilitate communication with other developers who understand them. The GoF book is dry and hard to get your head around sometimes -- they also make for an interesting thought exercise, they might prompt you to see common patterns in your team's application and write your own patterns. It's also not very precise (when you talk about the difference between Adapter, Proxy and Facade, for example).

There are some good sites out there with much clearer descriptions.


问:
Define which tests are run after build in Visual Studio 2012
Visual Studio 2012 has a new feature where it automatically runs your unit tests after every build.

I would like to use this feature, but I have a number of tests that should not be run after every build (long running performance tests, etc).

Is there a way to define which categories are run automatically?  Or some other way to define which test should be run?

答:
A colleague of mine wanted to know the answer to this question also.

He asked Cathy Sullivan (A Microsoft Visual Studio Program manager) on Twitter whether it was possible.

Cathy came back and said that unfortunately, it's not possible, however as part of the same conversation, Joshua Weber (another MS VS Program Manager) stated that Visual Studio's "Run Tests On Build" will honor any current filter you've applied within the search box.

(Image grab of twitter conversation)