is static methods secure in asp.net - asp.net

heys guys,
i have a website, which contains lots of db work to display data on page, so i have created a VB class which is public, under App_Code.
Now i have all the methods and functions under that class are Shared(Static), also i have a connection variable which is also static.
Client complains, that sometime there appears an error on the page, one of those error is Field Name does not belong to table Table, i dont understand, about this, as this is very rare, if there is no field with name, then this should occur everytime, one of my colleague says that there should not be Shared methods or functions... is this correct..

There is no "security" problem with a static method. Your colleague is confused. Whether or not the code you wrote should be static or instance methods depends on what exactly it does. But having them as static methods is not "dangerous."
I suggest you track down the query that is causing the problem because the method being static is certainly not the issue.
As far as your connection goes, I would not recommend keeping it as a static variable. I assume this is a SqlConnection, or something similar. In that case, if you keep it as a static variable, it is possible for the following to occur:
Your connection is never closed, even after you're done using it.
You will have issues if you have multiple queries trying to use the connection at the same time.
So I recommend you use the following pattern to ensure your connections are only kept open as long as they are in use.
public void DoSomething()
{
//Doing some work that doesn't need a connection.
//Now ready to submit or fetch data from the database.
using (SqlConnection connection = new SqlConnection(...))
{
using (SqlCommand command = new SqlCommand(..., connection))
{
//Now, working with the connection and command.
}
}
//Done with the connection, doing more work now.
}
The using statement works with anything that is IDisposable. Your connection variable here will be automatically closed and destroyed at the closing bracket of the using statement. I recommend you use it for anything that you can. Streams, SqlConnections, Fonts, etc.

It sounds to me like you have a infrequently-used SQL statement that refers to a column that does not exist on a table.
For example - suppose you had SQL like so
SELECT Col4 FROM Table2
and Col4 was not a member of Table2. You would get the error you describe.
If you're building SQL dynamically (which is dodgey) you might run into this.
But I don't think it has anything to do with your method 'security.'

Related

(EF6) How can I specify a different ConnectionString to be used with Automatic Migrations?

I want to have two different SQL connections. One will leverage code-first automatic migrations to keep the database schema up-to-date. The other will do the typical website day-to-day.
I have both connection strings in my Web.config (one named "Migrator" and the other named "Agent").
How can I accomplish this?
Right now the schema is updated on the first read or write to the database, so I'm unsure where I can even set this...
In case anyone else was wondering the same thing, the way I ended up doing this was:
static MyDbContext()
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDbContext, MyProgram.Migrations.Configuration>("Migrator"));
}
public MyDbContext() : base("Agent")
{
}
In this way whenever "MyDbContext" is first initialized or accessed it initializes my database using the "Migrator" connection string.

How to change multiple connection string value using one method

I'm currently handling a .Net system that was developed in Linq for its data retrieval structure. This system was developed by other developers last time and I'm dealing a big problem now.
One of the bad practice (or i just not sure why must the developer do that) i found from this system is that, inside /AppData/DataContext/, there are alot of .dbml files and in the .designer.vb, for example Product.designer.vb file, consists of this piece of code:
Private Shared mappingSource As System.Data.Linq.Mapping.MappingSource = New AttributeMappingSource
Public Sub New()
MyBase.New(Global.System.Configuration.ConfigurationManager.ConnectionStrings("DBconstr").ConnectionString, mappingSource)
OnCreated
End Sub
My current major challenge is, I need to change to a new connection string name for all DBconstr and point to another database while keeping the current "Dbconstr" setting in web.config. There are over 400 lines in the entire system I need to find and replace if i have to do it manually. So I need advice if there is any way i can change all hard-coded connection string using one or few direct methods instead of changing all 400 plus lines manually?
I had thought about calling certain method in .Master page and override the value of .ConnectionString for all the child pages but not sure if this is possible.
Please advice. Thanks
You should have a look at this: http://blogs.msdn.com/b/webdev/archive/2009/05/04/web-deployment-web-config-transformation.aspx. It explains how to use web.config transformation. It basically allows modifying the value of a setting (ie. connection strings) depending on your solution/build configuration.
Modifying the configuration file "on the fly" is much easier than trying to modify it in the code.
You should also check these two answers I provided on the same topic:
How to have different web.config settings for my local machine? -
https://stackoverflow.com/a/19294499/375304
Applying web.config transformations locally - https://stackoverflow.com/a/19301084/375304

How or where to remove generated SQL from tableadapter code?

