Async Await Stored Procedure - c#

I am using entity framework and am hoping of a way to await a result set from a stored procedure.
public async Task<ObservableCollection<FixturesQueryPM>> LoadFixtures()
{
try
{
using (var db = new FordAviationEntities())
{
DateTime preDate = DateTime.Today.AddDays(-50);
var obs = new ObservableCollection<FixturesQueryPM>();
Mapper.CreateMap<DATA_GetFixtureList_Result, PM.FixturesQueryPM>();
var rec = db.DATA_GetFixtureList(50);
if (rec != null)
{
foreach (var item in rec)
{
FixturesQueryPM newRec = Mapper.Map<Model.DATA_GetFixtureList_Result, PM.FixturesQueryPM>(item);
obs.Add(newRec);
}
return obs;
}
return null;
}
}
catch (Exception ex)
{
MessageBox.Show(string.Format("{0}{1}{2}", ex.Message, Environment.NewLine, ex.InnerException != null ? ex.InnerException.ToString() : ""));
return null;
}
}
Is this possible with SP's?
Thanks Scott

Related

How to break from the Catch block after throwing BadRequestException using C#

I have a method which needs to break after the BadRequestException() is thrown.
Currently after BadRequestException() is thrown, frontend shows loading bar buffering infinitely.
Please find my code below
public FeSite GetSiteBySiteId(string envCode, string siteId)
{
try
{
envCode.ThrowIfNull();
siteId.ThrowIfNull();
var watch = new Stopwatch();
watch.Start();
FeSite result = this.ExecuteAndParseWebRequestForEnv<FeSite>(envCode, $"sites/{siteId}", HttpMethod.Get);
this.LogService.Info($"FeeDataAcccess - GetSitebySiteId - {watch.ElapsedMilliseconds}ms");
return result;
}
catch (Exception e)
{
this.LogService.Error($"GetSiteBySiteId - {e.Message}");
throw new BadRequestException("Invalid siteId!");
}
}
Below method calls GetSiteBySiteId() method:
public string GetDevicesSerialNumberBySiteId(string envCode, string siteId)
{
var siteSerialNumber = "";
if (siteId != null)
{
var result = this.feeDataAccess.GetSiteBySiteId(envCode, siteId);
List<string> gatewaySiteSNlist = result.Gateways.Select(x => x.SerialNumber).ToList();
foreach (var item in gatewaySiteSNlist)
{
var siteSN = item;
siteSerialNumber += $";{siteSN};";
}
}
return siteSerialNumber;
}
I have tried this code below :
public FeSite GetSiteBySiteId(string envCode, string siteId)
{
do
{
try
{
envCode.ThrowIfNull();
siteId.ThrowIfNull();
var watch = new Stopwatch();
watch.Start();
FeSite result = this.ExecuteAndParseWebRequestForEnv<FeSite>(envCode, $"sites/{siteId}", HttpMethod.Get);
this.LogService.Info($"FeeDataAcccess - GetSitebySiteId - {watch.ElapsedMilliseconds}ms");
return result;
}
catch (Exception e)
{
this.LogService.Error($"GetSiteBySiteId - {e.Message}");
throw new BadRequestException("Invalid siteId!");
}
}
while (false);
{
break;
}
}
But I get error "No enclosing loop out of which to break or continue"
How to fix this? Thanks in advance.
public string GetDevicesSerialNumberBySiteId(string envCode, string siteId)
{
var siteSerialNumber = "";
if (siteId != null)
{
try{
var result = this.feeDataAccess.GetSiteBySiteId(envCode, siteId);
List<string> gatewaySiteSNlist = result.Gateways.Select(x => x.SerialNumber).ToList();
foreach (var item in gatewaySiteSNlist)
{
var siteSN = item;
siteSerialNumber += $";{siteSN};";
}
}catch{
//BadRequestException catch and error handling goes here
}
}
return siteSerialNumber;
}

The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects duplicate objects

