Showing posts with label logic. Show all posts
Showing posts with label logic. Show all posts

Tuesday, February 14, 2012

business vs. logic

You have seen a chair in a public room and go back after a while to acquire it. Is it unexpected that the object is not there anymore?

I implement the business logic in stored procedures. Once user orders some service, the actions carry out are: a)check they have sufficient funds on their balance; and, b) a price check is made selecting the latest from pricelist. The newly created job entry refers the price in the pricelist table according to service_id and the issued pricelist date.

These are data validity checks, which must be done in a multiuser database. In the session beginning, user gets prices and funds. These data are not locked throughout the session -- another process may change the records. Therefore, the extra "business" checks are needed to preserve data correctness at the start of every transaction. One way to report the errors would be to raise an error.

Consider the primary-foreign key violations. They are raised by system with severity level of 16. Uniqueness violation is raised with severity 14. The MSSQL reference http://msdn2.microsoft.com/en-us/library/ms164086.aspx tells us that this is a sort of error, which can be corrected by user. Indeed, (s)he can. But the exceptions are unexpected situations. Exception processing consumes huge CPU processing power if some occurs. Normally, programs allocate resources and use them. If resource cannot be allocated -- app exits with exception. It just has nothing to do. However, there is nothing exceptional in shared data access by multiple concurrent processes in a multithread/multiuser/distributed application. Since, we cannot lock the user resources during user session, we should be prepared to concurrent data changes. Therefore, I find the exception raising inappropriate tool.

Consider a situation, when one user is assigned to a group. Nothing prevents from another admin to remove the group at the same time. Therefore, our user management application should be ready to expected "group does not exist" "error" result. I even disagree that this is an error, since it is perfectly valid to have such a situation. It is like you have seen a chair in a room and later return to take it. But the chair is not there anymore. Is it unexpected? The case should not be exceptional, IMO.

So we have:
1. Severity 1-10 "informational messages";
2. Severity 11-16 errors; and
3. RETURN error_code.

Which should be used? Anything else? Do my considerations make sense?

When I want the SQL Code to with certainly 'talk' back to the application code, I use RAISERROR.

For SQL Procedures to 'talk' with each other, I may also use the RETURN value.

I may use 'WITH LOG' to force the error condition into the Application Log.

And you are wise to question what is an error condition. Is it a 'system' error, a 'logic' error, or a 'business rule' exception?

|||Thank you, Arnie for sharing your experience.


> And you are wise to question what is an error condition. Is it a 'system'
> error, a 'logic' error, or a 'business rule' exception?

I believe that the "business logic" is an oxymoron likewise "market order", which is chaos and disorder in fact. Nevertheless, I do not distinguish between "rules" and "logic" here. It is logical that user balance should not go below zero, it is logical that the price must be the latest one, it is logical that user must belong to an existing group.

I understand the exceptions in a serial programing where your threads allocate (lock) resources but not in distributed programing where you cannot be sure about current condition of resources. It is ok for the local copies of the data to be incoherent in multiprocessor system. When data become incoherent, they may cause logic/rules/constraint/etc violations.

Some recommend checking file existence before opening it. But another process may remove the file between the check and open op. System returns "file does not exist" open error. It does not investigate whether the thread checked the file existence or it is making a reckless open. In other words, it does not examine the intentions and conditions of the caller. One utility would, for instance, set up admin rights for a list of users. This 'setadmin' app assumes the group 'admins' exists. It has nothing to do if there is no such group. It is exceptional situation for the app. Another application requests available groups, uses one and sends result back. Multiuser application should be prepared to situation where the used group does not exist anymore. A more realistic is a stock with multiple operators. When you have selected the list of available goods into a local copy, the goods can be removed by another operator.
You should tell the user that the product list is outdated, that it is incoherent with reality rather than complaining that the operation cannot be accomplished.

Looks like, error handling in distributed systems is more general than a DB errors issue. But any advices are welcomed.
|||

Valentin,

Note that I didn't use the term 'business logic', but instead used 'business rule exception' -and yet I agree with you that often business needs sometimes seem to defy logic; and that when describing the condition of a market, 'market order' could easily be a oxymoron, but when used as a entity, 'market order' has a definitive 'thing' quality about it.

