SQLiteAsyncConnection UpdateWithChildren not available - xamarin

I am trying to implement a OneToMany relationship inside my PCL using SQLite.net. I have the async extensions package (SQLiteNetExtensions.Async) and I am basing the code on the example found in https://bitbucket.org/twincoders/sqlite-net-extensions. I am using SQLiteAsyncConnection but the UpdateWithChildren method does not seem to be available, only with SQLiteConnection.
using SQLite.Net;
using SQLite.Net.Async;
using SQLite.Net.Interop;
using SQLiteNetExtensions.Extensions;
private readonly SQLiteAsyncConnection conn;
public ActivityRepository(ISQLitePlatform platform, string dbPath)
{
var connectionFactory = new Func<SQLiteConnectionWithLock>(() => new SQLiteConnectionWithLock(platform, new SQLiteConnectionString(dbPath, storeDateTimeAsTicks: true)));
conn = new SQLiteAsyncConnection(connectionFactory);
}
public void method(object object) {
conn.UpdateWithChildren(object); --function not available
}

When using SQLiteAsyncConnection, you have to use the async Nuget package, SQLiteNetExtensionsAsync.Extensions namespace and async versions of all the methods:
using SQLite.Net;
using SQLite.Net.Async;
using SQLite.Net.Interop;
using SQLiteNetExtensionsAsync.Extensions;
private readonly SQLiteAsyncConnection conn;
public ActivityRepository(ISQLitePlatform platform, string dbPath)
{
var connectionFactory = new Func<SQLiteConnectionWithLock>(() => new SQLiteConnectionWithLock(platform, new SQLiteConnectionString(dbPath, storeDateTimeAsTicks: true)));
conn = new SQLiteAsyncConnection(connectionFactory);
}
public Task method(object object) {
return conn.UpdateWithChildrenAsync(object);
}
Please note that all async methods return a Task that must be awaited or returned.

Related

Store Workflow Activity Data When Publishing

I Need to store a specific activity data in another collection in database whenever a user publish a workflow in elsa.
I dont find any documentation, Please suggest me some resource or suggestion to achieve this. I have try to implement this with middleware. The Middleware code is
namespace WorkFlowV3
{
// You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
public class CustomMiddleware
{
private readonly RequestDelegate _next;
static HttpClient client = new HttpClient();
public CustomMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext httpContext)
{
//Write Custom Logic Here....
client.BaseAddress = new Uri("#");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
string path = "/api/test-middleware-call";
HttpResponseMessage response = await client.GetAsync(path);
await _next(httpContext);
}
}
// Extension method used to add the middleware to the HTTP request pipeline.
public static class CustomMiddlewareExtensions
{
public static IApplicationBuilder UseCustomMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<CustomMiddleware>();
}
}
}
But in this process, I cant fetch the specific activity data.
The easiest way to store information in your own DB in response to the "workflow published" event is by implementing a notification handler (from MediatR) that handles the WorkflowDefinitionPublished notification.
For example:
public class MyWorkflowPublishedhandler : INotificationhandler<WorkflowDefinitionPublished>
{
private readonly IMyDatabaseStore _someRepository;
public MyWorkflowPublishedhandler(IMyDatabaseStore someRepository)
{
_someRepository = someRepository;
}
public async Task Handle(WorkflowDefinitionPublished notification, CancellationToken cancellationToken)
{
var workflowDefinition = notification.WorkflowDefinition;
// Your logic to do a thing.
}
}
To register this handler, from your Startup or Program class, add the following code:
services.AddNotificationHandler<MyWorkflowPublishedhandler>();
Your handler will be invoked every time a workflow gets published.

How to unit test the void method which puts a message to azure service bus using AzureClientFactory

