I'm unsure as to what is the set-in-stone way to access databases - database

I have quite a deal of experience programing with VB6, VB.NET, C# so on and have used ADO, then SubSonic and now I am learning nHibernate since most of the prospective jobs I can go for use nHibernate.
The thing is, I have been programming based on what I have been taught, read or come to understand as best practice. Recently, someone through a spanner in the works and had me thinking. Up until now, I have been accessing the database(s) from both the core applcation and attached DLLs that I write.
What this persons said ends as follows and hence my question:
I can tell you
that you wouldn't normally want to do this - an external class library shouldn't have access to the database
What I was trying to do was to have a shared/static class for nHibernate sessions that could be consumed in both the global scope of the app and from any dll. This class was to be in a "core" DLL which all dlls and the application reference. Like I said I'm learning nHibernate so it may not be the way.
To say i'm questioning my database access methods is putting it lightly.
Can anyone put me straight on this?
Edit:
I suppose looking at what has been commented already, it depends on how the database is being accessed. I would tend never to put username/password credentials etc hardcoded in any DLLs for any means.
More specifically, my query is in relation to NHibernate's sessions. I have a static class, an helper class, which is called at application start and the new session is then created and attached to the current context, in the case of web applications, and then whenever I need the session I call "GetCurrentSession". This static class is in the "core" dll and can be accessed with any DLL etc that references. This behaviour is intended. My only question is is this ok? Should I be doing it another way?

A couple of reasons would be
Access to the database, how do you cover off username/password
sharing the DLL, a "bad" application may get hold of your DLL and link with it to get access to your database.
Saying this, if you have proper security on files, etc. then I would have thought using a DLL would probably be a reasonable way to go.

Assuming that the username and password are not stored directly in the DLL (but maybe passed as parameters, or passed as a complete connection object) this isn't so bad.
The possible bad practice here might be accessing the same database for the same purpose from different places - core app and DLL. This could get confusing quickly to a new developer, unless the separation is clear and logical.
Myself, I might try to move ALL (or almost all) data access to a DLL just for that purpose, then have the serious application logic (or as much as possible) in the core app or yet another DLL.

Related

SSDT Circular reference: Complex project

I have a fairly complex setup with eight databases on a server each referencing each other (about every database referencing each other), giving way to quite a complex web. The design is far from ideal, but unfortunately this is something we have to work with.
We need to create a SSDT solution to facilitate CI/CD
The whole project needs to be deployed from scratch on a new instance and I am trying to get my head around this, as I have limited SSDT knowledge for a project this scale.
The approaches I consider are as follows:
1) Split objects into shared objects, and reference the shared objects. This seems to be a nightmare to implement, as we would require different layers because of the complex web of references. (shared object referencing other shared objects). Also how do we deploy such a project on a blank server?
2) Create stubs for each object in a project being referenced by other objects, and make a database reference to these. This seems to be the easiest option, although it seems that if the object the stub is based on gets changed, the stubs also needs to be maintained otherwise the project will break. Is this the right assumption?
3) Only create stubs for projects required to compile (eg. tables referenced by views in other databases), and ignore warning references. I am leaning towards this route as the stubs will be much smaller and project easier to maintain, but I hate to ignore referencewarnings..
If we deploy using the stubs option, do we need to deploy the stubs first and then delete them after successful deployment?
Another (more straightforward question). What is the best way to deploy logins, users and object permissions ?
Thanks for replying.
The question is too broad but these are few suggestions:
You can't do anything with circular reference. There are some ways to workaround it but all of them are "hacky" and most probably will introduce more problems than to solve your problem. So try to move objects in so manner that there is only one way dependency;
Use synonyms for ALL cross database objects, so there supposed to be no straight reference outside database;
I agree with Peter Schott that it is better to ignore logins and users for now as handling them in SSDT is a bit of pain and you need to have good expertise on SSDT to make it working properly.

How to remove EntityFramework.SqlServer Reference from WebApplication project in a DDD Solution