This, and your other posts on Locking behavior demonstrate a deep concern for data integrity, and I can certainly appreciate your questions. When there are opportunities for instability, instability will occur. Stasis can only exist when ignoring temporality. Yet, in fact, Stasis cannot be separated from temporal considerations. The certainity of a state of data is increasingly uncertain as the system becomes more complex -distributed, multiprocessor, and multi-threaded. We often resort to extreme control when faced with apparant chaos. As TS Elliot would describe it, the time 'between' is the shadow, and we cannot ignore the shadow, for all things unknown exists in the shadow.

I once worked on a project where, for speed, data was cached on each web server in a very large web farm, and yet many data items were unique and ONLY one customer would be allowed to purchase that one item. There could be thousands of concurrent customers considering the same item. It was necessary to create a lot of communication between the cach objects, tenative 'sold' indicators, and definitive 'sold' indicators, 'cancellation', etc. You can imagine the chaos -but it did have a solution.

Since, as you put it so well, there are opportunities for chaos between the moment we determine IF an action can be taken AND the moment the action is actually taken, AND the 'system' doesn't help 'protect' us from that potential chaos, we are faced with having to find ways to invoke 'extreme control'. So like forcing all passengers through the security checkpoint as a single point of control, it may be useful to consider how to force all sensitive data activity through a 'single point of control'.

One useful approach is to force all data changes through Stored Procedures (No direct table access). Then in the Stored Procedure used to UPDATE a set of resouces in a TRANSACTION, also use sp_getapplock / sp_releaseapplock as a way to more tightly control access to the resources.

Here is an example: (Use Northwind database)

Code Snippet


CREATE PROCEDURE dbo.Employees_U_LastName
( @.EmployeeID int,
@.LastName varchar(20)
)
AS
BEGIN
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ
BEGIN TRANSACTION


DECLARE @.LockResult int

EXECUTE @.LockResult = sp_getapplock
@.Resource = 'ThisIsMyProcess-StayOut',
@.LockMode = 'Exclusive',
@.LockTimeout = 0

IF @.LockResult <> 0
BEGIN
ROLLBACK TRANSACTION
PRINT 'SomeOne Else is Using this Resource'
RETURN
END


PRINT 'TRANSACTION IS Active'
SELECT
EmployeeID,
LastName,
FirstName
FROM Employees
WHERE EmployeeID = @.EmployeeID


PRINT 'Waiting...'
WAITFOR DELAY '00:00:15'

PRINT 'Second UPDATE to Active TRANSACTION'
UPDATE Employees
SET LastName = @.LastName
WHERE EmployeeID = @.EmployeeID


EXECUTE sp_releaseapplock
@.Resource = 'ThisIsMyProcess-StayOut'


COMMIT TRANSACTION


PRINT 'Waiting for Other Process to Complete'
WAITFOR DELAY '00:00:05'

PRINT 'CHECK Results of TRANSACTION'
SELECT
EmployeeID,
LastName,
FirstName
FROM Employees
WHERE EmployeeID = @.EmployeeID


END
GO

Then execute this from two different connections.

Code Snippet


EXECUTE dbo.Employees_U_LastName
@.EmployeeID = 1,
@.LastName = 'Davolio-Jones'

In the second connection, you will get the message: 'SomeOne Else is Using this Resource'. But you have to be adamant that there is only one 'egress' point to the resources -through the procedure.

Perhaps this will help you along on your quest to find a secure and reliable method to control data

|||

Sometimes maybe it doesn't matter if the 'problem' is a 'system' error, a 'logic' error, or a 'business rule' error -the 'problem' has to be handled, and in the case at hand, they may all be handled the same. It is still very useful to keep clarity about the differences between them. For at times, the effect of treating them the 'same' is confusing at best.

valentin tihomirov wrote:

I do not distinguish between "rules" and "logic" here. It is logical that user balance should not go below zero, it is logical that the price must be the latest one, it is logical that user must belong to an existing group.

Logic follows defined mathematical sylogisms.

1 = 2

2 = 3

Therefore 3 = 1

