I am trying to read the records from table even when the table is locked due to particular transaction.
I am using below code
public async Task<KeyValuePair<String, List<Om_Category>>> CategoryList(Om_Category obj)
{
try
{
using (var transaction = new TransactionScope(
TransactionScopeOption.Required,
new TransactionOptions
{
IsolationLevel = IsolationLevel.ReadUncommitted
},
TransactionScopeAsyncFlowOption.Enabled))
{
using (var categoryContext = new ModelGeneration())
{
categoryContext.Configuration.ProxyCreationEnabled = false;
var data = await categoryContext
.tblCategory
.ToListAsync();
transaction.Complete();
return new KeyValuePair<String, List<Om_Category>>("", data);
}
}
}
catch (Exception ex)
{
return new KeyValuePair<String, List<Om_Category>>(ex.Message, null);
}
}
But seems like I am missing something to implement NoLocks. Still it
show timeout. Am I missing something ?
Surprisingly Entity Framework inbuilt Transaction Class worked !!
public async Task<KeyValuePair<String, List<BE_Category>>> CategoryList(BE_Category obj)
{
try
{
using (var categoryContext = new ModelGeneration())
{
using (var dbContextTransaction = categoryContext
.Database
.BeginTransaction(System.Data.IsolationLevel.ReadUncommitted))
{
categoryContext.Configuration.ProxyCreationEnabled = false;
//Code
dbContextTransaction.Commit();
return new KeyValuePair<String, List<BE_Category>>("", data);
}
}
}
catch (Exception ex)
{
return new KeyValuePair<String, List<BE_Category>>(ex.Message, null);
}
}
Reference
Related
I think I understand the error but I have no idea how to solve it :/
This is the error I'm getting:
"JAR library references with identical file names but different contents were found: __reference__guava.jar. Please remove any conflicting libraries from EmbeddedJar, InputJar and AndroidJavaLibrary. Food_Recipe_App.Android"
Reason to why I want Xamarin.Google.Guava is that someone said that it would fix an issue I had earlier;
"System.NullReferenceException
Message=Object reference not set to an instance of an object."
Which, honestly, I have no idea how to solve either.
I'm thankful for all help :)
Edit: It breaks after calling the Firestore.Read();
protected override async void OnAppearing()
{
base.OnAppearing();
//using (SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation))
//{
// conn.CreateTable<Recipe>();
// var recipes = conn.Table<Recipe>().ToList();
// //recipeListView.ItemsSource = recipes;
//};
var recipes = await Firestore.Read(); ***//this line breaks***
//assignRecipesToDays(recipes);
}
This is the Read method from my Firestore script:
public async Task<List<Recipe>> Read()
{
try
{
hasReadRecipes = false;
var collection = FirebaseFirestore.Instance.Collection("recipes");
var query = collection.WhereEqualTo("userId", FirebaseAuth.Instance.CurrentUser.Uid);
query.Get().AddOnCompleteListener(this);
for (int i = 0; i < 50; i++)
{
await System.Threading.Tasks.Task.Delay(100);
if (hasReadRecipes)
break;
}
return recipes;
}
catch (Exception ex)
{
return recipes;
}
}
And this is the whole Firestore Script if that helps solving it:
using Android.App;
using Android.Content;
using Android.Gms.Tasks;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Firebase.Auth;
using Firebase.Firestore;
using Food_Recipe_App.Assets.Classes;
using Food_Recipe_App.Helpers;
using Java.Interop;
using Java.Util;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xamarin.Forms;
[assembly: Dependency(typeof(Food_Recipe_App.Droid.Dependencies.Auth))]
namespace Food_Recipe_App.Droid.Dependencies
{
public class Firestore : Java.Lang.Object, IFirestore, IOnCompleteListener
{
List<Recipe> recipes;
bool hasReadRecipes = false;
public Firestore()
{
recipes = new List<Recipe>();
}
public async Task<bool> Delete(Recipe recipe)
{
try
{
var collection = FirebaseFirestore.Instance.Collection("recipes");
collection.Document(recipe.Id).Delete();
return true;
}
catch (Exception ex)
{
return false;
}
}
public async Task<bool> Insert(Recipe recipe)
{
try
{
var recipeDocument = new Dictionary<string, Java.Lang.Object>()
{
{ "title", recipe.title },
{ "description", recipe.description },
{ "creatorUserId", FirebaseAuth.Instance.CurrentUser.Uid }
};
var collection = Firebase.Firestore.FirebaseFirestore.Instance.Collection("recipes");
collection.Add(new HashMap(recipeDocument));
return true;
}
catch (Exception ex)
{
return false;
}
}
public void OnComplete(Android.Gms.Tasks.Task task)
{
if (task.IsSuccessful)
{
var documents = (QuerySnapshot)task.Result;
recipes.Clear();
foreach (var doc in documents.Documents)
{
Recipe newRecipe = new Recipe()
{
title = doc.Get("title").ToString(),
description = doc.Get("description").ToString(),
Id = doc.Id
};
recipes.Add(newRecipe);
}
}
else
{
recipes.Clear();
}
hasReadRecipes = true;
}
public async Task<List<Recipe>> Read()
{
try
{
hasReadRecipes = false;
var collection = FirebaseFirestore.Instance.Collection("recipes");
var query = collection.WhereEqualTo("userId", FirebaseAuth.Instance.CurrentUser.Uid);
query.Get().AddOnCompleteListener(this);
for (int i = 0; i < 50; i++)
{
await System.Threading.Tasks.Task.Delay(100);
if (hasReadRecipes)
break;
}
return recipes;
}
catch (Exception ex)
{
return recipes;
}
}
public async Task<bool> Update(Recipe recipe)
{
try
{
var recipeDocument = new Dictionary<string, Java.Lang.Object>()
{
{ "title", recipe.title },
{ "description", recipe.description },
{ "creatorUserId", FirebaseAuth.Instance.CurrentUser.Uid }
};
var collection = FirebaseFirestore.Instance.Collection("recipes");
collection.Document(recipe.Id).Update(recipeDocument);
return true;
}
catch (Exception ex)
{
return false;
}
}
}
}
I have a XXXWriter. Is this the correct Fire and Forget approach in C#?
public void Add(XXX model)
{
Task.Run(() => // Fire and forget?
{
using (var ctx = new FormsEntities())
{
var dbXXX = new DALXXX();
dbXXX.Foo = model.Foo;
try
{
ctx.DALXXX.Add(dbXXX);
ctx.SaveChanges();
}
catch (Exception ex)
{
Log.Log.LogError(ex.GetMostInnerException(), "whatever");
}
}
});
}
I would recommend that the implementation is refactored as below
public class XXXWriter
{
public static void FireAndForget(XXX model)
{
Task.Run(() => DoFireAndForgetAsync(model));
}
private void DoFireAndForgetAsync(XXX model)
{
try
{
using (var ctx = new FormsEntities())
{
var dbXXX = new DALXXX();
dbXXX.Foo = model.Foo;
ctx.DALXXX.Add(dbXXX);
ctx.SaveChanges();
}
}catch (Exception ex)
{
// Remember that the Async code needs to handle its own
// exceptions, as the "DoFireAndForget" method will never fail
Log.Log.LogError(ex.GetMostInnerException(), "whatever");
}
}
}
In a console application I'm starting from a list and open multiple tasks to handle them like:
List<Task> tasks = new List<Task>();
tasks.Add(Task.Run(() => { Elabor(el.Take(1000).ToList(), listLogDequeues); }));
tasks.Add(Task.Run(() => { Elabor(el.Skip(1000).Take(1000).ToList(), listLogDequeues); }));
tasks.Add(Task.Run(() => { Elabor(el.Skip(2000).Take(1000).ToList(), listLogDequeues); }));
Task.WaitAll(tasks.ToArray());
el and ListLogDequeue is a ConcurrentBag<T> and inside the function an integer is incremented safely using Interlocked.Add.
This allow me to run three/four tasks and perform operations, but inside Elabor is used Entity Framework and MongoClient, as two repos injected with Ninject in my console application Main. Each function build and use it's context, but I don't get if and how concurrency and thread safety can hurt here.
EF:
public OutAnag GetAnagById(string id)
{
try
{
using (var c = new Context())
{
return c.Anag.AsNoTracking().FirstOrDefault(e => e.Id == id);
}
}
catch (Exception ex)
{
return null;
}
}
Mongo:
public bool SetElab(string guid)
{
Context dbContext = new Context();
try
{
var filter = Builders<Anag>.Filter.Where(m => m.Guid == guid);
var update = Builders<Anag>.Update.Set(m => m.DataElaborazione, DateTime.Now);
var options = new FindOneAndUpdateOptions<Anag>();
dbContext.Anag.FindOneAndUpdate(filter, update, options);
}
catch (Exception e)
{
return false;
}
return true;
}
I am using Entity Framework 6.1 version.
I am performing a bulk insert operation with Entity Framework. I am getting an intermittent error with DbContext:
object reference not set to an instance of object" for db context.
Here is my code:
public class ApiTimingDataProvider : IApiTimingDataProvider
{
private ApiTimingDbContext _apiDbContext;
public ApiTimingDataProvider(ApiTimingDbContext apiDbContext)
{
if (apiDbContext == null)
throw new ArgumentNullException("ApiDbContext is Null");
_apiDbContext = apiDbContext;
}
public void InsertApiData(List<ApiTimingModel> apiModelList)
{
try
{
using (var ctx = _apiDbContext)
{
using (var transactionScope = new TransactionScope())
{
// some stuff in dbcontext
ctx.Database.CommandTimeout = 600;
ctx.BulkInsert(apiModelList);
ctx.SaveChanges();
transactionScope.Complete();
}
}
}
catch (Exception ex)
{
throw ex;
}
}
}
Can anyone suggest me the reason for getting the exception?
This is my query where I'm returning an IEnumerable<CreditCardTransaction> to iterate through.
public partial class CreditCardTransaction
{
public static IEnumerable<CreditCardTransaction> GetUnprocessedTransactions()
{
try
{
using (var context = new SuburbanEntities())
{
return from trans in context.CreditCardTransactions
where trans.IsPublished == false
select trans;
}
}
catch (Exception ex)
{
Logging.Log("An error occurred.", "GetUnprocessedTransactions",Apps.ServicesConfig, ex);
return null;
}
}
}
This is where I am modifying those transactions once I have processed them:
public void ProcessFile()
{
try
{
_client = new TruckServiceClient();
_globalSetting = new GlobalSetting();
var unprocesstransactions = CreditCardTransaction.GetUnprocessedTransactions();
foreach (var creditCardTransaction in unprocesstransactions)
{
creditCardTransaction.IsPublished = ProcessTransaction(creditCardTransaction);
}
}
catch (Exception ex)
{
Logging.Log("An error occurred.", "ProcessCreditCardTransactions.ProcessFile", Apps.RemoteServices, ex);
}
}
I am modifying the transactions here:
creditCardTransaction.IsPublished = ProcessTransaction(creditCardTransaction);
But once I have saved them, can I update the entity directly or do I need to create another method where I pass this information back in?
The problem you don't have access to the context. Here you have some examples how to do:
https://github.com/geersch/EntityFrameworkObjectContext
If you're developing Asp.Net app, you'll have some drawbacks illustreted in this article:
http://dotnetslackers.com/articles/ado_net/Managing-Entity-Framework-ObjectContext-lifespan-and-scope-in-n-layered-ASP-NET-applications.aspx#managing-objectcontext-instantiation