Using Statement SqlConnection closed? - sqlconnection

My connection is instantiated when I instantiate this.database like below, when I call ExecuteDataReader on this.database I am using try, catch... it opens the connection executes reader and returns a SqlDataReader object.
With all that said will the using statement below close my connection that was instantiated in another class without a using statement and no explicit call to dispose or close?
using (IDataReader reader = this.database.ExecuteDataReader(storedProcedure))
{
if (reader.Read())
{
blah....
}
}
Thanks

As I know Using is just a short cut for the following, and it works only if the underlaying object is disposable...
try
{
connection = new [...]
}
catch
{
}
finally
{
connection.dispose()
}

Related

WPF : Update View Model when DB Changes (Concurrency Issue)

I'm currently working on WPF app that is architectured as follows:
MVVM
Entity Framwork 4 (with LINQ).
WCF service that pool Database to get data (Oracle).
I Make my WFC call in my View Model Class and put my data in an ObsevableCollections.
Db Changes occurs from a another app.
So my app does not do any write actions on the DB what-so-ever (Zéro), it only reads data and displays it on the UI.
How can I make my app to be quickly responsive to DB changes, I read about the following solutions but I'm confused and don't know what to use:
Pooling DB every n seconds with a DispatcherTimer (seems to be too much work cause data changes every millisecond)
SqlDependency, searched all over the internet but didn't find a proper implementation with EF.
As I said, db changes every millisecond (financial data from other sources),
How can resolve this?
Thank you.
i tried the code bellow and it seemed to be working okay for the moment (but i still have some doubts about that infinit loop), let me know what you thing :
public class MyViewModel
{
BackgroundWorker _bgWorker ;
//some props
//some funcs
protected internal MyViewModel(Session session)
{
Session = session;
RefreshData();
}
protected void RefreshData()
{
try
{
_bgWorker = new BackgroundWorker
{
WorkerReportsProgress = true,
WorkerSupportsCancellation = true
};
_bgWorker.DoWork += bgDoWork;
if (!_bgWorker.IsBusy)
{
_bgWorker.RunWorkerAsync();
}
}
catch (Exception)
{
_bgWorker.CancelAsync();
}
}
private void bgDoWork(object sender, DoWorkEventArgs e)
{
var worker = (BackgroundWorker)sender;
while (!worker.CancellationPending)
{
//Thread.Sleep(1000); should i keep this or not ?
Proxy(); // WCF calls
}
}
}

Create database with data

I'm trying to create my database (code first) and I want to add some data in it when it's created.
public class InitializerWithData : CreateDatabaseIfNotExists<DatabaseContext>
{
protected override void Seed(DatabaseContext ctx)
{
GroupType gt = new GroupType() { Name = "RNC" };
//save
ctx.GroupType.Add(gt);
ctx.SaveChanges();
}
}
public DatabaseContext()
{
Database.SetInitializer<DatabaseContext>(new InitializerWithData());
Database.CreateIfNotExists();
}
As you can see I wrote my custom initializer but the code inside it is never fired though the database does get created.
So how do I solve this?
When you call Database.CreateIfNotExists(), it doesn't trigger the InitializeDatabase of the initializer. Basically it has separated implementation than the initializer.
If you want the Seed method to be fired. You need to execute a code that causes EF to send a query to the database.
First remove this line.
Database.CreateIfNotExists();
Then just execute a query, the least you could have is something like.
using(var db = new DatabaseContext())
{
db.Set<GroupType>().Any();
}
This code will create the database if it doesn't exist and execute the Seed method.

Handles SQL Exception from Entity Framework

