System.Data.SQLite transaction lock whole database - sqlite

I'm trying to insert into 2 different tables from different transactions. Unfortunally I'm getting "database locked" exeption onto cn2.Execute...
var cb = new System.Data.SQLite.SQLiteConnectionStringBuilder
{
BinaryGUID = true,
DataSource = string.Format("file:SqliteTest-{0:N}.db", Guid.NewGuid()),
FailIfMissing = false,
JournalMode = System.Data.SQLite.SQLiteJournalModeEnum.Wal,
LegacyFormat = false,
Pooling = true,
SyncMode = System.Data.SQLite.SynchronizationModes.Normal,
DefaultIsolationLevel = System.Data.IsolationLevel.ReadCommitted
};
using (var cn1 = new System.Data.SQLite.SQLiteConnection(cb.ToString()))
{
cn1.Open();
cn1.Execute("create table t_1(uuid BLOB not null primary key, ts INTEGER not null);");
cn1.Execute("create table t_2(uuid BLOB not null primary key, ts INTEGER not null);");
using (var cn2 = (System.Data.SQLite.SQLiteConnection)cn1.Clone())
{
using (var tr1 = cn1.BeginTransaction(System.Data.IsolationLevel.ReadCommitted))
using (var tr2 = cn2.BeginTransaction(System.Data.IsolationLevel.ReadCommitted))
{
cn1.Execute("insert into t_1(uuid,ts) values(#uuid, #ts);",
new { uuid = Guid.NewGuid(), ts = DateTime.UtcNow.Ticks }, tr1);
cn2.Execute("insert into t_2(uuid,ts) values(#uuid, #ts);",
new { uuid = Guid.NewGuid(), ts = DateTime.UtcNow.Ticks }, tr2);
}
}
}

Related

ElasticSearch 7 nest 7 return attribute from result all result

I'm using ElarsticSearch 7.7 & NEST 7.7 and on my web page, I'm getting 9 search result documents per page. Even I'm showing the first 9 results on the page, I need to return some property values from all the results for side filtration on the web page.
Eg: if I'm searching "LapTop", my page will show 9 results on the first page. Also, I need to show all the "Manufactures" from all the search results. Not only manufacturers in the first-page result. Then customers can filter by manufacture not only display on the first page.
I have tried GlobalAggregation but it returns categories and manufactures only items in selected page.
public SearchResult Search(SearchType searchType, string searchQuery, int storeId, int pageNumber = 1, int pageSize = 12, IList<SearchFilter> requestFilter = null, decimal? priceFrom = 0, decimal? priceTo = 100000000, string sortBy = null, int totalCount = 0)
{
var queryContainer = new QueryContainer();
var sorts = new List<ISort>();
sorts.Add(new FieldSort { Field = "_score", Order = SortOrder.Descending });
switch (sortBy)
{
case "z-a":
sorts.Add(new FieldSort { Field = Field<ElasticIndexGroupProduct>(p => p.SortValue), Order = SortOrder.Descending });
break;
case "a-z":
sorts.Add(new FieldSort { Field = Field<ElasticIndexGroupProduct>(p => p.SortValue), Order = SortOrder.Ascending });
break;
}
var aggrigations = new AggregationDictionary
{
{"average_per_child", new
AverageAggregation("average_per_child",Field<ElasticIndexGroupProduct>(d => d.Price))},
{"max_per_child", new MaxAggregation("max_per_child",Field<ElasticIndexGroupProduct>(d => d.Price))},
{"min_per_child", new MinAggregation("min_per_child", Field<ElasticIndexGroupProduct>(d => d.Price))},
{
"globle_filter_aggrigation", new GlobalAggregation("globle_filter_aggrigation")
{
Aggregations =new AggregationDictionary
{
{"category_flow", new TermsAggregation("category_flow"){Field = Field<ElasticIndexGroupProduct>(p => p.CategoryFlow)} },
{"manufacturers", new TermsAggregation("manufacturers"){Field = Field<ElasticIndexGroupProduct>(p => p.Manufacturer)} }
}
}
}
};
var searchRequest = new SearchRequest<ElasticIndexGroupProduct>()
{
Profile = true,
From = (pageNumber - 1) * pageSize,
Size = pageSize,
Version = true,
Sort = sorts,
//Scroll = Time.MinusOne,
Aggregations = aggrigations
};
var multiMatch = new QueryStringQuery
{
Query = searchQuery,
Fields = GetSearchFields(searchType),
Boost = 1.1,
Name = "named_query",
DefaultOperator = Operator.Or,
Analyzer = "standard",
QuoteAnalyzer = "keyword",
AllowLeadingWildcard = true,
MaximumDeterminizedStates = 2,
Escape = true,
FuzzyPrefixLength = 2,
FuzzyMaxExpansions = 3,
FuzzyRewrite = MultiTermQueryRewrite.ConstantScore,
Rewrite = MultiTermQueryRewrite.ConstantScore,
Fuzziness = Fuzziness.Auto,
TieBreaker = 1,
AnalyzeWildcard = true,
MinimumShouldMatch = 2,
QuoteFieldSuffix = "'",
Lenient = true,
AutoGenerateSynonymsPhraseQuery = false
};
searchRequest.Query = new BoolQuery
{
Must = new QueryContainer[] { multiMatch },
Filter = new QueryContainer[] { queryContainer }
};
var searchResponse = _client.Search<ElasticIndexGroupProduct>(searchRequest);
var categoryFlowsGlobe = new List<string>();
var allAggregations = searchResponse.Aggregations.Global("globle_filter_aggrigation");
var categories = allAggregations.Terms("category_flow");
foreach (var aggItem in categories.Buckets)
{
if (!categoryFlowsGlobe.Any(x => x == aggItem.Key))
{
categoryFlowsGlobe.Add(aggItem.Key);
}
}
}
This is the exact use case for Post filter - to run a search request that returns hits and aggregations, then to apply filtering to the hits after aggregations have been calculated.
For Manufacturers, these can be retrieved with a terms aggregation in the search request - you can adjust the size on the aggregation if you need to return all manufacturers, otherwise you might decide to return only the top x.