Hi I am using Entity Framework Code First, for my Database and CRUD operations, but when I am trying to add into couple of tables using entities.
Here is the message I am getting:
The relationship between the two objects cannot be defined because
they are attached to different ObjectContext objects duplicate objects
My create function is as below:
public T Create(T item)
{
try
{
if (ufb != null && ufb.CurrentUser != null)
{
SetValue("CreatedByUserId", item, ufb.CurrentUser.Id);
SetValue("UpdatedByUserId", item, ufb.CurrentUser.Id);
}
SetValue("DateCreated", item, DateTime.Now);
SetValue("DateUpdated", item, DateTime.Now);
var newEntry = this.DbSet.Add(item);
this.Context.Database.Log = message => LogHandler.LogInfo(1111, message);
try
{
this.Context.SaveChanges();
}
catch (Exception ex)
{
LogHandler.LogInfo(2501, ex.Message);
}
BuildMetaData(item, true, true);
return newEntry;
}
catch (DbEntityValidationException dbEx)
{
// http://forums.asp.net/t/2014382.aspx?Validation+failed+for+one+or+more+entities+See+EntityValidationErrors+property+for+more+details+
string msg = string.Empty;
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
msg += validationError.PropertyName;
msg += "---";
msg += validationError.ErrorMessage;
msg += "||";
}
}
throw new Exception("7777 CREATE EntityValidationErrors: " + msg);
}
}
Here is how I am trying to call the create method for couple of Entities, can somebody please suggest me what am I doing wrong, any help please
public InspectionItem Create(InspectionItem inspectionItem)
{
try
{
//------------------------------------------------------
// save the indexes to the multiple categories,
// then clear the list of category objects in the
//------------------------------------------------------
List<int> inspectionCategoryIdlist = new List<int>();
foreach (var itemCat in inspectionItem.InspectionItemCategory)
{
int itemCatId = itemCat.ViolationTypeId;
inspectionCategoryIdlist.Add(itemCatId);
}
inspectionItem.InspectionItemCategory.Clear();
inspectionItem.InspectionItemNumber = "TEMP"; // just get past the Create
var saveInspectionItemCategories = inspectionItem.InspectionItemCategory;
inspectionItem.InspectionItemNumber = CalculateInspectionItemNumber(inspectionItem.InspectionItemId);
UnitOfWork.InspectionItemRepository.Create(inspectionItem);
if ((inspectionItem != null) && (inspectionItem.InspectionItemId != null) && (inspectionItem.InspectionItemId > 0))
foreach (var violationTypeId in inspectionCategoryIdlist)
{
var a = new InspectionItemViolationCategory();
a.InspectionItem = inspectionItem;
var violationType = new ViolationType();
violationType = UnitOfWork.ViolationTypeRepository.Find(violationTypeId);
a.ViolationType = violationType;
UnitOfWork.InspectionItemViolationCategoryRepository.Create(a);
}
return inspectionItem;
}
catch (Exception ex)
{
LogHandler.LogError(2101, "Commit Fail in Inspection Item Create", ex);
throw ex;
}
}
Any suggestion or code sample anything helps, thanks a lot.

how to call Call Async Methods in Parallel.ForEach loop properly [duplicate]

