How do I close an OracleConnection in .NET - oracle

Say I have these two objects:
OracleConnection connection = new OracleConnection(connectionString);
OracleCommand command = new OracleCommand(sql, connection);
To close the connection or Oracle, do I have to call command.Dispose(), connection.Dispose(), or both?
Is this good enough:
using(connection)
{
OracleDataReader reader = cmd.ExecuteReader();
// whatever...
}

using (OracleConnection connection = new OracleConnection(connectionString))
{
using (OracleCommand command = new OracleCommand(sql, connection))
{
using (OracleDataReader reader = cmd.ExecuteReader())
{
}
}
}
If it implements IDisposable, and if you create it, then put it in a using block.

Both answers are pretty much on target. You always want to call .Dispose() on any IDisposeable object. By wrapping in a "using" you tall the compiler to always impliment a try/finialy block for you.
1 point of note, if you want to avoid the nesting, you can write the same code like this:
using (OracleConnection connection = new OracleConnection(connectionString))
using (OracleCommand command = new OracleCommand(sql, connection))
using (OracleDataReader reader = cmd.ExecuteReader())
{
// do something here
}

This is good enough. using statement will wrap the dispose statement, so even if the exception is thrown, you are safe, it's my preferred way to dispose the resource.
using(OracleConnection connection = new OracleConnection(connectionString); )
{
//Create a command object
using(OracleCommand command = new OracleCommand(sql, connection))
{
using(OracleDataReader reader = cmd.ExecuteReader())
{
}
}
// whatever...
}
I think by use "using", you are ask the compiler to inject a try ... finally block , and in finally block, it will close the disposable object for you.

using will ensure your connection is closed. You could also pass in CommandBehavior.CloseConnection to your command's ExecuteReader method to close it before Dispose is called.

Related

AVCapturePhotoSettings not accepting accept NSDictionary element

not sure what I am doing wrong, I wanna create a simple custom camera, I'm creating the AVCapturePhotoOutput attaching it to AVCaptureSession, then creating AVCapturePhotoSettings with minimum settings to make taking a picture work, see code below.
I get exception kCVPixelBufferPixelFormatTypeKey is not being define but it is indeed in the NSDictionary I am passing.
I need some light here, thanks
public void TakePicture()
{
var output = new AVCapturePhotoOutput();
_captureSession.AddOutput(output);
var settings = AVCapturePhotoSettings.Create();
var previewPixelType = settings.AvailablePreviewPhotoPixelFormatTypes.First();
var keys = new[]
{
new NSString("kCVPixelBufferPixelFormatTypeKey"),
new NSString("kCVPixelBufferWidthKey"),
new NSString("kCVPixelBufferHeightKey"),
};
var objects = new NSObject[]
{
// don't have to be strings... can be any NSObject.
previewPixelType,
new NSString("160"),
new NSString("160")
};
var dicionary = new NSDictionary<NSString, NSObject>(keys, objects);
settings.PreviewPhotoFormat = dicionary;
output.CapturePhoto(settings,this);
}
It is because kCVPixelBufferPixelFormatTypeKey is not available in Xamarin.
We should use CVPixelBuffer.PixelFormatTypeKey here . It will be convert to kCVPixelBufferPixelFormatTypeKey automatically when compiling.
The same reason for kCVPixelBufferWidthKey and kCVPixelBufferHeightKey , the api is CVPixelBuffer.WidthKey and CVPixelBuffer.HeightKey in Xamarin.iOS.

How to get IEditorOperations from IVsTextView?

I'm developing my first Visual Studio (2015 Community) Command Menu and I'm trying to get access to IEditorOperations to delete text, send backspace etc. but I'm not sure how to. I can do:
var Service = Provider.GetService(typeof(IEditorOperationsFactoryService)) as IEditorOperationsFactoryService;
Service.GetEditorOperations(???);
I'm not sure what to pass in the ??? since I don't have access to an ITextView instead what I have is a IVsTExtView via:
IVsTextView View;
IVsTextManager Manager = (IVsTextManager)ServiceProvider.GetService(typeof(SVsTextManager));
int MustHaveFocus = 1;
Manager.GetActiveView(MustHaveFocus, null, out View);
When creating the Command Menu, VS generates a template for me with a private ctor creating the command service, binding it to the command set id etc. An overridden Initialize method, and a bunch of properties.
Any ideas?
EDIT: After help from Sergey, I managed to get a bit further. But now I get a null when I try to get the IEditorOperationsFactoryService, all the other values are valid.
static IEditorOperations GetEditorService(IServiceProvider Provider, IVsTextView VsView)
{
IEditorOperations Result;
try
{
var Model = (IComponentModel)Provider.GetService(typeof(SComponentModel));
var Editor = (IEditorOperationsFactoryService)Provider.GetService(typeof(IEditorOperationsFactoryService)); // returns null
var Adaptor = Model.GetService<IVsEditorAdaptersFactoryService>();
IWpfTextView TextView = Adaptor.GetWpfTextView(VsView);
Result = Editor.GetEditorOperations(TextView);
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show(e.ToString());
Result = null;
}
return (Result);
}
You can get IEditorOperationsFactoryService instance from variable named Model, like this:
var Model = (IComponentModel)this.ServiceProvider.GetService(typeof(SComponentModel));
var Editor = (IEditorOperationsFactoryService)Model.GetService<IEditorOperationsFactoryService>();
You can get IWpfTextView (that implements ITextView) from IVsTextView using:
IVsTextView textView = ...;
IWpfTextView v = GetEditorAdaptersFactoryService().GetWpfTextView(textView);
private Microsoft.VisualStudio.Editor.IVsEditorAdaptersFactoryService GetEditorAdaptersFactoryService()
{
Microsoft.VisualStudio.ComponentModelHost.IComponentModel componentModel =
(Microsoft.VisualStudio.ComponentModelHost.IComponentModel)serviceProvider.GetService(
typeof(Microsoft.VisualStudio.ComponentModelHost.SComponentModel));
return componentModel.GetService<Microsoft.VisualStudio.Editor.IVsEditorAdaptersFactoryService>();
}