is based on logic. That balance MUST be >= 0 is a Business decision (busines rule) solely BECAUSE [ bal < 0 ] is mathematically valid -but in this situation, this business has determined to not allow that to occur. A bank 'should' not allow an account to overdraw (balance >= 0 ) at all times, in other words, as the trustee for your money, the bank 'should' not give others money claiming that it is your money if you don't have money to give out. However, the banking industry decided that there was money to be earned by allowing overdrafts, and you can't charge for an overdraft UNLESS the balance is allowed to be less than zero, so the business rule changed, and balance can be less than zero ( to some limit ).

Logic is easy to code, business rules, subject to change, require a lot more effort and consideration.

Of course, I realize that you know what I'm talking about. I'm using your posting to help others that may be reading, and still learning, and still uncertain... (So I hope you accept the 'lecture' in that guise. I often respond to a posting with the realization that I may also be responding to other readers with similar -but not exactly the same, questions.)

|||

For clarification, in the demonstration procedure I posted earlier, I used a PRINT statement when checking if @.LockResult. Normally, I would raise an error so that the calling application (or procedure) can capture the error number and react accordingly.

First, create the Error in the database, (Use whatever Error Number ( > 50000 ) and message you wish.)

Code Snippet

EXECUTE sp_addmessage
@.msgnum = 51001,
@.severity = 16,
@.msgtext = N'Resource NOT Available',
@.lang = 'us_english',
@.replace = REPLACE

Then in the procedure:

Code Snippet

IF @.LockResult <> 0
BEGIN
ROLLBACK TRANSACTION
RAISERROR ( 51001, 16, 1 )
RETURN
END

Now the application (or calling procedure) can handle ErrorNumber 51001 as deemed necessary. Wait a few seconds and Re-Submit perhaps...

|||

Arnie Rowland wrote:

One useful approach is to force all data changes through Stored Procedures (No direct table access).

SPs are really how I'm trying to do it. Thanks for hinting about sp_getapplock. It looks like a 'lock' object (mutex, critical section) in conventional programming language. However, I think it is too coarse-grain. All the users who wish to change their last names will lock each other. In addition, this lock shell be taken by parties who affect the last names in different way (removing the record, for instance). And you get the whole database locked/synchronized by one big lock. The granularity of automatic transactional locks are one record. However, using full db object names like db_name.table_1.row_id.field_x we can outperform the locking granularity down to field finesse. These are my first ideas about the procedure. Thanks for the hint.

Arnie Rowland wrote:

Logic follows defined mathematical sylogisms.

I was learnt it is the math, which is a science of proving, which is based on logic But I think I can understand the difference between logic and rules now. Thank you for the explanation.

Arnie Rowland wrote:

Of course, I realize that you know what I'm talking about. I'm using your posting to help others that may be reading, and still learning, and still uncertain... (So I hope you accept the 'lecture' in that guise. I often respond to a posting with the realization that I may also be responding to other readers with similar -but not exactly the same, questions.)


That is ok, I am a communist. The sharing is a means of saving resources and a condition of intelligent life survival on the planet Earth.

|||

You're right, using sp_getapplock is kind of 'course-grained'; sp_getapplock creates a 'lock' object, using the name you provide. The only thing 'locked' is the entry to the sproc code. The included (and required) TRANSACTION locks the underlying data. However, blocking others from using the sproc code in practice creates a single 'gateway' through which all controlled activity must pass, effectively forcing serialization of the controlled activity. I would want to make the process as streamlined and efficient as possible in order to cause the minimal amount of queue stacking.

In a very high performance / high utilitzation system, using sp_getapplock just may prove to be to much of a 'bottleneck'. But, if one was concerned about reading into an active TRANSACTION, and the effects on other activities as a result of being able to read into an active TRANSACTION, sp_getapplock is one way to reduce the 'paranoia'. It may be too 'heavy-handed' for most use.

...deleted...

Keep up the good questions.

business process logic in stored procedures