I've been developing an app which uses strongly typed datasets and stored procedures. I've just graduated and this was the method that was sold to us as the way to go. I'm starting to have severe doubts.
My client has advised me that he might change from SQL Server to MySQL. From what I've read it might be better to not use stored procedures as migrating could become more difficult. So anyhow I've just implemented a new table adapter query using the wizard and selected Use SQL Statements rather than Create new stored procedure.
My call to the query
Intranet.administratorsDataTable dt = taAdministrators.GetAdministrators();
now generates this error:
executereader requires an open and available connection. the
connection's current state is closed
I have no idea why this auto generated code doesn't have a connection and I'm hungover and in no shape to deal with this. I decided to just go back to the SP's for the moment so I can get some work done. This error is still being thrown (same table adapter, same method name but reconfigured to use a SP). All of my other DB calls work fine.
I'm assuming the generated SQL code is still floating around somewhere even though I changed the adapter to use SP's. Can someone tell me where it is so I can delete it?
On another note I'm really starting to think that using SqlConnection and SqlCommand manually is a much better option, as using these query 'Tools' are just way to much trouble when it comes to flexibility such as modifying database tables etc. Can any of you more experienced people tell me if that's correct or do you advocate using table adapters?
*Edit
it also throws these:
Invalid operation. The connection is closed.
and
There is already an open DataReader associated with this Command which must be closed first.
The solution was to go to the query properties in the tableAdapter and manually change the "Command Type" to StoredProcedure.
highlight the query > go to properties window > change the command type
Seem this didn't (or doesn't) get auto updated when I reconfigure the query.
if you provide some code, it would be better.
I think, you need to open the the connection.
SqlCommand Cmd= new SqlCommand();
Cmd.Open();
// then u can use Cmd.ExecuteReader();

How to rollback any transaction when doing test with phpUnit in symfony2

I'm testing the controllers using the crawler, but when I'm posting a form that doesn't generate any errors, it save the form in the database.
How can I prevent him to do so without changing the controller, and without testing something else.
Is there best practice about this kinds of test ?
I tried the rollback, but in the ControllerTest there is no more active transactions
You need to write your own test client class extending Symfony\Bundle\FrameworkBundle\Client.
It's because default client doesn't share connection object between requests (so you can't use transactions outside test client). If you extend test client you can handle transaction by your own.
In your client class you need make static connection object, and override method doRequest() to avoid creating new connection object every time but use our static one instead.
It's well described here:
http://alexandre-salome.fr/blog/Symfony2-Isolation-Of-Tests
When you have your own doRequest method all you need is handle transaction, so you wrap handle() method with begin and rollback. Your doRequest method could look sth like that:
protected function doRequest($request)
{
// here you need create your static connection object if it's doesn't exist yet
// and put it into service container as 'doctrine.dbal.default_connection'
(...)
self::$connection->beginTransaction();
$response = $this->kernel->handle($request);
self::$connection->rollback();
(...)
return $response
}
You can read the documentation of PHPUnit for database testing
http://www.phpunit.de/manual/3.6/en/database.html
You will need setup your database and teardown the changes you made.
If you think that the above is too complicated maybe you are interested in make a mockup of your database layer
http://www.phpunit.de/manual/3.6/en/test-doubles.html
Mockup is create a custom object based in the original object where put your own test controls. Probably in this case you are interested in mockup the Entity Manager of Doctrine

ASP.NET MVC: How to view query executed by SaveChanges (on the ADO.NET Entity Data Model)

When trying to add a few items to the database I'm getting this error:
UpdateException was unhandled by user code
An error occurred while updating the entries. See the InnerException for details.
The InnerException contains this:
{"Column count doesn't match value count at row 1"}
I can't see anything wrong with the objects I'm trying to add, all the required values are filled.
Is there any way of viewing the query that causes the problem?
The method's code, if required:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult LaadVerrichtingenIn() {
int[] intArray = Array.ConvertAll<String, int>(Request.Form["selectedObjects"].Split(','), new Converter<String, int>(Convert.ToInt32));
List<Verrichting> gekozenVerrichtingen = new List<Verrichting>();
foreach(int i in intArray){
base._entities.AddToVerrichtingSet(((Dictionary<int, Verrichting>)Session["ingelezenVerrichtingen"])[i]);
gekozenVerrichtingen.Add(((Dictionary<int, Verrichting>)Session["ingelezenVerrichtingen"])[i]);
}
Session["ingelezenVerrichtingen"] = null;
base._entities.SaveChanges(); //Exception occurs here
return View("IngeladenVerrichtingen");
}
base._entities is an ADO.NET Entity Data Model.
Thanks
I'm not sure if there's a 'neater' way to do this with the Entity Framework, but if you're using SQL Server then I'd generally use the SQL Server Profiler to read the queries being executed against the server. If you're using a different database then there may be an equivalent - in any case it would probably be helpful if you let us know.
If you're using MySQL > 5.0.37 it has new query profiler functionality - this should be able to show you the queries being sent.
SQL server profiler will work fine if you're using SQL Server. Within the Entity Framework, you can use the ToTraceString method.
I've just come across the same problem while inserting data using the Entity Framework and MySQL. My hunch is, since I'm using double values, that the decimal separator "," is being misinterpreted as a field separator. I upgraded to Connector version 6.1.0, but still no luck. Maybe this is also going on in your case.
Check out this bug report.
BTW, I found that the following line of code works around the problem:
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

Resources