In my sql stored procedure, i do some insertion and updating which in some scenarios throws Primary Key or unique key violation.
When I try to execute this procedure from ADO.net, .net application also throws that exception and let me know that something wrong had happen.
But when I try to execute this procedure from EF, it just executes. Neither it show anything nor update anything.
How should I handle or notify user that something wrong had happen?
Ado.Net code is
SqlConnection sqlConnection = new SqlConnection(#"data source=database01; database=test; user id=test; password=test;");
SqlCommand cmd = new SqlCommand("[uspUpdateTest]", sqlConnection);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("RunID", RunID);
cmd.Parameters.AddWithValue("RunCode", RunCode);
sqlConnection.Open();
var str = cmd.ExecuteNonQuery();
Entity Framework Code is
TestEntities context = new TestEntities();
var str=context.UpdateRun(RunID, RunCode);
I am very much sure, you must set some return type(dummy) in your function import. It makes sense most of the time, because if you don't do so, your method name does not appear in intellisense and you will no be able to access it using context.MethodName.
My suggestion for you is, remove the return type of your Function Import and set it to none. Execute your method using ExecuteFunction method of context.
Context.ExecuteFunction(FunctionName,Parameters). It'll definitely throws the exception.
First of all, make sure you're throwing an Exception in your stored procedure which we can catch in our C# code. See - http://social.msdn.microsoft.com/forums/en-US/adodotnetdataproviders/thread/efea444e-6fca-4e29-b100-6f0c5ff64e59 - quote:
If you want RAISERROR to throw a SqlException, you need to set its
severity above 10. Errors with a severity of 10 and below are
informational, and thus don't throw exceptions.
I'll also show you the following code. I have been using this in my MVC controllers when getting data from my service layer using Entity Framework:
try
{
try
{
//Entity Framework/Data operations that could throw the data exception
//...
} catch (DataException dex) //see http://msdn.microsoft.com/en-us/library/system.data.dataexception.aspx
{
//Specifically handle the DataException
//...
}
}
catch (Exception e)
{
//do something (logging?) for the generic exception
throw e;
}
You can put a breakpoint on the last catch if the first catch doesn't trigger to see Exception-type/inner-exception of 'e' and go from there. It is useful to put a breakpoint on the generic exception, as it let's me know when I haven't handled something.
We can use the following way for sql raised error exception from entity framework:
Let's say, we have DBContext. So that
var connection= (SqlConnection)db.Database.Connection;
if (connection != null && connection.State == ConnectionState.Closed)
{
connection.Open();
}
SqlCommand com = new SqlCommand("spname", connection);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add(new SqlParameter("#parameter", parameter));
try
{
com.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex.message;
} `
The question here gives quite a nice summary of catching and handling the exceptions gracefully. You have several options after that for rolling back etc.

How to hide the output of a console view?

I'm writing an Eclipse plug-in in which the user can interact with another process via the Console view (in this case, an interpreter), for example, evaluate expressions and so on.
Sometimes the program needs to ask the interpreter for certain values. These interactions however, shouldn't be shown in the console view to the user.
I have following instances:
private IProcess process;
private ILaunch launch;
private IStreamsProxy proxy;
the queries my program do are made via adding an IStreamListener to the proxy:
proxy.getOutputStreamMonitor().addListener(new IStreamListener(){
#Override
public void streamAppended(String response, IStreamMonitor arg1) {
doSomeStuffWiththeRepsonse(response);
}
});
while the listener is listening to the OutputStreamMonitor of the proxy, I don't want the response to pop up in the console view of the plugin.
How can I do that?
Okay, here is how I did it.
The launch system of Eclipse works as follows:
1. Implement a ILaunchConfigurationDelegate, the only method in this interface is launch, which recieves an ILaunchConfiguration, a mode, an ILaunch and an IProgressMonitor.
In my program, launch starts an inferiorProcess using DebugPlugin.exec() using a commandline argument. Then a new Process is created by calling DebugPlugin.newProcess() with the ILaunch, the inferiorProcess, the name for the interpreter and some attributes.
This method creates a new RuntimeProcess and adds it to the ILaunch and vice versa.
2. Define a LaunchConfigurationType by using the extension point org.eclipse.debug.core.launchConfigurationTypes and add it to the plugin.xml:
<extension
point="org.eclipse.debug.core.launchConfigurationTypes">
<launchConfigurationType
delegate="myplugin.MyLaunchConfigurationDelegate" (1)
id="myplugin.myExternalProgram" (2)
modes="run" (3)
name="MyExternalProgram" (4)
public="false"> (5)
</launchConfigurationType>
</extension>
The extension point gives the exact path to the ILaunchConfigurationDelegate class created as above (1) and an unqiue identifier (2) to retrieve the instance of ILaunchConfigurationType from the LaunchManager used to launch the program. (3) defines the modes it can run as, run and debug. The name (4) is later shown in the top bar of the console view. If you only want to access and launch your external program programmatically in your plug-in (and not via the Run drop-down menu) (5) must be set to false.
3. Create a class that stores the Instances of IProcess, ILaunch and IStreamsProxy and which calls apropiate methods to start the process and to write onto the streamsproxy. A method for starting the process could look like this:
// is the process already running?
public boolean isRunning() {
boolean result = false;
try {
if (this.process != null) {
result = true;
this.process.getExitValue();
result = false;
}
}
catch (DebugException exception) {
}
return result;
}
// start the process
public void start() {
try {
if (!isRunning()) {
// get the ILaunchConfigurationType from the platform
ILaunchConfigurationType configType = DebugPlugin.getDefault().getLaunchManager().getLaunchConfigurationType(myplugin.myExternalProgram);
// the ILaunchConfigurationType can't be changed or worked with, so get a WorkingCopy
ILaunchConfigurationWorkingCopy copy = configType.newInstance(null, "myExternalProgram");
this.launch = copy.launch(ILaunchManager.RUN_MODE, new NullProgressMonitor());
IProcess[] processes = this.launch.getProcesses();
if (processes.length > 0) {
// get the IProcess instance from the launch
this.process = this.launch.getProcesses()[0];
// get the streamsproxy from the process
this.proxy = this.process.getStreamsProxy();
}
}
}
catch (CoreException exception) {
}
if (isRunning())
// bring up the console and show it in the workbench
showConsole();
}
public void showConsole() {
if (this.process != null && this.process.getLaunch() != null) {
IConsole console = DebugUITools.getConsole(this.process);
ConsolePlugin.getDefault().getConsoleManager().showConsoleView(console);
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
IViewPart view = page.findView("org.eclipse.ui.console.ConsoleView");
if (view != null)
view.setFocus();
}
}
Now to the initial problem of the question
The IStreamsListener of the console view, which listens to the OutputStreamMonitor of the IStreamsProxy could not be retrieved and thus not being stopped of listening. Prints to the console could not be prevented. OutputStreamMonitor doesn't provide methods to get the current listeners. It is not possible to just subclass it and override/add some methods, because the important fields and methods are private.
http://www.java2s.com/Open-Source/Java-Document/IDE-Eclipse/debug/org/eclipse/debug/internal/core/OutputStreamMonitor.java.htm
Just copy the code and add a get-method for the fListeners field and change some method modifiers to public.
In order to get your own OutputStreamMonitor into the system, you need to create your own IStreamsProxy. Again only subclassing wont work, you need to copy the code again and make some changes.
http://www.java2s.com/Open-Source/Java-Document/IDE-Eclipse/debug/org/eclipse/debug/internal/core/StreamsProxy.java.htm
Important:
public class MyStreamsProxy implements IStreamsProxy, IStreamsProxy2 {
/**
* The monitor for the output stream (connected to standard out of the process)
*/
private MyOutputStreamMonitor fOutputMonitor;
/**
* The monitor for the error stream (connected to standard error of the process)
*/
private MyOutputStreamMonitor fErrorMonitor;
(...)
public MyStreamsProxy(Process process) {
if (process == null) {
return;
}
fOutputMonitor = new MyOutputStreamMonitor(process
.getInputStream());
fErrorMonitor = new MyOutputStreamMonitor(process
.getErrorStream());
fInputMonitor = new InputStreamMonitor(process
.getOutputStream());
fOutputMonitor.startMonitoring();
fErrorMonitor.startMonitoring();
fInputMonitor.startMonitoring();
}
The only thing remaining is providing your own IProcess that uses your IStreamsProxy. This time subclassing RuntimeProcess and overriding the method createStreamsProxy() is enough:
public class MyProcess extends RuntimeProcess {
public MyProcess(ILaunch launch, Process process, String name,
Map attributes) {
super(launch, process, name, attributes);
}
#Override
protected IStreamsProxy createStreamsProxy() {
String encoding = getLaunch().getAttribute(DebugPlugin.ATTR_CONSOLE_ENCODING);
return new MyStreamsProxy(getSystemProcess());
}
}
MyProcess is integrated by creating a new instance of it in the launch method in the ILaunchConfigurationDelegate instead of using DebugPlugin.newProcess().
Now it is possible to hide and expose the output of the console view.
/**
* Storage field for the console listener
*/
private IStreamListener oldListener;
/**
* Hides the output coming from the process so the user doesn't see it.
*/
protected void hideConsoleOutput() {
MyOutputStreamMonitor out
= (MyOutputStreamMonitor) this.process.getStreamsProxy().getOutputStreamMonitor();
List<IStreamListener> listeners = out.getListeners();
// the console listener
this.oldListener = listeners.get(0);
out.removeListener(this.oldListener);
}
/**
* Reverts the changes made by hideConsoleOutput() so the user sees the response from the process again.
*/
protected void exposeConsoleOutput() {
MyOutputStreamMonitor out
= (MyOutputStreamMonitor) this.process.getStreamsProxy().getOutputStreamMonitor();
out.addListener(oldListener);
this.oldListener = null;
}
The hide and expose methods have to be called before any other listeners are added. There might be a better solution, however, this works.
Previous answer does the trick and I was going with something similar first after hours of trying to solve this. Finally I ended up doing something a bit simpler, but also somewhat nastier...basically:
...
ILaunch launch = launcconf.launch(
ILaunchManager.RUN_MODE, monitor);
DebugUIPlugin.getDefault().
getProcessConsoleManager().launchRemoved(launch);
...
So, I'm basically telling the console manager listener methods that this lauch has already been removed and it removes the console. Seems to do the trick for me atleast.
i don't want the response to pop up in the console view of the plugin. how can i do that?
Well since that is your actual concern, then just toggle the button on the console view called "Show console when standard output changes". Way more of a simpler approach than all of this, and it can be turned back on/off.

ado when does it dispose? what happens when in the using i use a class member

I have a porogram where I use m_sqlConnection as a class member
does
using (m_sqlConnection = new SqlConnection(sr_ConnectionString))
{
m_sqlConnection.Open();
} //dispose
similar to
using ( SqlConnection m_sqlConnection = new SqlConnection(sr_ConnectionString))
{
m_sqlConnection.Open();
}//dispose
Both will dispose the new SqlConnection.
In the second case, trying to call any method on m_sqlConnection (if not re-assigned) will throw an exception.
See using Statement on MSDN. There are several examples, including these cases.