Hi All,
I've always tried to think of and use sql as being a tool to quickly
retrieve / update relevant data, and let other parts of a system handle
the decisions as to what needs to be done to the data. However I keep
coming across (and sometimes find myself creating) the situation where
there are massive stored procedures which will have several different
statements, pulling data from loads of tables and updating others based
on some business logic.
First question: is this a bad thing?
as I see it this has the advantage that updates can be expressed as a
function to be applied over a whole table, making the process much
faster than if the data was changed in a business layer, then
propogated to the database. However the "code" is hard for someone else
to understand, and hard to re-use/improve. I often find that processes
which would be modelled with quite a large framework of objects are
condensed down into a large stored procedure, such that to anyone else
looking at it will just see a mass of update insert and selects with no
idea why.
Second question: when to do it?
I have found that at times it's unaviodable, either for performance or
simply the ease of access to all the data that I need to use a stored
proc, does anyone have any rules of thumb as to when it's a good/bad
idea?
Third question: what are the alternatives?
I'd hope that there are other ways to get around the problems that
people are solving using sql, does anyone have any links/suggestions of
how to approach things that people would often resort to sql for, using
more maintainable methods?
I could probably rattle on for days on this issue, but I'm hoping maybe
people will be able to suggest some best practice about this.
Cheers
WillWill
1),2)
I remember some times ago it was discussion about this subject and some
people say that they put the business logic in the stored procedure and
some people say they do not but only code/dll....
I have been praticipate in some projects where we put all login in to
stored procedure and it was relaible/readable and worder very good in terms
of perfomance as well
So the answer will be it depends on YOUR project's business logic and sure
if you can test 'somehow' and make the right decision
3) Well if you develop multi tier application the question is where to put
BL in data layer (dll that access to the database) or directly to stored
procedures
Again , I have seen many projects where people (including me) put the logic
into SP and some projects where people put the BL (including me) in the
code, so it is really DEPENDS on many things.
If you are lucky and Erlan ( and many others here at forum) jump in , it is
interesting to see what does he suggest ?
"Will" <william_pegg@.yahoo.co.uk> wrote in message
news:1144324357.527781.15400@.e56g2000cwe.googlegroups.com...
> Hi All,
> I've always tried to think of and use sql as being a tool to quickly
> retrieve / update relevant data, and let other parts of a system handle
> the decisions as to what needs to be done to the data. However I keep
> coming across (and sometimes find myself creating) the situation where
> there are massive stored procedures which will have several different
> statements, pulling data from loads of tables and updating others based
> on some business logic.
> First question: is this a bad thing?
> as I see it this has the advantage that updates can be expressed as a
> function to be applied over a whole table, making the process much
> faster than if the data was changed in a business layer, then
> propogated to the database. However the "code" is hard for someone else
> to understand, and hard to re-use/improve. I often find that processes
> which would be modelled with quite a large framework of objects are
> condensed down into a large stored procedure, such that to anyone else
> looking at it will just see a mass of update insert and selects with no
> idea why.
> Second question: when to do it?
> I have found that at times it's unaviodable, either for performance or
> simply the ease of access to all the data that I need to use a stored
> proc, does anyone have any rules of thumb as to when it's a good/bad
> idea?
> Third question: what are the alternatives?
> I'd hope that there are other ways to get around the problems that
> people are solving using sql, does anyone have any links/suggestions of
> how to approach things that people would often resort to sql for, using
> more maintainable methods?
> I could probably rattle on for days on this issue, but I'm hoping maybe
> people will be able to suggest some best practice about this.
> Cheers
> Will
>

Business Logic Object as Data Source in SQL Reporting Services

Hi all,
I'm running SQL Reporting Services and my question is:
Can I connect the datasource of my reports to a business logic object that
returns a dataset instead of using a direct connection to a SQL Server?
Anyone that knows if and how this can be done?
Regards
-Janne HasslfWhy didn't you post to the reportingsvcs newsgroup?
Aaron Bertrand
SQL Server MVP
http://www.aspfaq.com/
"Janne" <janne.hasslof@.stenaline.com> wrote in message
news:70190248.0401290423.26d52934@.posting.google.com...
quote:

> Hi all,
> I'm running SQL Reporting Services and my question is:
> Can I connect the datasource of my reports to a business logic object that
> returns a dataset instead of using a direct connection to a SQL Server?
> Anyone that knows if and how this can be done?
> Regards
> -Janne Hasslf

Business Logic Object as Data Source in SQL Reporting Services