Amazon DynamoDBv2 QueryOperationConfig SelectValues.Count not working

I have this piece of code like this:
var options = new DynamoDBOperationConfig
{
ConditionalOperator = ConditionalOperatorValues.Or,
OverrideTableName = nameTable,
ConsistentRead = true
};
new QueryOperationConfig()
{
IndexName = indexName,
Filter = queryFilter,
Select = SelectValues.Count
};
result = context.FromQueryAsync<TEntity>(queryConfig, options).GetRemainingAsync().Result;
as per the documentation, it should return just the count of values that match the filter, at least, the piece of code in the SelectValues class says that
//
// Summary:
// An enumeration of all supported Select values for Query and Scan. Value of Count
// will force service to return the number of items, not the items themselves.
but result is always an empty list; how can i make the count work ?
If you are still looking for the answer, this is the solution:
new QueryOperationConfig()
{
IndexName = indexName,
Filter = queryFilter,
Select = SelectValues.Count,
ConsistentRead = true
};
var table = context.GetTargetTable<TEntity>();
var search = table.Query(queryConfig);
result = search.Count;
Having ConsistentRead set to true will cause it to give you real time updates when the table is updated.
It's not working on Document level...
You can try to do this in low level model.
int count = 0;
Dictionary<string, AttributeValue> lastKey = null;
do
{
var request = new QueryRequest
{
TableName = "tableNmae",
IndexName = "indexName",
KeyConditionExpression = "ID= :v_ID",
ExpressionAttributeValues = new Dictionary<string, AttributeValue>
{
{
":v_ID",
new AttributeValue
{
N = "1"
}
}
},
ConsistentRead = false,
Select = Select.COUNT,
ExclusiveStartKey = lastKey
};
var respone = await tableClient.QueryAsync(request);
count += respone.Count;
lastKey = respone.LastEvaluatedKey;
} while (lastKey != null && lastKey.Count != 0);

how to solve error like "Cannot implicitly convert type"?

Code:
public IEnumerable<InvoiceStringData> GetInvoiceByID(string orderID)
{
var orderId = Convert.ToInt32(orderID);
ResponseDetails jsonRes = new ResponseDetails();
List<string> campaignidByProdid = new List<string>();
Productlevelcharges prodlevel = new Productlevelcharges();
List<Productlevelcharges> lstprodlevel = new
List<Productlevelcharges>();
List<OrderVM> lstorvm = new List<OrderVM>();
List<ProductMaster> lstpmvm = new List<ProductMaster>();
List<OrderDetailsVM> lstodvm = new List<OrderDetailsVM>();
List<ProductVariant> lstpvvm = new List<ProductVariant>();
List<CampaignProductMapper> lstcmvm = new
List<CampaignProductMapper>();
List<CampaignVm> lstcm = new List<CampaignVm>();
List<InvoiceStringData> Bill = new List<InvoiceStringData>();
InvoiceStringData InvoiceStringData = new InvoiceStringData();
var orderChargId = _context.Orderlevelcharges.Where(a => a.OrderId == orderId).Select(a => a.OrderChargeId).FirstOrDefault();
var orderCharge = orderChargId.ToString();
var lst = CalculateUnitPrice(orderCharge, orderID);
var result = (from v in lst
group v by new
{
v.InvoiceDate,
v.InvoiceNo,
v.NetAmount,
v.TotalAmount,
v.SaveAmount
} into order
select new
{
invoiceDate = order.Key.InvoiceDate,
netAmount = order.Key.NetAmount,
totalAmount = order.Key.TotalAmount,
saveAmount = order.Key.SaveAmount,
// productMasterlst=order
_invoice = new
{
product = order.Select(o => new {
o.productName, o.UnitPrice, o.Quantity, o.UnitOfMeasure, o.hsnCode,
o.Weight, o.Tax1Sgst, o.Tax2Cgst, o.Tax3Igst })
}
}).ToList();
return result;
}
error:
CS0266 Cannot implicitly convert type
'System.Collections.Generic.List<> product> _invoice>>' to 'System.Collections.Generic.IEnumerable'. An explicit conversion exists (are you missing a cast?) Payment.API D:\Consumer Billing\MRU 15-05-18 10.47\MRU Current\src\Services\Payment\Payment.API\BAL\Repository\InvoiceRepo.cs 131 Active

