To close db and cannot create commands from unopened database error - xamarin.android

string dppath = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "user.db3");
db = new SQLiteConnection(dppath);
string DELETEPASSCODE_DETAIL = "DELETE FROM Table1;";
db.Execute(DELETEPASSCODE_DETAIL);
db.Close();
Hello. When the program executes the above code and reaches the below code, I get this error: cannot create commands from unopened database
try
{
string dpPath = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "user.db3");`
if (dpPath.IndexOf("user.db3") < 0)
{
CreateDB();
CreateTable();
}
else
{
if (db == null)
{
db = new SQLiteConnection(dpPath);
}
var tableExist = db.GetTableInfo("Table1");
……
The error occurs on this db.GetTableInfo("Table1");

I made some mistakes for the first check of the code. Now, I reproduced this issue.
The db can not be null, delete the If statement.
Change:
if (db == null)
{
db = new SQLiteConnection(_databasePath);
}
var tableExist = db.GetTableInfo("Info");
var table_Info = db.Table<Info>().ToList();
To:
db = new SQLiteConnection(_databasePath);
var tableExist = db.GetTableInfo("Info");
var table_Info = db.Table<Info>().ToList();
db.Table<Info>().ToList() could also be used to get the table information.

Related

Installing Umbraco programmatically

I'm trying to install Umbraco without using the visual interface, in order to increase my productivity.
Currently my code looks like this:
var installApiController = new InstallApiController();
var installSetup = installApiController.GetSetup();
var instructions = new Dictionary<string, JToken>();
var databaseModel = new DatabaseModel
{
DatabaseType = DatabaseType.SqlCe
};
var userModel = new UserModel
{
Email = "my#email.com",
Name = "My name",
Password = "somepassword",
SubscribeToNewsLetter = false
};
foreach (var step in installSetup.Steps)
{
if (step.StepType == typeof(DatabaseModel))
{
instructions.Add(step.Name, JToken.FromObject(databaseModel));
}
else if (step.StepType == typeof(UserModel))
{
instructions.Add(step.Name, JToken.FromObject(userModel));
}
}
var installInstructions = new InstallInstructions
{
InstallId = installSetup.InstallId,
Instructions = instructions
};
InstallProgressResultModel progressInfo = null;
do
{
string stepName = "";
if (progressInfo != null)
{
stepName = progressInfo.NextStep;
}
try
{
progressInfo = installApiController.PostPerformInstall(installInstructions);
}
catch (Exception e)
{
throw new Exception(stepName, e);
}
}
while (progressInfo.ProcessComplete == false);
The code fails at this line: https://github.com/umbraco/Umbraco-CMS/blob/dev-v7.8/src/Umbraco.Web/Install/InstallSteps/NewInstallStep.cs#L47, and I believe it's because the ApplicationContext isnt updated for each of the installation steps (e.g. not updated after the database is created).
Is it possible to update the ApplicationContext manually after each step in the installation progress, or do I have to trigger all installation steps in separate HTTP requests?
The code works, if I run each step in separate HTTP requests.

TFS API: How to get attachments from shared steps?

This is what I see in the test results in the Test Manager: some attachments (1) are on the test steps (in this case - on a shared step). Some (2) are on a result level. In the report I'm working on, I can extract information about attachments (2), but fail to get information about (1). Any suggestions?
In the debugger I can see, that the steps are iterated, I can see, i.e. "Verify the stuff" string etc, but the step has 0 attachments.
For reference, this is most of the code I am using to extract test case results:
foreach (ITestCaseResult testCaseResult in resutlsToDisplay)
{
project.TestCases.Find(test.Id);
var testRun = testCaseResult.GetTestRun();
var testPlanEntry = project.TestPlans.Find(testRun.TestPlanId);
var artifacts = testCaseResult.QueryAssociatedWorkItemArtifacts();
if (testPlanEntry.Name != testPlan)
continue;
var testResult = new TestResult // CUSTOM CLASS
{
TestConfiguration = testCaseResult.TestConfigurationName,
TestRun = testRun.Id,
DateCreated = testRun.DateCreated,
DateStarted = testRun.DateStarted,
DateCompleted = testRun.DateCompleted,
Result = testCaseResult.Outcome.ToString(),
TestResultComment = testRun.Comment,
RunBy = testCaseResult.RunBy == null ? "" : testCaseResult.RunBy.DisplayName,
Build = testRun.BuildNumber ?? ""
};
foreach (var iteration in testCaseResult.Iterations)
{
var iterationResult = testResult.Clone();
iterationResult.ResultAttachmentHtml = getAttachments(iteration.Attachments, testCase.TestCaseId.ToString(), string.Empty, iteration.IterationId.ToString()); // HERE I GET THE ATTACHMENTS OF TYPE 2
iterationResult.Iteration = iteration.IterationId;
iterationResult.IterationComment = iteration.Comment;
foreach (var step in steps)
{
var stepCopy = step.Clone();
iterationResult.Steps.Add(stepCopy);
var actionResult = iteration.FindActionResult(stepCopy.TestStep);
if (actionResult == null)
continue;
stepCopy.Result.Comment = actionResult.ErrorMessage;
stepCopy.Result.Result = actionResult.Outcome.ToString();
stepCopy.Result.AttachmentHtml = getAttachments(actionResult.Attachments, testCase.TestCaseId.ToString(), step.Number, iteration.IterationId.ToString()); // HERE I DO NOT GET ATTACHMENTS OF TYPE 1 - WHY?
}
config.TestCaseResult.TestResults.Add(iterationResult);
}
} //end foreach testCaseResult in resutlsToDisplay
I think I figured it out eventually.
The ITestCaseResult contains ITestIterationResultCollection Iterations.
The ITestIterationResult contains TestActionResultCollection of ITestActionResult.
ITestActionResult can be either ITestStepResult or ISharedStepResult.
If it is ITestStepResult, then it has Attachments collection right there.
If it is ISharedStepResult, however, then it has its own TestActionResultCollection. So this is the one that I have to iterate to find if each member has Attachments.
The code to iterate over steps, including shared steps, looks like this:
foreach (ITestIterationResult iteration in testCaseResult.Iterations)
{
var iterationResult = testResult.Clone();
iterationResult.ResultAttachmentHtml = getAttachments(iteration.Attachments,
testCase.TestCaseId.ToString(),
string.Empty, iteration.IterationId.ToString());
iterationResult.Iteration = iteration.IterationId;
iterationResult.IterationComment = iteration.Comment;
foreach (ITestActionResult action in iteration.Actions)
{
if (action is ITestStepResult)
{
GetStepResults(steps, action, iterationResult, iteration, getAttachments, testCase, false);
}
else if (action is ISharedStepResult)
{
ISharedStepResult result = action as ISharedStepResult;
foreach (var sharedAction in result.Actions)
{
if (sharedAction is ITestStepResult)
{
GetStepResults(steps, sharedAction, iterationResult, iteration, getAttachments, testCase, true);
}
}
}
}

Entity Framework not able to update Tables

I'm new to EF, using 6.0 code-first.
using (EmpolyeeContext emp = new EmpolyeeContext())
{
var callrecordSession = new CallRecordingSession();
string ucid = new Random().Next(0, 5000).ToString();
callrecordSession.UCID = ucid;
callrecordSession.InstrumentationTransactionId = new Random().Next(0, 9000).ToString();
callrecordSession.ClientName = "IVR";
callrecordSession.ClientRequestObject = "{string.empty}";
callrecordSession.CallRecordingStatusName = "Started";
callrecordSession.ModifiedDatetime = DateTime.Now;
emp.CallRecordingSessions.Add(callrecordSession);
var itemToEdit = emp.CallRecordingSessions.Where(c => c.UCID == ucid).FirstOrDefault<CallRecordingSession>();
if (itemToEdit != null)
{
itemToEdit.CallRecordingStatusName = "Inprogress";
itemToEdit.ModifiedDatetime = DateTime.Now;
}
emp.SaveChanges();
}
What is wrong with this code? I'm always getting itemtoEdit as null
Entity Framework always queries the data source. This is by design. If they queried your local cache instead, You could get an Id that has already been inserted by a different user in the database. Also Entity framework has to merge results from your memory and the database.
var itemToEdit = emp.CallRecordingSessions.Where(c => c.UCID == ucid).FirstOrDefault<CallRecordingSession>();
So all you got to do is call the savechanges before you get the data back.
emp.CallRecordingSessions.Add(callrecordSession);
emp.SaveChanges();
var itemToEdit = emp.CallRecordingSessions.Where(c => c.UCID == ucid).FirstOrDefault<CallRecordingSession>();
if (itemToEdit != null)
{
itemToEdit.CallRecordingStatusName = "Inprogress";
itemToEdit.ModifiedDatetime = DateTime.Now;
}
emp.SaveChanges();
.SaveChanges() did the tricks.

TestManagementHttpClient Create Test Run

I am trying below C# code to create TFS test run. But every time I am getting below error. Though I have given test plan details. I couldnt even find documentations on this.
Error
An exception of type 'Microsoft.TeamFoundation.TestManagement.WebApi.TestObjectNotFoundException' occurred in mscorlib.dll but was not handled in user code
Additional information: Test plan {0} not found.
Code
public async Task CreateTestRun()
{
TestManagementHttpClient witClient = connection.GetClient<TestManagementHttpClient>();
TestCaseResultUpdateModel TestCaseResultUpdateModel = new TestCaseResultUpdateModel();
ShallowReference testPlanReference = new ShallowReference();
testPlanReference.Id = "{TestPlanId}";
testPlanReference.Name = "{TestPlanName}";
testPlanReference.Url = "http://{TFSInstance}/{Project}/_apis/test/plans/{TestPlanID}";
RunCreateModel RunCreateModel = new RunCreateModel("SWAT-Run","",new int[] {2304187},testPlanReference,
null,0,"",false,"Error Message","","","","","comment","","", "",
null, null, null, null,null,"","","","",new TimeSpan(0,0,10,0,0),"",null);
TestRun testRun = await witClient.CreateTestRunAsync(this.Project, RunCreateModel, null);
}
I have done it succssful with below code, hope it can be helpful to you.
var tfsRun = _testPoint.Plan.CreateTestRun(false);
tfsRun.DateStarted = DateTime.Now;
tfsRun.AddTestPoint(_testPoint, _currentIdentity);
tfsRun.DateCompleted = DateTime.Now;
tfsRun.Save(); // so results object is created
var result = tfsRun.QueryResults()[0];
result.Owner = _currentIdentity;
result.RunBy = _currentIdentity;
result.State = TestResultState.Completed;
result.DateStarted = DateTime.Now;
result.Duration = new TimeSpan(0L);
result.DateCompleted = DateTime.Now.AddMinutes(0.0);
var iteration = result.CreateIteration(1);
iteration.DateStarted = DateTime.Now;
iteration.DateCompleted = DateTime.Now;
iteration.Duration = new TimeSpan(0L);
iteration.Comment = "Run from TFS Test Steps Editor by " + _currentIdentity.DisplayName;
for (int actionIndex = 0; actionIndex < _testEditInfo.TestCase.Actions.Count; actionIndex++)
{
var testAction = _testEditInfo.TestCase.Actions[actionIndex];
if (testAction is ISharedStepReference)
continue;
var userStep = _testEditInfo.SimpleSteps[actionIndex];
var stepResult = iteration.CreateStepResult(testAction.Id);
stepResult.ErrorMessage = String.Empty;
stepResult.Outcome = userStep.Outcome;
foreach (var attachmentPath in userStep.AttachmentPaths)
{
var attachment = stepResult.CreateAttachment(attachmentPath);
stepResult.Attachments.Add(attachment);
}
iteration.Actions.Add(stepResult);
}
var overallOutcome = _testEditInfo.SimpleSteps.Any(s => s.Outcome != TestOutcome.Passed)
? TestOutcome.Failed
: TestOutcome.Passed;
iteration.Outcome = overallOutcome;
result.Iterations.Add(iteration);
result.Outcome = overallOutcome;
result.Save(false);

Entity Framework Newbie - Save to DB

I have 3 joined tables; ValidationRun has many Result which has many Error
The following code succeeds in saving to the Result and Error tables but not the ValidationRun.
Can you see the problem please?
private void WriteResultsToDB(SqlDataReader dr, XMLValidator validator)
{
using (var context = new ValidationResultsEntities())
{
var run = new ValidationRun { DateTime = DateTime.Now, XSDPath = this.txtXsd.Text };
//loop through table containing the processed XML
while (dr.Read())
{
var result = new Result
{
AddedDateTime = (DateTime)dr["Added"],
CustomerAcc = (string)dr["CustomerAcc"],
CustomerRef = (string)dr["CustomerRef"]
};
if (this.rdoRequest.Checked)
{
result.XMLMsg = (string)dr["RequestMSG"];
}
else
{
result.XMLMsg = (string)dr["ReplyMSG"];
}
if (validator.Validate(result.XMLMsg))
{
foreach (string error in validator.Errors)
{
result.Errors.Add(new Error { ErrorDescription = error });
}
}
else
{
//validator caught an error
result.Errors.Add(new Error { ErrorDescription = "XML could not be parsed" });
}
if (result.Errors.Count == 0) result.ValidFile = true; else result.ValidFile = false;
context.AddToResults(result);
context.SaveChanges();
}
}
You don't appear to be adding the run to any part of the context. If it were referenced by the result you are adding, perhaps, the change tracker would know it was supposed to be saved, but as it is written it is just some orphaned object that doesn't get attached anywhere.

Resources