Hi all,
I'm running SQL Reporting Services and my question is:
Can I connect the datasource of my reports to a business logic object that
returns a dataset instead of using a direct connection to a SQL Server?
Anyone that knows if and how this can be done?do you have an OLE DB or .NET data provider to connect to BO?
-Aaron
Norberto Mesen Lopez wrote:
> Hi all,
> I'm running SQL Reporting Services and my question is:
> Can I connect the datasource of my reports to a business logic object that
> returns a dataset instead of using a direct connection to a SQL Server?
> Anyone that knows if and how this can be done?

business logic location

For quite a while I've had pretty good success with putting most of my
business logic in stored procedures and triggers. It's fast, relational,
searchable, and updatable without any recompiling.
At the moment I'm considering supporting both SQL Server and Oracle, and it
seems to me that to support multiple database platforms the business logic
needs to be moved out of the database layer. Not only would this seem
necessary to me, but it would also seem to be ugly, much more complicated,
harder to maintain, and slower, maybe far slower.
This is the first time I've looked at this problem; it was my assessment
years ago that deep business logic (not the minor stuff associated with just
the UI) in hard code was a bad idea. I was hoping someone could share their
point of view on this area with me, maybe point out some examples of how
multiple database support is currently done, and how feasable (automatable)
it is to port data, with stored procedures and triggers, between SQL and
Oracle.
PaulOn Mon, 19 Sep 2005 10:44:04 -0400, PJ6 wrote:

>For quite a while I've had pretty good success with putting most of my
>business logic in stored procedures and triggers. It's fast, relational,
>searchable, and updatable without any recompiling.
>At the moment I'm considering supporting both SQL Server and Oracle, and it
>seems to me that to support multiple database platforms the business logic
>needs to be moved out of the database layer. Not only would this seem
>necessary to me, but it would also seem to be ugly, much more complicated,
>harder to maintain, and slower, maybe far slower.
Hi Paul,
I disagree. Even when porting to Oracle or any other platform, you'll
still have to have the business logic in the data layer. Just think
back: over the last few years, how many client technologies have you
seen come and go? And how many times did you switch database vendor?
Besides: business rules in the front end tend to be much easier to
bypass than business rules in triggers in the database.

>This is the first time I've looked at this problem; it was my assessment
>years ago that deep business logic (not the minor stuff associated with jus
t
>the UI) in hard code was a bad idea. I was hoping someone could share their
>point of view on this area with me, maybe point out some examples of how
>multiple database support is currently done, and how feasable (automatable)
>it is to port data, with stored procedures and triggers, between SQL and
>Oracle.
It helps if you start coding from day one with the idea that you might
one day have to port. Use ANSI-standard whenever feasible. If you do use
proprietary (because ANSI would require an extremely ugly kludge or many
extra lines of code, or because the ANSI version is lots slower),
document it, and describe how the ANSI version looks.
You'll still have a lot of work carved out for you before you'll be
ready to run the same product on SQL Server and Oracle, becuase there
are lots of irritating differences. Expect the porting of data to be
relatively easy, the porting of queries quite complicated and the
porting of stored procedures and triggers to be hell. Especially if you
didn't write the original code with portability as one of the design
objectives...
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)|||"Hugo Kornelis" <hugo@.pe_NO_rFact.in_SPAM_fo> wrote in message
news:7u01j1tqn6tnoaol3siot2te99bl5psnne@.
4ax.com...
<...>
> Besides: business rules in the front end tend to be much easier to
> bypass than business rules in triggers in the database.
<...>
> You'll still have a lot of work carved out for you before you'll be
> ready to run the same product on SQL Server and Oracle, becuase there
> are lots of irritating differences. Expect the porting of data to be
> relatively easy, the porting of queries quite complicated and the
> porting of stored procedures and triggers to be hell. Especially if you
> didn't write the original code with portability as one of the design
> objectives...
Well I guess I'll to stand by my choice to keep most business logic in the
data layer then, and damn the torpeedos, we won't support Oracle.
MSDE is free anyway.
Paul|||"PJ6" <nobody@.nowhere.net> wrote in message
news:eEAw3rrvFHA.2932@.TK2MSFTNGP10.phx.gbl...
... we won't support Oracle.
Great idea... :-)|||>Especially if you
>didn't write the original code with >portability as one of the design
>objectives...
just wanted to add that the price for portability may be very very
high.
For instance, a wide table, appr. 4100 bytes per row, which menas 1 row
per page. Start using those "horrible proprietary" data types like bit
and smalldatatime, and here you go: 3900 bytes, 2 rows per page!
Having sacrificed portasbility, all of a sudden you get 100% better
performance.
There are also plenty of differences in locking and concurrency, index
behaviour etc.|||On Wed, 21 Sep 2005 10:44:26 -0400, PJ6 wrote:

>"Hugo Kornelis" <hugo@.pe_NO_rFact.in_SPAM_fo> wrote in message
> news:7u01j1tqn6tnoaol3siot2te99bl5psnne@.
4ax.com...
><...>
><...>
>Well I guess I'll to stand by my choice to keep most business logic in the
>data layer then, and damn the torpeedos, we won't support Oracle.
Hi Paul,
If the expected extra revenues do not outweigh the expected cost of
having to maintain two versions of the code plus the write-off of the
conversion to Oracle, that'd be the soundest decision.

>MSDE is free anyway.
And ditto for SQL Express (with even less limitation, IIRC).
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)|||On 21 Sep 2005 08:45:19 -0700, Alexander Kuznetsov wrote:

>just wanted to add that the price for portability may be very very
>high.
(snip)
>Having sacrificed portasbility, all of a sudden you get 100% better
>performance.
Hi Alexander,
Great example!
That's exactly why I want portability to be "one of" the design
objectives. Not the only one, nor even the most important one.
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)

business logic in Stored Proc VS aspx.vb page

Hello,

I stuck in a delimma.
Where to put the business logic that involves only one update
but N number of selects from N tables......with N where conditionsHi

In general I would put this in the middle tier or the database. Allowing
direct access to tables from a client would raise security issues and make
it less managable.

John

"A.V.C." <yhspl_softwaregroup@.hotmail.com> wrote in message
news:d28fa5d0.0407060443.2797e77@.posting.google.co m...
> Hello,
> I stuck in a delimma.
> Where to put the business logic that involves only one update
> but N number of selects from N tables......with N where conditions|||A.V.C. (yhspl_softwaregroup@.hotmail.com) writes:
> I stuck in a delimma.
> Where to put the business logic that involves only one update
> but N number of selects from N tables......with N where conditions

I am of the school that puts as much as possible of the business logic
in the stored procedures. The idea is to put the logic where the data is.
If you put logic in the middle tier, you may have a lot network traffic.

The one case where the middle layer is a better place, is when you
have computations that are very intensive on reports. Then you can
take off load from SQL Server, and you can more easilyu scale out.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||"Erland Sommarskog" <esquel@.sommarskog.se> wrote in message
news:Xns951EF3408DA66Yazorman@.127.0.0.1...
> A.V.C. (yhspl_softwaregroup@.hotmail.com) writes:
> > I stuck in a delimma.
> > Where to put the business logic that involves only one update
> > but N number of selects from N tables......with N where conditions
> I am of the school that puts as much as possible of the business logic
> in the stored procedures. The idea is to put the logic where the data is.
> If you put logic in the middle tier, you may have a lot network traffic.

Which would not have otherwise existed if the logic is internal
to the database stored procedure.

> The one case where the middle layer is a better place, is when you
> have computations that are very intensive on reports. Then you can
> take off load from SQL Server, and you can more easilyu scale out.

Where separate pre-processing (ie: regeneration of the computed
values) into a work table is feasible, then this can allow the logic to
be retained in SQL because the realtime computations have been
reduced.|||THanx
Could you pls elaborate the scenario where middle tier is ideal for business logic ?

Erland Sommarskog <esquel@.sommarskog.se> wrote in message news:<Xns951EF3408DA66Yazorman@.127.0.0.1>...
> A.V.C. (yhspl_softwaregroup@.hotmail.com) writes:
> > I stuck in a delimma.
> > Where to put the business logic that involves only one update
> > but N number of selects from N tables......with N where conditions
> I am of the school that puts as much as possible of the business logic
> in the stored procedures. The idea is to put the logic where the data is.
> If you put logic in the middle tier, you may have a lot network traffic.
> The one case where the middle layer is a better place, is when you
> have computations that are very intensive on reports. Then you can
> take off load from SQL Server, and you can more easilyu scale out.|||A.V.C. (yhspl_softwaregroup@.hotmail.com) writes:
> Could you pls elaborate the scenario where middle tier is ideal for
> business logic ?

