SMO Server connection not closed - database-connection

I'm writing a C# application that upgrades client machines from one application version to another. The first step is to create a backup of a SQL database. I'm doing this using SMO and it works fine. Next I uninstall a windows service. Then I try to rename the database that I backed up, again, using SMO. This fails because it says it can't gain exclusive access to the database. When I look at the activity monitor, I can see that there are two connections to the database I'm trying to rename. One connection is the one I'm using to try to rename the database, the other is the one I used to backup the database. It's status is sleeping but I'm assuming this is why I can't get exclusive access to rename the database. I was kind of surprised to find the SMO objects didn't implement IDisposable. I tried setting my Server object reference to null incase garbage collection might help, but that didn't work. The connections stay there until I quit the application.
So I have a couple of questions
How do I get rid of the first connection? I know it's possible because it happens when my application shuts down
Can I put the database in single user mode using or force the rename in some other way using SMO?
Thanks

I got it to work if I turn off pooling in my connection string by adding Pooling=false. Then calling Disconnect on the ServerConnection:
ServerConnection svrConn = null;
try
{
string connString = Cryptographer.Decrypt(ConfigurationManager.ConnectionStrings["CS"].ConnectionString);
svrConn = new Microsoft.SqlServer.Management.Common.ServerConnection(new System.Data.SqlClient.SqlConnection(connString));
Server server = new Microsoft.SqlServer.Management.Smo.Server(svrConn);
Backup backup = new Microsoft.SqlServer.Management.Smo.Backup();
...
backup.SqlBackup(server);
}
catch (Exception ex)
{
...
}
finally
{
if (svrConn != null)
svrConn.Disconnect();
}
I think server.ConnectionContext.Disconnect would also work, but haven't tried it.

Related

Reset app state between InstrumentationTestCase runs

One of my QA engineers is supporting an app with a fairly large codebase and a lot of different SharedPreferences files. He came to me the other day asking how to reset the application state between test runs, as if it had been uninstalled-reinstalled.
It doesn't look like that's supported by Espresso (which he is using) nor by the Android test framework natively, so I'm not sure what to tell him. Having a native method to clear all the different SharedPreferences files would be a pretty brittle solution.
How can one reset the application state during instrumentation?
Current espresso doesn't provide any mechanism to reset application state. But for each aspect (pref, db, files, permissions) exist a solution.
Initial you must avoid that espresso starts your activity automatically so you have enough time to reset.
#Rule
public ActivityTestRule<Activity> activityTestRule = new ActivityTestRule<>(Activity.class, false, false);
And later start your activity with
activityTestRule.launchActivity(null)
For reseting preferences you can use following snippet (before starting your activity)
File root = InstrumentationRegistry.getTargetContext().getFilesDir().getParentFile();
String[] sharedPreferencesFileNames = new File(root, "shared_prefs").list();
for (String fileName : sharedPreferencesFileNames) {
InstrumentationRegistry.getTargetContext().getSharedPreferences(fileName.replace(".xml", ""), Context.MODE_PRIVATE).edit().clear().commit();
}
You can reset preferences after starting your activity too. But then the activity may have already read the preferences.
Your application class is only started once and already started before you can reset preferences.
I have started to write an library which should make testing more simple with espresso and uiautomator. This includes tooling for reseting application data. https://github.com/nenick/espresso-macchiato See for example EspAppDataTool with the methods for clearing preferences, databases, cached files and stored files.
Improving on #nenick's solution, encapsulate the state clearing behavior in a custom ActivityTestRule. If you do this, you can allow the test to continue to launch the activity automatically without intervention from you. With a custom ActivityTestRule, the activity is already in the desired state when it launches for the test.
Rules are particularly useful because they're not tied to any specific test class, so can be easily reused within any test class or any project.
Below is one I implemented to ensure that the app is signed out when the activity launches, per test. Some tests, when they failed, were leaving the app in a signed in state. This would then cause later tests to also fail because the later ones assumed they would need to sign in, but the app would already be signed in.
public class SignedOutActivityTestRule<T extends Activity> extends ActivityTestRule<T> {
public SignedOutActivityTestRule(Class<T> activityClass) {
super(activityClass);
}
#Override
protected void beforeActivityLaunched() {
super.beforeActivityLaunched();
InstrumentationRegistry.getTargetContext()
.getSharedPreferences(
Authentication.SHARED_PREFERENCES_NAME,
Context.MODE_PRIVATE)
.edit()
.remove(Authentication.KEY_SECRET)
.remove(Authentication.KEY_USER_ID)
.apply();
}
}
you can try add this to gradle:
android {
...
defaultConfig {
...
testInstrumentationRunnerArguments clearPackageData: 'true'
}
}
refer to https://developer.android.com/training/testing/junit-runner
To remove all shared state from your device's CPU and memory after each test, use the clearPackageData flag.

Check if DTC service is turned on in C#

When Distributed Transaction Coordinator (DTC) is not running, our MVC C# site throws strange misleading errors, confusing developers and testers. We want to do a code check that the service is running and flag the issue on something like Global.asax. Any way to do this?
The below code starts the MSDTC service on the local machine if it's currently "Stopped"
You need to reference the System.ServiceProcess assembly
using(var msDtcSvc = new System.ServiceProcess.ServiceController("MSDTC"))
{
if(msDtcSvc.Status == System.ServiceProcess.ServiceControllerStatus.Stopped)
{
msDtcSvc.Start();
}
}

