Passing an ADO SQL connection ByVal - sql

I have an existing application written in Visual Basic. It's a web application build on ASP.NET and WCF that we use for reporting.
The result is a page that refreshes it's data every set amount of time. Usually after a day or so, this particular page crashes and the service must be reset, however other pages work. My working theory has to do with connections.
Connections to SQL Server are made through the class SQLDataAccess. This class creates a new connection when it is instantiated, the connection can be closed by calling a method on the class.
Most calls look like this:
Try
existingConnection.DataRequest.CommandText = "dbo.p_Select_Table"
DataAccessConnection.ExecuteDataSet()
Catch
Finally
If(existingConnection IsNot Nothign) Then
existingConnection.closeConnection()
End If
End Try
However two connections are initially made, then both connections are passed around more than this bug report was. They get passed ByVal.
Will this create new connections and neglect to close the old one?

When you pass any reference type by value, what you are passing is a reference. No object is copied. Passing a method parameter by value is basically just the same as assigning one variable to another. If the type is a value type then the object is copied and both variables contain different objects. For reference types, both variables refer to the same object. It's just like objects in the real world. If I lend you my car, does that mean there are two cars? No it doesn't, and it's the same when you pass a reference type object by value.

Related

Is it a good practice the attach an event related parameter to an object's model as a variable?

This is about an API handling the validation during saving an object. Which means that the front-end client sends a request to the API to a specific end point, then on the back-end the API creates a new object if the right conditions are meet.
Right now the regular method that we use is that the models has a ruleset for each fields and then the validation is invoked when the save function is invoked, but technically the validation is done right before the object is saved into the database.
Then during today's code review I came across a solution which I wasn't sure if it's a good practice or not. And it was about that the front-end must send a specific parameter to the API every time. This is because other APIs are using our API as well, and we needed to know if the request was sent as and API request or a browser request. If this parameter is present then we want to execute an extra validation function on a specific field.
(1)If I would have to implement it, then I would check the incoming parameter in the service handler or in the controller level, and if I got one, I would invoke the validation right away, and if it fails I would throw an error.
(2)The implementation I saw however adds an extra variable to the model, and sets the model variable when there is an incoming parameter, then validates only when the save function is invoked on the object(which first validates the ruleset defined on the object fields, then saves the object into the database)
So my problem with (2) is that the object now grown bigger with an extra variable that is only related to a specific event. So I would say it's better to implement (1). But (2) also has an advantage, and that is when you create the object on different end point by parsing the parameters, then the validation will work there as well, even if the developer forget to update the code there.
Now this may seems like a silly question because, why would I care about just 1 extra variable, but this is like a bedrock of something good or bad. So if I say this is ok, then from now on the models will start growing with extra variables that are only related to specific events, which I think should be handled on the controller/service handler level. On the other hand the code would be more reliable if it's not the developer who should remember all the 6712537 functionalities and keep them in mind when makes some changes somewhere. Let's say all the devs will get heart attack tomorrow from the excitement of an amazing discovery, and a new developer has to work on the project while he doesn't know about these small details, and then he has to change something on the code that is related to this functionality - so that new feature should be supported by this old one as well.
So my question is if is there any good practice on this, and what do you think what would be the best approach?
So I spent some time on thinking on the solution, and I think the best is to have an array of acceptable trigger variables in the model class. Then when the parameters are passed to the model on the controller level, then the loader function can be modified that it takes the trigger variables from the parameters and save it in the model's associative array variable that stores the trigger variables.
By default this array is empty, and it doesn't matter how much new variables are needed to be created, it will only contain the necessary ones when those are used.
Then of course the loader function needs to be modified in a way that it can filter out the non trigger variables as well as it is done for the regular fields, and there can be even a rule set of validation on the trigger variables if necessary.
So this solves the problem with overgrowing the object with unnecessary variables and the centralized validation part, because now the validation can be always done in the model instead of the controller.
And since the loader function is modified to store the trigger variables in the model's trigger variables array variable, the developer never has to remember that this functionality was created. Which is good, because in the future when he creates a new related function or end point that should handle object creation, he will not miss it to validate it against the old functionality, because the the loader function that he modified in the past like this will handle it for him.
It needs to be noted tho, that since the loader function doesn't differentiate between the parameters, and where to load them other then checking the names of the parameters with the filter functions, these parameter names should be identical from each other, otherwise a buggy functionality can be created accidentally. Like if you forget that a model attribute with the same name was used, then you can accidentally trigger an event that was programmed to be triggered if the trigger variable with the same name is present. However this can be solved by prefixing the trigger variables for example.

What error should I return when a COM object has been deleted but is being attempted to be referenced?