Permit me to take an example from the system I work with, which is abour
securities trading. When a deal comes in there are a couple of computations
to carry out give the basics: price and the quantity. Most of these
computations are simple: price * qty gives your the purchase amount, and
then you compute charges. And to compute charges you require access to
data, because the charges depends on the customer and instrument and this
is information that is in several tables.

The one exception here is when you trade with bonds, because they may be
traded on interest rather than price, in which case the price has to be
computed from the interest. You also have to compute the accrued interest
for the bond, that the seller is to pay to the buyer. These computations
are not very simple to implement in SQL. What we do is that we call a
COM object that runs on the SQL Server machine that performs the
computation, so we still have this logic on the server.

Our customers have fairly modest volume of bond deals, so this is not an
issue. But assume that you have a site that trades exclusively in bonds,
and can perform many trades a second (not very likely, I think). In this
case, having the COM object on the server would take some toll that would
be bearable. We could make the COM object remote, but it would still be
one server. If instead the middle tier would get all trades to compute,
there could be several machines that each gets their load, so you can scale
better.

It's maybe not the best example, but I think it gives you the idea that
even if you put some logic in the middle tier, it may not be all logic,
but only some specific part.

Finally one more argument for having the logic in stored procedures: you
have all the code in one place. If you use the middle tier, you will jump
forth and back in different languages and the code is more difficult to
follow, debug and maintain.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp

business logic in store procedure

Hey guys,
I have to import a csv file to my database and then addsome values to other fields based on these values. At present I use astore procedure that does a bulk insert and then I use an update andfetch inside the sql to perform these updates. I am not sure if this isthe best way. Is this bad, since some amount of busniess logic is inthe store procedure?

If it is, how can I do this better?
Thanks for the answer.

Yes, it's fine to do add values in the stored procedure. And if as you say, all the values that need to be added can be computed from existing values in the csv file (or the corresponding table), we can add computed column(s) to the table. Then no extra update is needed. For example, if we import csv file into a table T(firstName varchar(20), LastName varchar(20)), and we want to add a full name column based on the firstName and lastName, we can add a computed column:

alter table T add fullName as firstName+' '+lastName

Business Logic Handler Not Loading

I'm trying to implement a custom conflict resolver by inheriting from

Microsoft.SqlServer.Replication.BusinessLogicSupport.BusinessLogicModule. The replication is between a SQL Server 2005 Express subscriber and a SQL Server 2005 publisher/distributer.

The problem is that the resolver class in the DLL will not load; although, it does appear to find the DLL. (If I rename the DLL I get a "file not found error"). The exact error message is:

Microsoft.SqlServer.Replication.ComErrorException

"Error loading custom class "MergeConflictHandler" from custom assembly "MergeConflictHandler",

Error : "Could not load type 'MergeConflictHandler' from assembly 'MergeConflictHandler, Version=1.0.2502.22393, Culture=neutral, PublicKeyToken=0403e50cc4dc27fa'."."}

I placed the DLL in the directory of the program that calls SynchronizationAgent.Synchronize and tried it with and without being registered in the GAC. There was no change. Interestingly, when I move the file out of that location, but register it in the GAC, the file is not found. Thinking it may be a security problem, I gave Everyone Read & Execute and Read privileges. I believe the class is actually instantiated by replmerge.exe, an apparantly unmanaged app, so I tried marking it ComVisible. No Luck.

I registered the resolver with the following T-SQL code:

sp_registercustomresolver @.article_resolver = 'eClinical Notes Conflict Resolver'

, @.is_dotnet_assembly = 'true'

, @.dotnet_assembly_name = 'MergeConflictHandler'

, @.dotnet_class_name = 'MergeConflictHandler'

, @.resolver_clsid = Null

The resolver I've created is not much more than a shell at this point. It is pasted below, but I tried using the code found on MSDN character-for-character and had the same problem.

using System;

using System.Text;

using System.Data;

using System.Data.Common;