I have a highly standardized project in DDD (Domain-Driven Design), so it means that each layer has it's responsibilities and no layer knows other than itself and the Domain Layer.
Here's the structure of my project:
My Infra.Data layer is responsible for connecting with the Database, and i'm persisting using EntityFramework.
My problem is: in order to make it work with SQLServer Databases, i need to add a reference to EntityFramework.SqlServer in my WebApplication layer, which breaks my separation of concerns concept, as you can see below.
Even having the same reference in my Infra.Data layer, which is where it only should be, as you can see below.
If i remove the EntityFramework.SqlServer reference from the WebApplication layer, it stops working, and throws exception every time i try to persist data, as you can see below.
I need to know how to remove this reference to keep separation of concerns, because the way it is now, i'll have to change my WebApplication if i want to change my persistence. My Web layer is prohibited to even have anything with the word "EntityFramework" in it. I want FULL separation of concerns to change any layer without affecting no other.
If i register my <entityFramework> provider in my Web.config file, it will only works if i have the EntityFramework.SqlServer in the project, but without the EntityFramework.SqlServer reference on the WebApplication, it miss namespaces and complain about it.
Note: My project also connects to MySql Databases successfully, and i don't need no references to MySql.Data or any other MySql library in my WebApplication layer, as expected.
Please help me, my DDD/Separation of Concerns OCD is cracking on it, thanks.
You can!
Just create this class in your Infra.Data project:
internal static class ForceEFToCopyDllToOutput
{
private static SqlProviderServices instance = SqlProviderServices.Instance;
}
When you do this you let the compiler know that the specific resource is used and should be available in the bin folder.
Some consider this a hack but it's useful if you want to keep your layers free from infrastructure concerns.
You can read more about this here: DLL reference not copying into project bin
EDIT:
All you'll need now is to copy the connection string from your Infra.Data app.config to your WebApplication web.config
<connectionStrings>
<add name="DatabaseConnectionString" providerName="System.Data.SqlClient" connectionString="..." />
</connectionStrings>
You would not be able to get rid of Entity-framework configuration and the required DLL in your Web-application :
Lets say your infrastructure layer and domain layer need to depend on Entity-framework. This means these two libraries need to have physical access to Entity Framework DLLs(Have Entity-framework package installed) and configured.
When you run your web application which has dependency on infrastructure and domain libraries, all Dlls used by underlying libraries (infrastructure and domain) need to be present physically and configured otherwise you will have run time issue(program might be compile-able but you will get run-time errors).
Morale of the story : If application x [Irrespective of the layer it belongs to] has dependency to library y,z and library y,z rely on some dll and require configuration, for application x to work at run-time you need to have all dlls needed by y,z available and provide their configuration (web.config) in your instance.
You can obviously provide some workarounds such as copying the files directly and providing separate config files for each layer but I strongly advise against it because it would get extremely messy and very hard to maintain in the long run.

How can I execute code stored in a database?