Do not dispose objects multiple times

Can't seem to see why FXCop is complaining that I am disposing the memoryStream object more than once. As near as I can tell, I'm only disposing of it in the finally block.
Full error message is:
CA2202 Do not dispose objects multiple times Object 'memoryStream' can be disposed more than once in method 'MessageTransform.GetEnvelope(Message)'. To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.: Lines: 48 Api MessageTransform.cs 48
var memoryStream = new MemoryStream();
try
{
var messageBuffer = message.CreateBufferedCopy(int.MaxValue);
var xPathNavigator = messageBuffer.CreateNavigator();
var xmlWriter = XmlWriter.Create(memoryStream);
xPathNavigator.WriteSubtree(xmlWriter);
xmlWriter.Flush();
xmlWriter.Close();
memoryStream.Position = 0;
var xdoc = XDocument.Load(XmlReader.Create(memoryStream));
return xdoc;
}
catch (ApplicationException e)
{
Console.WriteLine(e.Message);
return null;
}
finally
{
memoryStream.Dispose();
}
If I wrap the same code in a using block I get the same error.
using (var memoryStream = new MemoryStream())
{
var messageBuffer = message.CreateBufferedCopy(int.MaxValue);
var xPathNavigator = messageBuffer.CreateNavigator();
var xmlWriter = XmlWriter.Create(memoryStream);
xPathNavigator.WriteSubtree(xmlWriter);
xmlWriter.Flush();
xmlWriter.Close();
memoryStream.Position = 0;
var xdoc = XDocument.Load(XmlReader.Create(memoryStream));
return xdoc;
}
Is this just an issue with a hyperactive FXCop or does using a using block or .Dispose() somehow not apply to a System.IO.MemoryStream?
The XmlWriter can dispose the stream from its Close method, which is what the rule is picking up. However, this behavior is conditional and should not be invoked in an XmlWriter created for a stream in the way you describe.
As Nicole described, the XmlWriters' Close can dispose the Memorystream-object, which is causing the error to be raised.
I do want to point out that a using statement and try-finallystatement are the exact same thing. The compiler translates using statements into a tryblock with your execution and a Dispose() in the finallyblock.

how to implement async method using Task Parallel Library for I/O operations

I found that for expensive IO bound operation I can use TaskCompletionSource
as shown here http://msdn.microsoft.com/en-us/library/hh873177.aspx#workloads
But the example shown is only waiting for some time and return DateTime.
public static Task<DateTimeOffset> Delay(int millisecondsTimeout)
{
TaskCompletionSource<DateTimeOffset> tcs = null;
Timer timer = null;
timer = new Timer(delegate
{
timer.Dispose();
tcs.TrySetResult(DateTimeOffset.UtcNow);
}, null, Timeout.Infinite, Timeout.Infinite);
tcs = new TaskCompletionSource<DateTimeOffset>(timer);
timer.Change(millisecondsTimeout, Timeout.Infinite);
return tcs.Task;
}
Above code waits for timeout. I have a database call which I want to fire in the above way, but little confused in how to write it:
using (var context = new srdb_sr2_context())
{
return context.GetData("100", "a2acfid");
}
I wrote the function as below, but not sure if this is correct way of doing it:
TaskCompletionSource<IList<InstructorsOut>> tcs = null;
Timer timer = null;
timer = new Timer(delegate
{
timer.Dispose();
//prepare for expensive data call
using (var context = new srdb_sr2_context())
{
var output = context.GetData("100", "a2acfid");
//set the result
tcs.TrySetResult(output);
}
}, null, Timeout.Infinite, Timeout.Infinite);
tcs = new TaskCompletionSource<IList<InstructorsOut>>(timer);
timer.Change(0, Timeout.Infinite);
return tcs.Task;
Any help would be appreciated.
Your code doesn't make much sense to me. Timer is useful if you want to execute the code after some time, but that's not what you need here.
If you want to execute an operation on a background thread, you can use Task.Run():
Task<IList<InstructorsOut>> GetDataBackground()
{
return Task.Run(() =>
{
using (var context = new srdb_sr2_context())
{
return context.GetData("100", "a2acfid");
}
});
}
Using a background thread this way can be useful in UI apps, where you don't want to block the UI thread. But if you have something like ASP.NET application, this won't actually give you any performance or scalability improvements. For that, the GetData() method would have to be made truly asynchronous.