I have extended an API in C++ written on a legacy framework that is used via JavaScript/VB. There is an object that can create from another object. However, the coder can hold on to that object (it's exposed) and do operations on it. Also, the object can be deleted. Because of that last part, I need to keep the object around, even when it is deleted in case the developer tries to reference through that object, and if they attempt to do so, return an error (HRESULT), otherwise, it could cause a crash.
What is the best common HRESULT that I should use? I can't seem to find one that matches what I want.
The only one that I found the winerr.h file that might be relivant is ERROR_FLT_DELETING_OBJECT, but I don't think it is meant for that.
EDIT
Perhaps I should not use the word delete and replace it with instead detach. The object is to be detached from the main object, but is still lives on till the gc cleans up. However, if the user were to attempt to use this detached object, I want them to wake up to the fact that they have already detached it and that they shouldn't be playing with it any more.
EXAMPLE
var newObj = container.create_newObject();
newObj.doStuff();
container.doStuffWithNewObject(newObject);
container.RemoveObject(newObj);
newObj.doStuff(); // ERROR - see, still have reference and attempting to do stuff.
container.doStuffWithNewObject(newObject); // ERROR

declaring global variables in vb

The user clicks a button, a new form is generated where the user enters his/her password? How can I keep an in-memory copy of the username?
For instance in web forms, I can just use Session ("User"). How can I replicate this with winforms?
Thanks
You could use a static (Shared in VB .NET) object
Example
Public Class SessionInformation
Public Shared Property UserPassword As String
End Class
You can then access this by calling
SessionInformation.UserPassword
Since there seems to be some concerns revolving around whether or not this is a valid implementation I will explain why this is not the best idea.
This creates a single instance of SessionInformation which means that if it is changed anywhere in the program it affects the rest of the program.
Maintaining object persistence can be difficult if you aren't using a database (SQL, Access, a file, etc...) to maintain an out of memory copy of the object that you want to retrieve at a later date. The easiest way to implement this would be to use a SQLCE database that live in your application folder and using standard T-SQL to store the information that you need. However in the case of a password this may be non-ideal due to security issues.
Or the better way for logging in and out user would be to make use of the System.Security.Principal Namespace to create a user for your application.
You don’t need an equivalent to the Session object in web applications. Sessions are only needed because web applications actually have to access variables across process boundaries (= a session in a web application encompasses multiple requests of a user to a web server, and historically each request started a new application!).
In a “normal” application, this isn’t the case – any non-local variable will do. In your particular case, it would make sense for the password form to have a property that contains the username. The user then enters their username and password and the caller of this password form can retrieve the username:
' The caller looks something like this:
Dim pw As New PasswordForm()
pw.ShowDialog() ' Display the dialog, and wait until the user has dismissed it.
Dim theUsername = pw.Username
Inside the PasswordForm, there is something like this:
Public ReadOnly Property Username() As String
Get
' Return the value of the username textbox field.
Return UsernameInput.Text
End Get
End Property
We could get more sophisticated but this will do.
If you need to reuse the username across the application, chances are that you also need to share other information about the user (what are they working on? …). This, in short, is the state of the application and there is usually an object which represents that state. This would be the right place to store the username as well.
If your application only has one other form (the “main dialog”), then just use a private variable inside that form to store the username. No need for a global variable.
Just have a public variable on the forms, never unload the form, and get the data from that form using formname.variablename (define it as public at form level).
This even can be achieved with controls if you set them to public.
BEFORE THE FLAMES: this solves OP problems, whenever if this is optimal, good or anything else, is another problem.

Sharing Non-Persistent Objects Between Contexts in Core Data?

I was wondering if there is a way to share an NSManagedObject between two or more NSManagedObjectContext objects running in the same thread.
I have the following problem: I have one main context shared through all my code in the application and several different contexts that are created for each remote fetch request that I issue. (I created a custom class that fetches remotely and inserts all the objects found in the server in his own NSManagedObjectContext). Those fetch requests may run simultaneously since they use NSURLConnection objects that may end at different times. If the same remote object gets fetched by different connections, I will end up with duplicates at the moment of saving and merging the context with the main one. (That is, objects that have the same remote ID but a different objectID).
One possible solution would be to save (and so persist) every object as soon as it is created but I can't do that because it may have some relationships that may still have not been filled and won't validate during the save operation.
I'm really looking forward to a method that allows you to share the same non-persistent instance of an object between context. If anybody has encountered this issue and came up with a solution, I would be pleased to know!
Context cannot communicate between each other save through their stores. However, you can insert a managed object with a nil managed object context and it will be independent (albeit without relationships) of any context. You could pass that independent managed object around however you wished and insert it into a context when you needed to persist it. This is dangerous but possible.
However, if you're not running each connection on a separate thread then you don't gain anything by having multiple context. Each connection object will activate its delegate in sequence on the main thread. In this case, your easiest solution would be to use the same delegate for all the connections and let the delegate handle the insertions into a single context. To prevent duplication, just do a fetch on the remoteID and see if you get back an extant object before inserting a new object for that remoteID.
I don't think what you want to do is possible. I mean if you want to share changes between different contexts, you got to use notifications and merge it whenever did save or did change occur. But in your case, I'd say just use 1 context and save in the end. Or a less elegant way: save all the remote ids temporary in your app and check before inserting new ones. In this case, you can continue use multiple contexts and save after each didfinishloading.

VB.net: Any problems using a Shared method for getting a db connection?

I have a utility class that creates & returns a db connection:
Public Shared Function GetConnection() as OracleConnection
dim c as New OracleConnection()
... set connection string...
c.Open()
Return c
End Function
Is there any risk of concurrent calls returning the same connection? The connection string enables pooling.
Since you are returning a new connection each time you will not have any concurrency issues. If you were using a Shared method to return multiple references to the same instance, that could be a problem but that is not what you are doing here.
You are safe to use this method in this way as long as you are always returning a new instance of your database connection object each time. Any connection pooling will also work the same as it always would - you won't need to worry about your Shared method usage created problems there either.
Forget the concurrent calls issue for a moment. If there is any connection pooling going on you will absolutely have reuse of the same underlying database connections, even if they don't use the same object.
This is generally a desirable thing as opening a connection to the DB can be an expensive operation.
Are you worried about closing the connection object out from under another caller? If so, as another response pointed out, I think you are safe with the code you provided.
I don't think so.
Since c is a local variable ("stack variable") and not a static one every call has it's own instance of c.
Next you create a new object (the connection) and return this.
Shouldn't be any problem with concurrency, because each call is a new connection.
I might make one change, though: make the method private.
This will force you to put all your data access code in one class and push to create a nice, separate data access layer. At very least make it internal so that your data access layer is confined to a single assembly (that's separate from the rest of your code).