How can I store, for example, the body of a method in a database and later run it? (I'm using Delphi XE2; maybe RTTI would help.)
RTTI is not a full language interpreter. Delphi is a compiled language. You write it, compile it, and distribute only your binaries. Unless you're Embarcadero, you don't have rights to distribute DCC32 (the command line compiler).
However, the JVCL includes a delphi-like language subset wrapped up in a very easy to use Component, called "JvInterpreter". You could write some code (as pascal) and place it in a database. You could then "run that code" (interpreted, not compiled) that you pull from the database. Typically these should be procedures that call methods in your code. YOu have to write some "wrappers" that expose the compiled APIs that you wish to expose to the interpreter (provide access to live data, or database connection objects, or table/query objects). You're thinking that this sounds perfect right? Well, it's a trap.
Beware of something called "the configuration complexity clock". YOu've just reached 9 o'clock, and that's where a lot of pain and suffering begins. Just like when you have a problem, and you solve it with regular expressions, and "now you have two problems", adding scripting and DSLs to your app has a way of solving one problem and creating several others.
While I think the "DLL stored in a database blob field" idea is evil, and absurd, I think that wanton addition of scripting and domain-specific languages to applications is also asking for a lot of pain. Ask yourself first if some other simpler solution could work. Then apply the YAGNI principle (You Ain't Gonna Need It) and KISS (keep-it-simple-smartguy).
Think twice before you implement anything like what you're asking about doing in your question.
Your best Option, IMHO, is using a scripting engine and storing scripts in the database.
Alternatively you could put the code in a dll and put that dll in the database. There is code for loading a dll from a resource into ram and processing it so it can be used as if it was loaded using LoadLibrary, e.g. in dzlib. I don't really know whether works with any dll and in which versions of Windows, but it does with the ones I tried.

Organizing Apex Classes under Namespace

Is there any way in Salesforce to group apex classes under a package or namespace? Can we use managed package for internal organization purpose?
This is a limitation in the force.com stack that makes medium-large size projects painful, if not impractical. Using managed packages in order to get a package prefix doesn't really solve any problems, so it's not really worth the trouble.
I usually try to organize a project into one flat level of namespaces. In lieu of actual namespaces, I'll give each would-be-namespace a 3-5 character name, to be used as a prefix. Any class that belongs in the "namespace" gets prefixed. E.g., if I need a payroll namespace, I'd use a PYRL prefix. A class called PaycheckCalculator becomes PYRL_PaycheckCalculator.
The practical advantage of this type of convention is it helps prevent name clashes and classes are grouped by their "namespace" when viewed in a sorted list, such as in an IDE, or Setup > Develop > Apex Classes
Unfortunately, several basic OO principles are still fundamentally broken. Probably the most important one is every class forms an implicit dependency on every other class it has visibility to, which is all of them.
I'd love to hear how others have worked around this limitation.
Well, you can use managed packages, but as Jeremy mentioned it doesn't really buy you much. Of course managed packages are essential for developing publicly listed apps to sell on the AppExchange. But internally it's really an org-wide problem since once you create a managed package with a prefix, everything that touches any other part of it gets stamped with the same namespace prefix, including all custom objects. And worse, you can't access code in a managed package from outside the managed package (which is actually the whole point of them in the first place).
Although it's not the prettiest solution, what I personally do is maintain numerous named orgs with different purposes, applications and utility classes. When I need a utility class in one org, say I'm building a new app destined for the AppExchange, I'll do an Eclipse Export/Import from the utility org in question. It definitely seems strange but having a library of orgs is the best way I've managed to keep track of everything and to manage "internal" organization. But the end result is really just a glorified copy-paste operation between arbitrary code stores.
I faced similar challenges while working on big projects, wrote this blog post sometime back to share the approach I am following now : http://www.tgerm.com/2011/11/apex-class-naming-convention-suggestion.html

VBScript/ASP Classic

I have a couple of questions regarding VBScript and ASP Classic:
What is the preferred way to access an MS SQL Server database in VBScript/ASP?
What are best practices in regards to separating model from view from controller?
Any other things I should know about either VBScript or ASP?
If you haven't noticed, I'm new at VBScript coding. I realize numbers 2 & 3 are kind of giant "black hole" questions that are overly general, so don't think that I'm expecting to learn everything there is to know about those two questions from here.
ADO is an excellent way to access a database in VBScript/Classic ASP.
Dim db: Set db = Server.CreateObject("ADODB.Connection")
db.Open "yourconnectionstring -> see connectionstrings.com"
Dim rs: Set rs = db.Execute("SELECT firstName from Employees")
While Not rs.EOF
Response.Write rs("firstName")
rs.MoveNext
Wend
rs.Close
More info here: http://www.technowledgebase.com/2007/06/12/vbscript-how-to-create-an-ado-connection-and-run-a-query/
One caveat is that if you are returning a MEMO field in a recordset, be sure you only select ONE MEMO field at a time, and make sure it is the LAST column in your query. Otherwise you will run into problems.
(Reference: http://lists.evolt.org/archive/Week-of-Mon-20040329/157305.html )
I had to walk away from my PC when I saw the first answer, and am still distressed that it has been approved by so many people. It's an appalling example of the very worst kind of ASP code, the kind that would ensure your site is SQL-injectable and, if you continue using this code across the site, hackable within an inch of its life.
This is NOT the kind of code you should be giving to someone new to ASP coding as they will think it is the professional way of coding in the language!
NEVER reveal a connection string in your code as it contains the username and password to your database. Use a UDL file instead, or at the very least a constant that can be declared elsewhere and used across the site.
There is no longer any good excuse for using inline SQL for any operation in a web environment. Use a stored procedure -- the security benefits cannot be stressed enough. If you really can't do that then look at inline parameters as a second-best option... Inline SQL will leave your site wide open to SQL injection, malware injection and the rest.
Late declaration of variables can lead to sloppy coding. Use "option explicit" and declare variables at the top of the function. This is best practice rather than a real WTF, but it's best to start as you mean to go on.
No hints to the database as to what type of connection this is -- is it for reading only, or will the user be updating records? The connection can be optimised and the database can handle locking very efficiently if effectively told what to expect.
The database connection is not closed after use, and the recordset object isn't fully destroyed.
ASP is still a strong language, despite many folks suggesting moving to .NET -- with good coding practices an ASP site can be written that is easy to maintain, scaleable and fast, but you HAVE to make sure you use every method available to make your code efficient, you HAVE to maintain good coding practices and a little forethought. A good editor will help too, my preference being for PrimalScript which I find more helpful to an ASP coder than any of the latest MS products which seem to be very .NET-centric.
Also, where is a "MEMO" field from? Is this Access nomenclature, or maybe MySQL? I ask as such fields have been called TEXT or NTEXT fields in MS-SQL for a decade.
Remember to program into the language rather than program in it. Just because you're using a limited tool set doesn't mean you have to program like it's 1999.
I agree with JasonS about classes. It's true you can't do things like inheritance but you can easily fake it
Class Dog
Private Parent
Private Sub Class_Initialize()
Set Parent = New Animal
End Sub
Public Function Walk()
Walk = Parent.Walk
End Function
Public Function Bark()
Response.Write("Woof! Woof!")
End Function
End Class
In my projects an ASP page will have the following:
INC-APP-CommonIncludes.asp - This includes stuff like my general libraries (Database Access, file functions, etc) and sets up security and includes any configuration files (like connection strings, directory locations, etc) and common classes (User, Permission, etc) and is included in every page.
Modules/ModuleName/page.vb.asp - Kind of like a code behind page. Includes page specific BO, BLL and DAL classes and sets up the data required for the page/receives submitted form data, etc
Modules/ModuleName/Display/INC-DIS-Page.asp - Displays the data set up in page.vb.asp.
Echoing some ideas and adding a few of my own:
1) Best way to access the database would to abstract that away into a COM component of some sort that you access from VBScript.
2) If you really wanted to you could write the controller in VBScript and then access that in the page. It would resemble a Page Controller pattern and not a Front Controller that you would see in ASP.NET MVC or MonoRail
3) Why are you doing this to yourself? Most of the tooling required to do this kind of work isn't even available anymore.
AXE - Asp Xtreme Evolution is a MVC framework for ASP classic
There are some attempts at making test frameworks for asp:
aspUnit is good, but no longer maintained.
I saw a sample on how to make your own one a few months back.
The example used nUnit to call functions against the website for automatic testing.
I think i got it off here (my line is borked so I can't check)
On number 2, I think you have a few options...
1) You can use COM components developed in VB6 or the like to separate some of your business logic from your UI.
2) You can create classes in VBScript. There is no concept of inheritance and other more advanced features are missing from the implementation, but you can encapsulate logic in classes that helps reduce the spagehtti-ness of your app. Check out this: https://web.archive.org/web/20210505200200/http://www.4guysfromrolla.com/webtech/092399-1.shtml
I agree with #Cirieno, that the selected answer would not be wise to use in production code, for all of the reasons he mentions. That said, if you have just a little experience, this answer is a good starting point as to the basics.
In my ASP experience, I preferred to write my database access layer using VB, compiling down to a DLL and referencing the DLL via VBScript. Tough to debug directly through ASP, but it was a nice way to encapsulate all data access code away from the ASP code.
way way back in the day when VBScript/ASP were still ok
I worked in a utility company with a very mixed DB envrionment, I used to swear by this website: http://www.connectionstrings.com/
#michealpryor got it right
I've been stuck building on ASP, and I feel your pain.
1) The best way to query against SQL Server is with parameterized queries; this will help prevent against SQL injection attacks.
Tutorial (not my blog):
http://www.nomadpete.com/2007/03/23/classic-asp-which-is-still-alive-and-parametised-queries/
2) I haven't seen anything regarding MVC specifically geared towards ASP, but I'm definitely interested because it's something I'm having a tough time wrapping my head around. I generally try to at least contain things which are view-like and things which are controller-like in separate functions. I suppose you could possibly write code in separate files and then use server side includes to join them all back together.
3) You're probably coming from a language which has more functionality built in. At first, some things may appear to be missing, but it's often just a matter of writing a lot more lines of code than you're used to.
Also for database access I have a set of functions - GetSingleRecord, GetRecordset and UpdateDatabase which has similar function to what Michael mentions above

Resources