How to download Azure blob asynchronously only if it exists - in one step?

I want to asynchronously download a block blob from Azure storage, but only if the blob exists.
var blob = documentsContainer.GetBlockBlobReference(blobName);
if (await blob.ExistsAsync())
await blob.DownloadToStreamAsync(stream);
But this makes two HTTP calls, right? The common path in my app is that the blob will exist, so most of the time I don't want the overhead of the existence check. But I need to gracefully handle the case where the blob doesn't exist also.
I tried leaving the existence check out and just using a try/catch block. That works if I am using DownloadTextAsync, but when using DownloadToStreamAsync, if the blob isn't there, it just hangs.
Is there a way to download a binary blob to a stream asynchronously, only if it exists, without making two calls?
It turns out that it does properly throw the exception:
try
{
var blob = documentsContainer.GetBlockBlobReference(blobName);
await blob.DownloadToStreamAsync(stream);
...
}
catch (StorageException ex)
{
if ((HttpStatusCode)ex.RequestInformation.HttpStatusCode == HttpStatusCode.NotFound)
{
return null; // exit the calling function
}
throw;
}
When I tried this originally, it hung at the DownloadToStreamAsync call. After the comments in the original question, I started checking the versions, and I found a mismatch in Microsoft.Data.Services.Client.dll. I was using 5.6.1, but my test project somehow had 5.6.0. (I'm not sure where it pulled that from, as it's not in my solution at all). After manually referencing Microsoft.Data.Services.Client 5.6.1 from the test project, it no longer hangs.

node.js process out of memory error

FATAL ERROR: CALL_AND_RETRY_2 Allocation Failed - process out of memory
I'm seeing this error and not quite sure where it's coming from. The project I'm working on has this basic workflow:
Receive XML post from another source
Parse the XML using xml2js
Extract the required information from the newly created JSON object and create a new object.
Send that object to connected clients (using socket.io)
Node Modules in use are:
xml2js
socket.io
choreographer
mysql
When I receive an XML packet the first thing I do is write it to a log.txt file in the event that something needs to be reviewed later. I first fs.readFile to get the current contents, then write the new contents + the old. The log.txt file was probably around 2400KB around last crash, but upon restarting the server it's working fine again so I don't believe this to be the issue.
I don't see a packet in the log right before the crash happened, so I'm not sure what's causing the crash... No new clients connected, no messages were being sent... nothing was being parsed.
Edit
Seeing as node is running constantly should I be using delete <object> after every object I'm using serves its purpose, such as var now = new Date() which I use to compare to things that happen in the past. Or, result object from step 3 after I've passed it to the callback?
Edit 2
I am keeping a master object in the event that a new client connects, they need to see past messages, objects are deleted though, they don't stay for the life of the server, just until their completed on client side. Currently, I'm doing something like this
function parsingFunction(callback) {
//Construct Object
callback(theConstructedObject);
}
parsingFunction(function (data) {
masterObject[someIdentifier] = data;
});
Edit 3
As another step for troubleshooting I dumped the process.memoryUsage().heapUsed right before the parser starts at the parser.on('end', function() {..}); and parsed several xml packets. The highest heap used was around 10-12 MB throughout the test, although during normal conditions the program rests at about 4-5 MB. I don't think this is particularly a deal breaker, but may help in finding the issue.
Perhaps you are accidentally closing on objects recursively. A crazy example:
function f() {
var shouldBeDeleted = function(x) { return x }
return function g() { return shouldBeDeleted(shouldBeDeleted) }
}
To find what is happening fire up node-inspector and set a break point just before the suspected out of memory error. Then click on "Closure" (below Scope Variables near the right border). Perhaps if you click around something will click and you realize what happens.

MQ Connection - 2009 error

am connectting the MQ with below code. I am able connected to MQ successfully. My case is i place the messages to MQ every 1 min once. After disconnecting the cable i get a ResonCode error but IsConnected property still show true. Is this is the right way to check if the connection is still connected ? Or there any best pratcices around that.
I would like to open the connection when applicaiton is started keep it open for ever.
public static MQQueueManager ConnectMQ()
{
if ((queueManager == null) || (!queueManager.IsConnected)||(queueManager.ReasonCode == 2009))
{
queueManager = new MQQueueManager();
}
return queueManager;
}
The behavior of the WMQ client connection is that when idle it will appear to be connected until an API call fails or the connection times out. So isConnected() will likely report true until a get, put or inquire call is attempted and fails, at which point QMgr will then report disconnected.
The other thing to consider here is that 2009 is not the only code you might get. It happens to be the one you get when the connection is severed but there are connection codes for QMgr shutting down, channel shutting down, and a variety of resource and other errors.
Typically for a requirement to maintain a constant connection you would want to wrap the connect and message processing loop inside a try/catch block nested inside a while statement. When you catch an exception other than an intentional exit, close the objects and QMgr, sleep at least 5 seconds, then loop around to the top of the while. The sleep is crucial because if you get caught in a tight reconnect loop and throw hundreds of connection attempts at the QMgr, you can bring even a mainframe QMgr to its knees.
An alternative is to use a v7 WMQ client and QMgr. With this combination, automatic reconnection is configurable as a channel configuration.

Resources