We have a method to submit message to azure service bus which returns void. Since the SendMessageAsync is not returning any response after putting the message to the Azure Queue, I'm not sure whether we need to unit test this method.
We are using xUnit and Moq for the test and the project is .Net 6
Please let us know your thoughts as well.
This is the method that needs to be tested.
private readonly IConfiguration _configuration;
private readonly ILogger<QueueService> _logger;
private readonly IAzureClientFactory<ServiceBusClient> _azureClientFactory;
public AzureBusService(IConfiguration configuration,
ILogger<QueueService> logger,
IAzureClientFactory<ServiceBusClient> azureClientFactory)
{
_configuration = configuration;
_logger = logger;
_azureClientFactory = azureClientFactory;
}
public async Task SendMessage(string message)
{
try
{
var serviceBusCLient = _azureClientFactory.CreateClient("AzureSB");
var serviceBusSender = serviceBusCLient.CreateSender("queue1");
var serviceBusMessage = new ServiceBusMessage(message);
await serviceBusSender.SendMessageAsync(serviceBusMessage);
}
catch (Exception ex)
{
_logger.LogError("ex.Message}");
throw new Exception($"sendmessage failed");
}
}

Unable to setup MiniProfiler w/ Enity Framework 4.0 (Not code first)

I installed MiniProfiler and MiniProfiler.EF in my project via nuget.
Before using MiniProfiler I would open a connection using this in my model repository:
public class NotificationRepository
{
private CBNotificationModel.CB_NotificationEntities db;
public NotificationRepository()
{
db = new CB_NotificationEntities();
}
public NotificationContact GetNotificationContacts()
{
return db.NotificationContacts.ToList();
}
}
To use mini profiler I created:
public static class ConnectionHelper
{
public static CB_NotificationEntities GetEntityConnection()
{
var conn = new StackExchange.Profiling.Data.EFProfiledDbConnection(GetConnection(), MiniProfiler.Current);
return ObjectContextUtils.CreateObjectContext<CB_NotificationEntities>(conn); // resides in the MiniProfiler.EF nuget pack
}
public static EntityConnection GetConnection()
{
return new EntityConnection(ConfigurationManager.ConnectionStrings["CB_NotificationEntities"].ConnectionString);
}
}
The model repository now uses
db = ConnectionHelper.GetEntityConnection();
However this gives the error:
An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll
Am I missing a step? I tried adding MiniProfilerEF.Initialize() and MiniProfilerEF.Initialize_EF42() in Application_start() however that just changes the errors given.
There does not seem to be much information for setting up a entity framework project to use miniprofiler unless it is codefirst.
I was able to get this working by changing my ConnectionHelper class to the following:
public static class ConnectionHelper
{
public static CB_NotificationEntities GetEntityConnection()
{
var connectionString = ConfigurationManager.ConnectionStrings["CB_NotificationEntities"].ConnectionString;
var ecsb = new EntityConnectionStringBuilder(connectionString);
var sqlConn = new SqlConnection(ecsb.ProviderConnectionString);
var pConn = new StackExchange.Profiling.Data.EFProfiledDbConnection(sqlConn, MiniProfiler.Current);
var context = ObjectContextUtils.CreateObjectContext<CB_NotificationEntities>(pConn);
return context;
}
}

Autofac, ASP.NET MVC 3 httpRequest scope and AutoMapper: No scope with a Tag matching 'httpRequest' is visible