Join two dynamic Linq in Asp.net

I have used linq to store data, below is the code:
var result = (dynamic)null;
var serviceData = (dynamic)null;
var userData = (dynamic)null;
/****Linq 1*****/
serviceData= dtPasscode.AsEnumerable().Select(m => new
{
ACCOUNT_ID = intAccountId,
SUB_ACC_ID = m.Field<string>("ACCOUNT_ID_ALIAS")
});
/**Linq 2**/
userData = DisplyCustomerDetails(Convert.ToInt64(strSubAccountID));
result = serviceData.Concat(userData);
And another linq through function:
/**Function**/
System.Data.EnumerableRowCollection DisplyCustomerDetails(Int64 intAccountId)
{
var result = (dynamic)null;
/** Data Display if no service avaiable **/
IAccount_BL objAccount_BL = new Account_BL();
Customer objCustomer = new Customer();
DataTable dtCustomer = null;
int intErrorCount = 0;
objCustomer.Account_Id = Convert.ToInt64(intAccountId);
dtCustomer = objAccount_BL.GetCustomerDetails(objCustomer, ref intErrorCount);
objAccount_BL = null;
objCustomer = null;
if (intErrorCount == 0)
{
if (dtCustomer != null)
{
if (dtCustomer.Rows.Count > 0)
{
result = dtCustomer.AsEnumerable().Select(m => new
{
ACCOUNT_ID = intAccountId,
SUB_ACC_ID = m.Field<string>("ACCOUNT_ID_ALIAS")
});
}
}
}
return result;
}
I wanted to join both the result of Linq1 & Linq2, I tired Concat & Union, getting below error
'System.Data.EnumerableRowCollection<<>f__AnonymousTypea>' does not contain a definition for 'Concat'
To Concat both enumerables must of the same class; you cannot use anonymous classes. Define a class that has the two fields and change the code to Select them.
Also, don't use ... = (dynamic) null; just assign the variable directly
var serviceData= dtPasscode ...
var userData = DisplyCustomerDetails ...
var result = serviceData.Concat(userData);

Add parent row and add child for that new parent row

i am creating new record in 'Timecard' table and at the same time i want to create one record in 'TimecardStatusTrack' table using entity framework. i am able to create parent record but while adding child record i am getting exception. the code i have written is like
var fEmpManager = DependencyContainer.GetInstance<IBusinessService<FacilityEmployee>>();
int timecardStatusDidNotWork =
Convert.ToInt32(GeneralCodeId.TimeCardStatusDidNotWork, CultureInfo.InvariantCulture);
Timecard timecard = new Timecard();
TimecardStatusTrack timecardStatus = new TimecardStatusTrack();
try
{
var fEmp = fEmpManager.Where(w => w.JobId == jobId && w.AgencyBiddingProfile.AgencyCandidateId == agencyCandidateId).FirstOrDefault();
timecard.JobId = jobId;
timecard.AgencyCandidateId = agencyCandidateId;
timecard.WeekStartDate = Convert.ToDateTime(weekStartDate, CultureInfo.InvariantCulture);
timecard.WeekEndDate = Convert.ToDateTime(weekEndDate, CultureInfo.InvariantCulture);
timecard.FacilityEmployeeId = fEmp.Id;
timecard.FacilityId = fEmp.FacilityId;
timecard.TimecardStatusGCId = timecardStatusDidNotWork;
timecard.AddUser = SessionManager.AuthorizedInfo.UserId;
timecard.AddDate = DateTime.Now;
timecardStatus.TimecardStatusGCId = timecardStatusDidNotWork;
timecardStatus.AddUser = SessionManager.AuthorizedInfo.UserId;
timecardStatus.AddDate = DateTime.Now;
timecardStatus.UpdatedBy = SessionManager.AuthorizedInfo.UserId;
timecardStatus.Comments = string.Empty;
_ViewTimeCardBusibessService.Create(timecard);
timecard.TimecardStatusTracks.Add(timecardStatus);
_ViewTimeCardBusibessService.Update(timecard);
}
catch (Exception ex)
{
HandleValidationErrors(ex);
}
finally
{
DependencyContainer.ReleaseInstance(fEmpManager);
}

Resources