using Microsoft.SqlServer.Replication.BusinessLogicSupport;

namespace MergeConflictHandler

{

public class MergeConflictHandler :

Microsoft.SqlServer.Replication.BusinessLogicSupport.BusinessLogicModule

{

// Variables to hold server names.

private string m_PublisherName;

private string m_SubscriberName;

private string m_Artical_Name;

public MergeConflictHandler()

{

}

// Implement the Initialize method to get publication

// and subscription information.

public override void Initialize(string publisher, string subscriber, string distributor, string publisherDB, string subscriberDB,string articleName)

{

m_PublisherName = publisher;

m_SubscriberName = subscriber;

m_Artical_Name = articleName;

}

// Declare what types of row changes, conflicts, or errors to handle.

public override ChangeStates HandledChangeStates

{

get

{

return ChangeStates.UpdateConflicts;

}

}

public override ActionOnUpdateConflict UpdateConflictsHandler(DataSet publisherDataSet, DataSet subscriberDataSet, ref DataSet customDataSet, ref ConflictLogType conflictLogType, ref string customConflictMessage, ref int historyLogLevel, ref string historyLogMessage)

{

if (m_Artical_Name == "PatientAllergies")

{

// Accept the updated data in the Subscriber's data set and apply it to the Publisher.

}

return ActionOnUpdateConflict.AcceptPublisherData;

}

}

}

Does anyone have any thoughts or advice? (Help!)

I had similar problems

I found that the parameter @.dotnet_class_name had to be set to assemblyName.className

If in your case the assembly is named the same as the class then it would need to be set to MergeConflictHandler.MergeConflictHandler

|||

Aero1 Thanks So Much

It is now working, although not exactly as you said. Apparantly the @.dot_class_name parameter needs to be prefixed with the Namespace, not the assemblyName. Perhaps your name space and assemblyName were the same for you? Anyway, I had tried prefixing the Namespace before, but obviously I did something wrong then. As an added benefit, it makes sense. Of course it still should be better documented! So to highlight the answer for future readers:

@.dot_class_name = 'Namespace.Classname'

Thanks again... Life is once again worth living.

|||

This is documented in: http://msdn2.microsoft.com/zh-cn/library/ms147911.aspx

However we will try to make it more discoverable.

Business Logic Handler called in which direction?

When running a business logic handler at the subscriber, you can override SubscriberInserts, SubscriberUpdates and SubscriberDeletes. Are these methods called when data is changed coming from the server to client, from the client to the server, or in both directions?

Thanks,

Bryan

It should be in both directions.

Business Layer

Hi,
Could some one help me in understanding the concept of Business Layer logic
implemented in Applications? Well,i'm purely a DBA guy and not much exposed
to Appliaction development.Any help/url for reference would be appreciated.
Thanks,
ShyamScalable and well-designed systems are usually divided into at least three
layers. The data layer is the back-end storage, indexing and retrieval
mechanism. Application layer is the front-end UI. The business logic layer
sits in between these two, enforcing your business rules. As an
oversimplified example (follow the numbered steps in order):
Application layer: 1. User inputs the name "JOHNSON" and presses Search
button. 2. Application layer sends request to business logic layer for
processing. 7. After it receives a response from the Business logic layer,
it formats the ouput correctly and displays to the user.
Business logic layer: 3. Validates that the name input is valid (i.e., no
numeric characters in the name) and formats a request to be submitted to the
data layer. 6. Returns results from the data layer to the Applicatin layer
for presentation.
Data layer: 4. Receives the request from the Business logic layer (i.e.,
"SELECT * FROM People WHERE LastName = 'JOHNSON'") and 5. returns the data
to the Business logic layer.
Web services that sit between an application UI and a SQL Database are a
good vehicle for implementing business logic layers (they are not the only
option though).
"Shyam" <Shyam@.discussions.microsoft.com> wrote in message
news:07B1F0E0-191C-46BA-8D6C-A65C26684609@.microsoft.com...
> Hi,
> Could some one help me in understanding the concept of Business Layer
> logic
> implemented in Applications? Well,i'm purely a DBA guy and not much
> exposed
> to Appliaction development.Any help/url for reference would be
> appreciated.
> Thanks,
> Shyam