This question already has answers here:
Nesting await in Parallel.ForEach [duplicate]
(11 answers)
Closed 2 years ago.
how to call Call Async Methods in Parallel.ForEach loop properly.billDataService.SaveBillDetail and GetProfileDetails both are async methods.data saving in MongoDB in SaveBillDetail .
public async Task ConvertXMLFileToJSON()
{
try
{
if (Directory.Exists(_appSettings.DocumentsStorage))
{
int i = 1; //Test
bool exists = Directory.GetFiles(_appSettings.DocumentsStorage).Any(x => x.Equals(Path.Combine(_appSettings.DocumentsStorage, "Ready.txt"), StringComparison.OrdinalIgnoreCase)); //Need to check
if (exists)
{
Parallel.ForEach(System.IO.Directory.GetFiles(_appSettings.DocumentsStorage, "*.xml"), (currentFile) =>
{
try
{
XElement root = XElement.Load(currentFile); // or .Parse(string);
//Removing CDATA property from XElement.
XElement items = XElement.Parse(root.ToString().Replace("<![CDATA", "").Replace("]]>", "").Replace("[", ""));
//Removing XML_INFO Tag from XElement.
items.Elements("XML_INFO").Remove();
XmlDocument xmlDoc = new XmlDocument();
using (XmlReader xmlReader = items.CreateReader())
{
xmlDoc.Load(xmlReader);
}
var json = JsonConvert.SerializeXmlNode(xmlDoc);
billDetails obj = JsonConvert.DeserializeObject<billDetails>(json);
BillDetails billDetails = new BillDetails();
billDetails.AccountNumber = obj.BILL_INFO.BILL_RUN.ACCT_INFO.ACCT_CODE;
billDetails.MobileNumber = obj.BILL_INFO.BILL_RUN.ACCT_INFO.PRINCIPAL_NO.STR_PRINCIPAL_NO;
billDetails.BillDate = DateTime.ParseExact(obj.BILL_INFO.BILL_RUN.BILL_PROP.TO_DATE, "dd/MM/yyyy", CultureInfo.InvariantCulture);
billDetails.DueAmount = obj.BILL_INFO.BILL_RUN.ACCT_INFO.ACCT_BALANCE_TRACE.TOTAL_DUE;
billDetails.CustomerName = obj.BILL_INFO.BILL_RUN.CUST_INFO.CUST_NAME.FULL_NAME;
billDetails.InvoiceId = obj.BILL_INFO.BILL_RUN.BILL_PROP.INVOICE_ID;
billDetails.DueDate = DateTime.ParseExact(obj.BILL_INFO.BILL_RUN.BILL_PROP.DUE_DATE, "yyyyMMdd hh:mm:ss", CultureInfo.InvariantCulture);
billDetails.RepositoryName = "postpaid";
billDetails.BillRun = obj.BILL_INFO.BILL_RUN; //tempObj2.BILL_INFO.ToString().Remove(0, 1);
billDetails.ObjectId = Guid.NewGuid().ToString();
if (billDetails != null)
{
BillDataService billDataService = new BillDataService(_dbConfig);
Console.WriteLine("SaveBillDetail");
if (billDataService.SaveBillDetail(billDetails) != null)
{
Console.WriteLine("SaveBillDetail done");
GetProfileDetails(billDetails);
_logger?.LogInformation(i++ + " File Success");
Console.WriteLine(i++ + " File Success");
// File.Delete(file); //Delete File
}
}
}
catch (Exception ex)
{
_logger?.LogError(ex, "Error");
}
finally { }
});
}
}
}
catch (Exception ex)
{
_logger?.LogError(ex, "Error");
}
finally
{
}
}
public async Task GetProfileDetails(BillDetails billDetails)
{
try
{
ProfileService profileService = new ProfileService(_dbConfig);
var searchFilter = new SearchFilter
{
Filters = new List<Filter>()
};
if (!string.IsNullOrEmpty(billDetails.AccountNumber))
{
searchFilter.Filters.Add(new Filter() { PropertyName = "AccountNumber", Operator = Operator.Equals, Value = billDetails.AccountNumber, CaseSensitive = true });
}
if (searchFilter != null)
{
Profile profile = await profileService.GetProfiles(searchFilter);
if (profile != null)
{
await SendMailNotification(profile, billDetails);
}
else
{
_logger?.LogError("Profile Info not found");
}
}
}
catch (Exception ex)
{
_logger?.LogError(ex, "Error");
throw;
}
finally { }
}
normal for each loop I can able to call and save data in MongoDB.but Parallel.ForEach loop I cannot able to call the async method using await and data saving in mongo also not working.inside Parallel.ForEach loop I avoided using await of the front of the calling method.
You can change your code to be like below and wait for all the tasks to be completed.
var fileTasks = System.IO.Directory.GetFiles(_appSettings.DocumentsStorage, "*.xml").Select(async currentFile =>
{
try
{
XElement root = XElement.Load(currentFile); // or .Parse(string);
// rest o your code here
if (billDetails != null)
{
if (billDataService.SaveBillDetail(billDetails) != null)
{
Console.WriteLine("SaveBillDetail done");
await GetProfileDetails(billDetails);
}
}
}
catch(exception ex) { //log exeption }
});
await Task.WhenAll(fileTasks);

Get data from Mobile Service Table

I want get data from Azure. This is my code:
private async void FindPromotion()
{
MobileServiceCollection<Promotions, Promotions> result;
MobileServiceInvalidOperationException exception = null;
string _place = textInputPlace.Text;
if (_place!= null)
{
try
{
//lista obiektów Category
result = await todoTable2.Where(todoItem => todoItem.Place==_place)
.Select(todoItem => todoItem.Products, todoItem => todoItem.Description)
.ToCollectionAsync();
}
catch (MobileServiceInvalidOperationException ex)
{
exception = ex;
}
if (exception != null)
{
await new MessageDialog(exception.Message, "Can't find items").ShowAsync();
}
else
{
ListItems.ItemsSource = result.Distinct();
}
}
}
I have error:
No overload for method 'Select' takes 2 arguments.
Anybody know? Is another way to get this data?
This is how you can select multiple columns:
result = await todoTable2.Select(todoItem => new { todoItem.Products , todoItem.Description}).ToCollectionAsync();

EventStore duplicate commit exception

UPDATE:
We are getting getting System.Data.SqlClient.SqlException. The message is:
Violation of PRIMARY KEY constraint 'PK_Commits'. Cannot insert duplicate key in object 'dbo.Commits'.\r\nThe statement has been terminated
It seems like EventStore is using streamid and commitid as unique id.
We use event store to append events as below.
public bool TryAppend(object[] content)
{
if (content == null)
throw new ArgumentNullException("content");
try
{
using (var stream = m_storage.OpenStream(m_streamID, 0, int.MaxValue))
{
var versionInStore = stream.StreamRevision;
content.ToList().ForEach(m =>
{
var version = ++versionInStore;
var key = string.Format("{0}-{1:00000000}", m.GetType().Name, version);
var savedMessage = new SavedRecord(key, version, m);
stream.Add(new EventMessage { Body = savedMessage });
});
stream.CommitChanges(Guid.NewGuid());
}
return true;
}
catch (Exception e)
{
m_logger.LogError(e);
return false;
}
}
The configuration of EventStore is as below. We are using Sql Serer 2008 as persistance store.
return Wireup.Init()
.LogToOutputWindow()
.UsingSqlPersistence(m_connectionName)
.WithDialect(new MsSqlDialect())
.EnlistInAmbientTransaction() // two-phase commit
.InitializeStorageEngine()
.UsingJsonSerialization()
.Compress()
.UsingSynchronousDispatchScheduler()
.DispatchTo(new DelegateMessageDispatcher(DispatchCommit))
.Build();
Any ideas why are gettin the dupplicate commit exception?
Thanks
Have got the same issue; in my case it was probably because of different threads was adding different events to the stream with same id at the same time.
Have writtent the following code to be able to retry adding events:
private void TryAddEvent(IStoreEvents storeEvents, IUserEvent anEvent, Guid streamId)
{
var isCommitSuccessful = false;
for (var i = 0; i < 10 && !isCommitSuccessful; i++)
{
try
{
using (var stream = storeEvents.OpenStream(streamId, 0, int.MaxValue))
{
stream.Add(new EventMessage {Body = anEvent});
if (stream.UncommittedEvents.All(e => e.Body != anEvent))
{
stream.Add(new EventMessage {Body = anEvent});
}
stream.CommitChanges(Guid.NewGuid());
}
isCommitSuccessful = true;
}
catch (Exception ex)
{
if (!(ex is SqlException) && !(ex is ConcurrencyException))
{
throw;
}
using (var stream = storeEvents.OpenStream(streamId, 0, int.MaxValue))
{
if (stream.CommittedEvents.Any(e => e.Body == anEvent))
{
isCommitSuccessful = true;
}
}
}
}
if (!isCommitSuccessful)
{
throw new ConcurrencyException(String.Format("Cannot add {0} to event store", anEvent.GetType()));
}
}
Hope it would help.

Categories