Unable to func-eval using Mdbg due to "code is optimized" exception

We are using MdbgCore.dll to evaluate a property off a parameter on a thread callstack.
To do this, we are performing a func-eval.
Unfortunately, all our attempts to perform the func-eval are failing with CORDBG_E_ILLEGAL_IN_OPTIMIZED_CODE, which seems to be due to the thread being used for the func-eval not being in a GC-safe point.
This is documented here: http://blogs.msdn.com/b/jmstall/archive/2005/11/15/funceval-rules.aspx.
We tried scanning all threads in the process to find a thread that is in a GC-safe point, but they all appear to have UserState marked with USER_UNSAFE_POINT.
There is very scarce documentation on the subject, and we are pulling our hair out trying to figure out if there is a way to get a thread in a GC-safe point so we can do the func-eval. We would consider anything that allows us to deterministically break into the process with a thread to do the func-eval with.
Disclaimer: we are trying to evaluate a method on a class that resides in an optimized assembly, so not sure if this is maybe also causing an issue.
The sample code follows:
if (argument.TypeName.EndsWith(
"WorkerRequest", StringComparison.OrdinalIgnoreCase)
&& !argument.IsNull)
{
try
{
// Invoke the "GetUriPath()" function to obtain the URI
string functionName = "System.Web.HttpWorkerRequest.GetUriPath";
MDbgFunction func = debugger.Processes.Active.ResolveFunctionNameFromScope(
functionName,
thread.CorThread.AppDomain
);
if (null == func)
{
throw new InvalidOperationException(
String.Format("Could not resolve {0}", functionName));
}
// Setup the eval
CorEval eval = threadForFuncEvals.CorThread.CreateEval();
// Setup the function parameters
List<CorValue> values = new List<CorValue>();
// Add the worker request "this" pointer
values.Add(
argument.CorValue
);
// resume the thread being used to do the func-eval
threadForFuncEvals.CorThread.DebugState = CorDebugThreadState.THREAD_RUN;
// Queue the function for execution
// EXCEPTION THROWN BELOW
// EXCEPTION THROWN BELOW
// EXCEPTION THROWN BELOW
eval.CallFunction(func.CorFunction, values.ToArray());
// BUGBUG: Should we pause all other threads to prevent them from moving?
// Continue the process to execute the function
if (!proc.Go().WaitOne(settings.BreakTimeout))
{
throw new InvalidOperationException("Timeout while evaluating function");
}
// get the returned string
var result = eval.Result;
if (result != null)
{
MDbgValue mv = new MDbgValue(proc, result);
string returnedValue = mv.GetStringValue(false);
threadInfo.Url = returnedValue;
}
}
catch (Exception e)
{
// BUGBUG: Ignoring exception
}
finally
{
// suspend the thread again
if (threadForFuncEvals != null)
{
threadForFuncEvals.CorThread.DebugState =
CorDebugThreadState.THREAD_SUSPEND;
}
}
}
Microsoft / Mdbg team, can you help?
Best,
Mike
Is this something to do with JIT optimization?
In my program, I turn JIT optimization off (for technical reasons, I think you can only do this with CreateProcess() and not using Attach()).
proc = m_Debugger.CreateProcess(ProcessName, ProcessArgs, DebugModeFlag.Default, DebugEngineUtils.GetAssemblyRuntimeVersion(ProcessName,DefaultNetVersion));
if (proc!=null) proc.CorProcess.OnCreateProcess += new Microsoft.Samples.Debugging.CorDebug.CorProcessEventHandler(CorProcess_OnCreateProcess);
if (proc!=null) proc.CorProcess.OnModuleLoad += new Microsoft.Samples.Debugging.CorDebug.CorModuleEventHandler(CorProcess_OnModuleLoad);
void CorProcess_OnModuleLoad(object sender, Microsoft.Samples.Debugging.CorDebug.CorModuleEventArgs e)
{
e.Module.JITCompilerFlags = Microsoft.Samples.Debugging.CorDebug.CorDebugJITCompilerFlags.CORDEBUG_JIT_DISABLE_OPTIMIZATION;
}
void CorProcess_OnCreateProcess(object sender, Microsoft.Samples.Debugging.CorDebug.CorProcessEventArgs e)
{
//try to disable optimization
((Microsoft.Samples.Debugging.CorDebug.CorProcess)sender).DesiredNGENCompilerFlags = Microsoft.Samples.Debugging.CorDebug.CorDebugJITCompilerFlags.CORDEBUG_JIT_DISABLE_OPTIMIZATION;
}

Resources