When I use a web type registered with autofac from an automapper mapping, I get this error:
No scope with a Tag matching 'httpRequest' is visible from the scope in which the instance was requested. This generally indicates that a component registered as per-HTTP request is being reqested by a SingleInstance() component (or a similar scenario.) Under the web integration always request dependencies from the DependencyResolver.Current or ILifetimeScopeProvider.RequestLifetime, never from the container itself.
When another type is resolved in the mapping it works.
When a web type is resolved from the controller it works.
Why doesnt web (or any other httprequest scoped?) types get successfully resolved in my mapping?
protected void Application_Start()
{
var builder = new ContainerBuilder();
builder.RegisterModule<AutofacWebTypesModule>();
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.RegisterModelBinders(Assembly.GetExecutingAssembly());
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
.AssignableTo<Profile>()
.As<Profile>()
;
builder.Register(c => Mapper.Engine)
.As<IMappingEngine>();
builder.RegisterType<AnotherType>()
.As<IAnotherType>();
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
var profiles = container.Resolve<IEnumerable<Profile>>();
Mapper.Initialize(c => profiles.ToList().ForEach(c.AddProfile));
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
public class HomeController : Controller
{
private readonly IMappingEngine _mapper;
private readonly Func<HttpContextBase> _httpContext;
public HomeController(IMappingEngine mapper, Func<HttpContextBase> httpContext)
{
_mapper = mapper;
_httpContext = httpContext;
}
public ActionResult Index()
{
var test = _httpContext.Invoke();
return View(_mapper.Map<Model, ViewModel>(new Model()));
}
}
public class MyProfile : Profile
{
private readonly Func<HttpContextBase> _httpContext;
private readonly Func<IAnotherType> _anotherType;
public MyProfile(Func<HttpContextBase> httpContext, Func<IAnotherType> anotherType)
{
_httpContext = httpContext;
_anotherType = anotherType;
}
protected override void Configure()
{
CreateMap<Model, ViewModel>()
.ForMember(d => d.Url, o => o.ResolveUsing(s =>
{
var test = _anotherType.Invoke().GetAValue();
return _httpContext.Invoke().Request.Url;
}))
;
}
}
public interface IAnotherType
{
string GetAValue();
}
public class AnotherType : IAnotherType
{
public string GetAValue() { return "a value"; }
}
public class ViewModel
{
public string Url { get; set; }
}
public class Model
{
}
EDIT: Its easy to create an empty MVC project, paste the code and try it out and see for yourself.
EDIT: Removed the ConstructServicesUsing call because its not required by the example. No services are resolved through AutoMapper in the example.
#rene_r above is on the right track; adapting his answer:
c.ConstructServicesUsing(t => DependencyResolver.Current.GetService(t))
Still might not compile but should get you close.
The requirement is that the call to DependencyResolver.Current is deferred until the service is requested (not kept as the value returned by Current when the mapper was initialised.)
I think you should use DependencyResolver.Current.Resolve instead of container.Resolve in
Mapper.Initialize(c =>
{
c.ConstructServicesUsing(DependencyResolver.Current);
profiles.ToList().ForEach(c.AddProfile);
});
I recently had a similar problem and it turned out to be a bad setup in my bootstrapper function. The following autofac setup did it for me.
builder.Register(c => new ConfigurationStore(new TypeMapFactory(), AutoMapper.Mappers.MapperRegistry.Mappers))
.AsImplementedInterfaces()
.SingleInstance();
builder.Register(c => Mapper.Engine)
.As<IMappingEngine>()
.SingleInstance();
builder.RegisterType<TypeMapFactory>()
.As<ITypeMapFactory>()
.SingleInstance();
I did not have to specify resolver in the Mapper.Initialize() function. Just called
Mapper.Initialize(x =>
{
x.AddProfile<DomainToDTOMappingProfile>();
});
after the bootstrapped and it works fine for me.

How to pass a mvc-mini-profiler connection to a base class from MVC3

Given this snippet of code
public abstract class Foo
{
private static SqlConnection _sqlConnection;
protected SqlConnection GetOpenConnection()
{
if (_sqlConnection == null)
{
_sqlConnection = new SqlConnection("connection string");
}
return _sqlConnection;
}
protected abstract void Execute();
}
public class FooImpl : Foo
{
protected override void Execute()
{
var myConn = GetOpenConnection();
var dog = myConn.Query<dynamic>("select 'dog' Animal");
var first = dog.First();
string animalType = first.Animal;
// more stuff here
}
}
How would you wrap the connection in a profiled connection if you don't have access to the connection creation process? Rewrite the code in the super class and wrap it there? This would involve changing hundreds of classes that inherit from the base. I'd prefer a way to change the base class, with as little changes necessary to the supers.
Thank you,
Stephen
Well after a bit of trial and error I compromised and added a ref to MvcMiniProfiler in the base library and changed the connection code a bit.
protected DbConnection GetOpenConnection()
{
if (_connection == null)
{
_connection = new SqlConnection(ConfigurationManager.ConnectionStrings["connection string "].ConnectionString);
_connection.Open();
}
return MvcMiniProfiler.Data.ProfiledDbConnection.Get(_connection, MiniProfiler.Current);
}
private static SqlConnection _connection;
This works for both hosting in the MVC project (for profiling purposes, where we don't have that capability (QA/Prod Databases)) and WPF/Windows Service

Resources