In my WCF service, I am getting the above error with the below code.
I am confused as to why I'm getting this error...
Can someone please explain what I would need to do in order to correct it?
public async Task<List<HH_FuelTkt_Output>> GetFilteredFuelTicketsAsync(HH_FuelTkt_Input value)
{
try
{
using (HandheldEntities DbContext = new HandheldEntities())
{
var tkts = await DbContext.HH_FuelTkt.Select(s =>
new HH_FuelTkt_Output
{
Customer_Name = s.Customer_Name,
FuelTkt_ID = s.FuelTkt_ID,
Image_ID = s.Image_ID,
Ticket_No = s.Ticket_No,
Trans_Timestamp = s.Trans_Timestamp,
Vehicle_No = s.Vehicle_No
}).Where(w => w.Image_ID != null);
The problem is, I forgot to include the ToListAsync on the end of the query.
Related
I'm running into this problem, let me describe it with my code: https://github.com/UnoSD/Moq.Dapper/issues/20
I'm trying to mock a QueryAsync call using Moq.Dapper library and hitting the error:
Multi-map error: splitOn column 'Id' was not found
Here is the multi mapping query and code that works perfect:
var query = $#" SELECT * FROM [{nameof(Dashboard)}] dashboard
left join [{nameof(DashboardUser)}] dusers on dashboard.DashboardId = dusers.DashboardId
left join [Users] users on dusers.UserId = users.Id
WHERE dashboard.{nameof(accountId)} = #{nameof(accountId)} AND dashboard.{nameof(dashboardId)} = #{nameof(dashboardId)}";
Dashboard? dashboardEntity = null;
using (var connection = _context.CreateConnection())
{
var result = await connection.QueryAsync<Dashboard, DashboardUser, User, Dashboard?>(query,
(dashboard, dashboardUser, user) =>
{
if (dashboard == null) return null;
if (dashboardEntity == null)
{
dashboardEntity = dashboard;
dashboardEntity.Users = new List<DashboardUser>();
}
if (dashboardUser != null)
{
dashboardEntity.Users.Add(dashboardUser);
if (user != null) dashboardUser.User = user;
}
return dashboardEntity;
}, splitOn: $#"{nameof(Dashboard.DashboardId)},{nameof(Dashboard.DashboardId)},Id", param: new { accountId, dashboardId });
}
When Mocking the QueryAsync call I'm hitting the same problem as everyone else in the GitHub thread:
Func<Dashboard, DashboardUser, User, Dashboard?> funMap = (Dashboard, DashboardUser, User) => Mock.Of<Dashboard>();
public async Task Should_Get_Dashboard()
{
// Arrange
var connection = new Mock<DbConnection>();
IEnumerable<Dashboard> expected = GenFu.ListOf<Dashboard>(1);
connection.SetupDapperAsync(c => c.QueryAsync(It.IsAny<string>(), funMap, It.IsAny<object>(), It.IsAny<IDbTransaction>(),It.IsAny<bool>(),
"DashboardId,DashboardId,Id", // <-- SplitOn defined but error is *Multi-map error: splitOn column 'Id' was not found*
It.IsAny<int?>(), It.IsAny<CommandType?>()))
.ReturnsAsync(expected);
_context.Setup(x => x.CreateConnection()).Returns(connection.Object);
var dashboardRepository = new DashboardRepository(_context.Object, null, null);
CommonResult<Dashboard?> actual = new();
// Act
actual = await dashboardRepository.GetDashboard(3, 1);
}
Does anyone have a solution for this? It's the final thing for my Unit Test code coverage.
UPDATE:
I don't need to specify the mapping. See how the code TFirst, TSecond, TThird, TResult is faint/dimmed and I get the same problem even with it explicitly mapped:
I did try this method:
connection.SetupDapperAsync(c => c.QueryAsync<Dashboard>(It.IsAny<string>(), It.IsAny<Type[]>(), GetFunc, It.IsAny<object>(), It.IsAny<IDbTransaction>(), It.IsAny<bool>(), $#"{nameof(Dashboard.DashboardId)},{nameof(Dashboard.DashboardId)},Id", It.IsAny<int?>(), It.IsAny<CommandType?>()))
.ReturnsAsync(expected);
and got the error:
System.ArgumentException : When using the multi-mapping APIs ensure you set the splitOn param if you have keys other than Id (Parameter 'splitOn')
I checked the Dapper code and tried * for the SplitOn and that made no difference.
UPDATE 2:
The problem is the MultiMapAsync method and I can't mock it because its scope is private:
UPDATE 3:
I changed the Dapper method to Public to see if I could Mock it:
Func<Dashboard, DashboardUser, User, Dashboard?> funMap = (Dashboard, DashboardUser, User) => Mock.Of<Dashboard>();
private class DontMap { /* hiding constructor */ }
public async Task Should_Get_Dashboard()
{
// Arrange
var connection = new Mock<DbConnection>();
IEnumerable<Dashboard> expected = GenFu.ListOf<Dashboard>(1);
connection.SetupDapperAsync(c => c.MultiMapAsync<Dashboard, DashboardUser, User, DontMap, DontMap, DontMap, DontMap, Dashboard?>(new CommandDefinition(It.IsAny<string>(), It.IsAny<object>(), It.IsAny<IDbTransaction>(), It.IsAny<int>(),It.IsAny<CommandType>(), CommandFlags.None, default), funMap, $#"{nameof(Dashboard.DashboardId)},{nameof(Dashboard.DashboardId)},Id")).ReturnsAsync(expected);
I get the error:
Specified method is not supported
Mocking Dapper extension methods provides no value. You end up just testing your own test code. I would do either an integration test, where you test the whole method on a small database, or pull the testable logic out of the Dapper call like this:
using (var connection = _context.CreateConnection())
{
var result = await connection.QueryAsync<Dashboard, DashboardUser, User, Dashboard?>(query,
(dashboard, dashboardUser, user) => CreateDashboardEntity(dashboardEntity, dashboard, dashboardUser, user),
splitOn: $#"{nameof(Dashboard.DashboardId)},{nameof(Dashboard.DashboardId)},Id", param: new { accountId, dashboardId });
}
public Dashboard? CreateDashboardEntity(Dashboard? dashboardEntity, Dashboard dashboard, DashboardUser dashboardUser, User user)
{
if (dashboard == null) return null;
if (dashboardEntity == null)
{
dashboardEntity = dashboard;
dashboardEntity.Users = new List<DashboardUser>();
}
if (dashboardUser != null)
{
dashboardEntity.Users.Add(dashboardUser);
if (user != null) dashboardUser.User = user;
}
return dashboardEntity;
}
Now you can unit-test CreateDashBoardEntity as much as you like, and there is no logic left in QueryAsync that haven't already been tested by the good Dapper developers.
I'm developing a C# WinForms app, using the UWP API. I'm attempting to read notifications programatically, and I have succeeded so far. However, whenever I call AppInfo from the UserNotification class, I get a NotImplementedException, no matter what property I read from AppInfo.
Does anyone have any suggestions?
I have only been able to find 1 answer to this question and it's not very useful, and also a few years old. This is a major roadblock in my project, any help is massively appreciated!
Thank you in advance.
EDIT
Here's my code.
try {
this.source = notification.AppInfo.DisplayInfo.DisplayName;
} catch(NotImplementedException e) {
this.source = "Unspecified";
}
NotificationBinding binding = notification.Notification.Visual.GetBinding(KnownNotificationBindings.ToastGeneric);
if (binding != null) {
Console.WriteLine(binding.GetTextElements()[1]);
this.title = binding.GetTextElements().FirstOrDefault()?.Text;
this.body = string.Join("\n", binding.GetTextElements().Skip(1).Select(t => t.Text));
}
Init();
I'm using the code from the examples in the docs.
UWP AppInfo throws NotImplementedException
Based on the exception message, it looks like notification.AppInfo.DisplayInfo has not
been implemented for WinForm platform. For this scenario, we have a workaround for getting AppInfo with [AppDiagnosticInfo][1] api. Please refer the following code
var list = await AppDiagnosticInfo.RequestInfoAsync();
var currentPackage = list.Where(o => o.AppInfo.PackageFamilyName == Package.Current.Id.FamilyName).FirstOrDefault();
if (currentPackage != null)
{
AppInfo currentAppInfo = currentPackage.AppInfo;
var display = currentAppInfo.DisplayInfo;
}
private async Task<AppDisplayInfo> GetDisplayInfo()
{
var list = await AppDiagnosticInfo.RequestInfoAsync();
var currentPackage = list.FirstOrDefault(o => o.AppInfo.PackageFamilyName == Package.Current.Id.FamilyName);
if (currentPackage != null)
{
var currentAppInfo = currentPackage.AppInfo;
var display = currentAppInfo.DisplayInfo;
return display;
}
return null;
}
I'm trying to understand why the following unit test does not execute the callback. If I modify the code so that the UpdateWorklowInstanceState method only contains 2 parameters (Guid and IList), it works. However, something about having 3 parameters interferes.
What I mean by interferes is that the Callback doesn't appear to get executed. There's no error message. I expect to see the "Error Occurred" message but instead receive an "Element Updated" message which means the Callback did not populate the resultMessages with the NotificationMessage.
public void BusinessObjectReturnsErrorNotification_ReturnErrorMessage()
{
var workflowInstanceGuid = Guid.NewGuid();
var workflowElementModel = new WorkflowElementModel
{
ElementName = "ValidName",
WorkflowInstanceId = workflowInstanceGuid.ToString()
};
var workflowElementInstance = new WorkflowElementInstance
{
ElementName = workflowElementModel.ElementName,
FullDescription = "Full Description",
SummaryDescription = "Summary Description",
RefTime = DateTime.Now,
ElementType = "ElementType"
};
var mockWebApiBusinessObject = new Mock<IWebApiBusinessObject>();
mockWebApiBusinessObject.Setup(m => m.UpdateWorkflowInstanceState(workflowInstanceGuid, workflowElementInstance, It.IsAny<List<NotificationMessage>>()))
.Callback<Guid, WorkflowElementInstance, IList<NotificationMessage>>(
(workflowInstanceId, elementDetails, resultMessages) =>
{
resultMessages.Add(new NotificationMessage("An Error Occured!", MessageSeverity.Error));
});
var controller = new WorkflowElementController(mockWebApiBusinessObject.Object);
var result = controller.UpdateWorkflowElement(workflowElementModel);
Assert.AreEqual("An Error Occured!", result.Content.ReadAsStringAsync().Result);
}
Method under test:
[HttpPost]
[ActionName("UpdateWorkflowElement")]
public HttpResponseMessage UpdateWorkflowElement(WorkflowElementModel workflowElementModel)
{
if (!ModelState.IsValid || workflowElementModel == null)
{
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
var response = new HttpResponseMessage(HttpStatusCode.OK);
string responseMessage;
if (workflowElementModel.RefTime == DateTime.MinValue)
{
workflowElementModel.RefTime = DateTime.UtcNow;
}
var resultMessages = new List<NotificationMessage>();
var instanceId = new Guid();
if (string.IsNullOrWhiteSpace(workflowElementModel.WorkflowInstanceId) ||
string.IsNullOrWhiteSpace(workflowElementModel.ElementName))
{
responseMessage = "WorkflowInstanceId or ElementName are null or empty";
}
else if (!Guid.TryParse(workflowElementModel.WorkflowInstanceId, out instanceId))
{
responseMessage = "WorkflowInstanceId is not a valid Guid";
}
else
{
var element = new WorkflowElementInstance
{
ElementName = workflowElementModel.ElementName,
RefTime = workflowElementModel.RefTime,
SummaryDescription = workflowElementModel.SummaryDescription ?? "",
FullDescription = workflowElementModel.FullDescription ?? ""
};
_webApiBusinessObject.UpdateWorkflowInstanceState(instanceId, element, resultMessages);
responseMessage = "Element Updated";
}
if (NotificationMessage.HasErrors(resultMessages))
{
responseMessage = resultMessages.Find(m => m.Status == MessageSeverity.Error).Message;
}
response.Content = new StringContent(responseMessage);
return response;
}
It does not work in you case for 3 parameters because you are mixing the expression parameter types.
It.IsAny<List<NotificationMessage>>()
in the setup, as apposed to the
IList<NotificationMessage>
in the callback parameters.
That means the setup expression parameters does not match the callback expression parameters so the call back is not going to be called.
Stick with one type so either go with the List<NotificationMessage> for both
You are also creating new instances of the parameters in the method under test, which would be different instance to the ones used in the setup. That is why the call back is not working. To prove it. Use It.IsAny<>() for all the parameters and it should work
mockWebApiBusinessObject
.Setup(m => m.UpdateWorkflowInstanceState(It.IsAny<Guid>(), It.IsAny<WorkflowElementInstance>(), It.IsAny<List<NotificationMessage>>()))
.Callback<Guid, WorkflowElementInstance, List<NotificationMessage>>(
(workflowInstanceId, elementDetails, resultMessages) =>
{
resultMessages.Add(new NotificationMessage("An Error Occured!", MessageSeverity.Error));
});
Or the more generic interface
mockWebApiBusinessObject
.Setup(m => m.UpdateWorkflowInstanceState(It.IsAny<Guid>(), It.IsAny<WorkflowElementInstance>(), It.IsAny<IList<NotificationMessage>>()))
.Callback<Guid, WorkflowElementInstance, IList<NotificationMessage>>(
(workflowInstanceId, elementDetails, resultMessages) =>
{
resultMessages.Add(new NotificationMessage("An Error Occured!", MessageSeverity.Error));
});
You should also take some time and review Moq Quickstart to get a better understanding of how to use the mocking framework.
Please consider updating at minor places in your unit test.
Add before mocking IWebApiBusinessObject object:
List<NotificationMessage> messages = new List<NotificationMessage>();
Additionally, update Callback :
var mock = new Mock<IWebApiBusinessObject>();
mock.
Setup(m => m.UpdateWorkflowInstanceState(It.IsNotNull<Guid>(), It.IsNotNull<WorkflowElementInstance>(),It.IsAny<List<NotificationMessage>>() )).
Callback(() =>
{
messages.Add(new NotificationMessage("error msg", MessageSeverity.Severe));
messages.Add(new NotificationMessage("Ignore Message", MessageSeverity.Normal)); // this is optional... u can remove it if u want.
});
And need to update the source code method UpdateWorkflowElement(WorkflowElementModel model) to
UpdateWorkflowElement(WorkflowElementModel model, List<NotificationMessage> messages);
Consider changes in unit test code calling UpdateWorkflowElement to
var result = controller.UpdateWorkflowElement(workflowElementModel, messages);
If I have understood your UpdateWorkflowInstanceState() method correctly,
then you are using IWebApiBusinessObject to call UpdateWorkflowInstanceState( , , ) method.
When UpdateWorkflowInstanceState( , , ) executes during unit testing, it fires the Callback in your unit test and adds messages in list of NotificationMessage.
i tried this method that I created but it prompts me an error:
Realms.RealmInvalidObjectException:This object is detached. Was it deleted from the realm?'
public void deleteFromDatabase(List<CashDenomination> denom_list)
{
using (var transaction = Realm.GetInstance(config).BeginWrite())
{
Realm.GetInstance(config).Remove(denom_list[0]);
transaction.Commit();
}
}
what is the proper coding for deleting records from database in realm in C# type of coding?
You are doing it the right way. The error message you are getting indicates that the object was removed already. Are you sure it still exists in the realm?
UPDATE:
I decided to update this answer because my comment on the other answer was a bit hard to read.
Your original code should work fine. However, if you want deleteFromDatabase to accept lists with CashDenomination instances that either have been removed already or perhaps were never added to the realm, you would need to add a check. Furthermore, note that you should hold on to your Realm instance and use it in the transaction you created. In most cases, you want to keep it around even longer, though there is little overhead to obtaining it via GetInstance.
public void deleteFromDatabase(List<CashDenomination> denom_list)
{
if (!denom_list[0].IsValid) // If this object is not in the realm, do nothing.
return;
var realm = Realm.GetInstance(config);
using (var transaction = realm.BeginWrite())
{
realm.Remove(denom_list[0]);
transaction.Commit();
}
}
Now, if you want to use identifiers, you could look it up like you do, but still just use Remove:
public void deleteFromDatabase(int denom_id)
{
var realm = Realm.GetInstance(config);
var denom = realm.All<CashDenomination>().FirstOrDefault(c => c.denom_id == denom_id);
if (denom == null) // If no entry with this id exists, do nothing.
return;
using (var transaction = realm.BeginWrite())
{
realm.Remove(denom);
transaction.Commit();
}
}
Finally, if your CashDenomination has denom_id marked as PrimaryKey, you could look it up like this:
public void deleteFromDatabase(int denom_id)
{
var realm = Realm.GetInstance(config);
var denom = realm.ObjectForPrimaryKey<CashDenomination>(denom_id);
if (denom == null) // If no entry with this id exists, do nothing.
return;
using (var transaction = realm.BeginWrite())
{
realm.Remove(denom);
transaction.Commit();
}
}
public void deleteFromDatabase(Realm realm, long cashDenominatorId)
{
realm.Write(() =>
{
var cashDenominator = realm.All<Person>().Where(c => c.Id == cashDenominatorId);
Realm.RemoveRange<CashDenomination>(((RealmResults<CashDenomination>)cashDenominator));
});
}
Which you would call as
Realm realm = Realm.GetInstance(config);
var denom_list = ...
// ...
deleteFromDatabase(realm, denom_list[0].id);
I already made it having this code :) thanks to #EpicPandaForce 's answer.
public void deleteFromDatabase(int denom_ID, int form_ID)
{
//Realm realm;
//and
//RealmConfiguration config = new RealmConfiguration(dbPath, true);
//was initialized at the top of my class
realm = Realm.GetInstance(config);
realm.Write(() =>
{
var cashflow_denom = realm.All<CashDenomination>().Where(c => c.denom_id == denom_ID);
var cashflow_form = realm.All<CashForm>().Where(c => c.form_id == form_ID);
realm.RemoveRange(((RealmResults<CashDenomination>)cashflow_denom));
realm.RemoveRange(((RealmResults<CashForm>)cashflow_form));
});
}
it is now deleting my data without exception :)
Ok here is the deal. using my Model to raise the Child_Update() Method. I know it is not good but im just learing right now. Now i given my Business class as Parameter to Change the already given rows.
It's doin everything fine without any error Messages and there is also no null variable but it's not changing anything in the database.
here i'm using the selectedIndex to choose the right items to update
public void ExecuteAngestellte(object obj)
{
try
{
_selectedIndex.Child_Update(new Farbe { FarbauswahlNr = SelectedIndex.FarbauswahlNr, Kurztext = SelectedIndex.Kurztext, Ressource = SelectedIndex.Ressource, Vari1 = SelectedIndex.Vari1, Vari2 = SelectedIndex.Vari2 });
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
and here's the child update
public void Child_Update(Farbe data)
{
using (var ctx =Csla.Data.ObjectContextManager<TestDBEntities>.GetManager(EntitiesDatabase.Name))
{
var objectStateManager = ctx.ObjectContext.ObjectStateManager;
var _data = new Datenbank.Farbe();
_data.FarbauswahlNr = data.FarbauswahlNr;
_data.Kurztext = data.Kurztext;
_data.Ressource = data.Ressource;
_data.Var1 = data.Vari1;
_data.Vari2 = data.Vari2;
ctx.ObjectContext.SaveChanges();
}
}
thx for help
as far as I can tell, your _data is not part of the datacontext
I am not sure what the variables all mean so here is a simple update I use for a single record with entity framework
public void UpdateTable(int idRecord, YourContext Context)
{
MyRecord = Context.MyTable.Find(idRecord);
myRecord.Column = "New Value";
Context.SaveChanges();
}
so I think you need to do:
var MyData = ctx.ObjectContext.TableName.Find(id)
I am assuming you are using entity framework. Does this help?