How to break from the Catch block after throwing BadRequestException using C# - 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;
}

Related

Async call inside foreach does not execute following switch

I don't know the async/await mechanism very well and I searched on Google, but without finding an acceptable answer.
I have a question about the code below:
When using .Result, the switch() block is executed.
// Here the flow starts - the callee is a VueJS axios ajax call
[Route("ChangeStatusOrders/ValidateStatus")]
[HttpPost]
public async Task<ActionResult> ValidateStatus(OrdersToBeProcessed model)
{
bool success = false;
string message = "";
try
{
model.ReturnData = await _statusBusiness.Validate(model);
success = true;
return Json(new { Success = true, ReturnData = model.ReturnData }, JsonRequestBehavior.AllowGet);
}
catch (ArgumentException ex)
{
message = $"Bad Request {ex.Message}";
_log.Error(message);
Response.StatusCode = 400;
return Json(new { Success = false, ErrorMessage = message }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
message = $"Spomething wrong message here - {ex.Message}";
_log.Error(message);
Response.StatusCode = 500;
return Json(new { Success = false, ErrorMessage = message }, JsonRequestBehavior.AllowGet);
}
finally
{
var param = new
{
model.Orders,
model.NotesText,
model.CompanyID,
model.CompanyName,
model.NewStatus,
model.ReturnData,
model.CodeType,
model.UserID,
model.isInternalUser,
Message = message
};
LogUserAction(ActionType.ChangeStatusOrders, success, param);
}
}
private readonly IDictionary<bool, Func<List<string>, int, List<Order>>> _dic;
constructor()
{
// below methods are not async
_dic = new Dictionary<bool, Func<List<string>, int, List<Pedido>>>
{
{ true, (p) => _orderRepository.GetByID(p) },
{ false, (p) => _orderRepository.GetByCompanyID(p) }
};
}
public async Task<ProcessResults> Validate(OrdersToBeProcessed model)
{
ProcessResults result = new ProcessResults();
bool useOurID = (model.CodeType == 1);
return await Task.Run(() =>
{
try
{
List<string> ordersList = SplitOrders(model.Orders);
List<string> buffer = ordersList.Distinct().ToList();
List<Order> ordersList = new List<Order>(buffer.Count());
buffer.ForEach(item =>
{
var tmp = new Order();
if (useOurID)
tmp.ID = Convert.ToInt64(item);
else
tmp.CompanyId = item;
orderList.Add(tmp);
});
List<Order> foundOrders = _dic[useOurId](buffer);
result.SuccessfullOrders = new List<ProcessedOrder>();
result.NotFoundOrders = new List<ProcessedOrder>();
result.NotAllowedOrders = new List<ProcessedOrder>();
// merge the list of order's id with those one's found in database
List<Orders> union = foundOrders.MergeAndReplace(ordersList).ToList();
foreach (var item in union)
{
ProcessedOrder ret = ValidateAsync(item).Result; // <-- here is an Async call
switch (ret.ProcessedResult)
{
case ProcessedResultEnum.CanBeProcessed:
result.SuccessfullOrders.Add(ret);
break;
case ProcessedResultEnum.OrderNotFound:
result.NotFoundOrders.Add(ret);
break;
case ProcessedResultEnum.CannotBeProcessed:
result.NotAllowedOrders.Add(ret);
break;
}
}
return result;
});
private async Task<Order> ValidateAsync(Order item)
{
ProcessedOrder ret = new ProcessedOrder();
ret.CompanyID = item.CompanyID;
ret.Name = item.Name;
ret.ID = item.ID;
ret.Status = (item.Status?.ID).ToString();
var queueOrderItems = await _queueOrderService.SearchByOrderIdAsync(item.ID);
if (item.ID == 0 || String.IsNullOrEmpty(iitem.CodigoEntidade))
{
ret.Message = "Order not found in database.";
ret.Result = ProcessedResultEnum.OrderNotFound;
}
else if (item.Status == null || queueOrderItems == null)
{
ret.Message = "Order Cannot Be Processed";
ret.Result = ProcessedResultEnum.CannotBeProcessed;
}
else
{
ret.Message = "Order Can Be Processed";
ret.Result = ProcessedResultEnum.CanBeProcessed;
}
return ret;
}
public async Task<SearchBiIdResult> SearchByOrderIdAsync(long orderID )
{
SearchByIDResult ret;
SearchByIDRequest request = new SearchByIDRequest() { OrderID = orderID };
// calls a WCF async method descibed below
SearchByIDResponse response = await _queueOrderItemsClient.SearchByIDAsync(request);
ret = _mapper.Map<SearchByIDResponse>(response);
return ret;
}
// WCF async method definition (in reference.cs)
public System.Threading.Tasks.Task<UI.Services.Business.QueuesService.SearchByIDResponse> SearchByIDAsync(UI.Services.Business.QueuesService.SearchByIDRequest request) {
return base.Channel.SearchByIDAsync(request);
}
However, if I replace .Result with
ProcessedOrder ret = await ValidateAsync(item);
the loop immediately returns back up to the foreach statement, without executing the switch() block.
Can someone explain to me why this behavior?
I changed
return await Task.Run(() =>
to
return await Task.Run(async () =>
and the foreach block behaved as expected.

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);

How to detect edited or deleted messages on telegram TLSharp

I am trying to detect which message is edited or deleted on a subscribed channel on telegram with TLSharp library in c#.
1- in a while(true) loop I am getting latest updates.
2- when I delete or edit a message for test, I receive TLUpdateChannelTooLong only.
3- then I use client.GetHistoryAsync function to get channel messages, and check their EditDate.
But I don't know how much should I go deep in history and I can not find deleted message with this code easily.
Is there any solution to find deleted/edited messages easy and safe?
Part of my code:
state = await client.SendRequestAsync<TLState>(new TLRequestGetState());
while (true)
{
await Task.Delay(1000);
var req = new TLRequestGetDifference() { Date = state.Date, Pts = state.Pts, Qts = state.Qts };
TLDifference diff = null;
try
{
diff = await client.SendRequestAsync<TLAbsDifference>(req) as TLDifference;
}
catch (Exception ex)
{
HandleThisException(ex);
}
//--
if (diff != null)
{
state = await client.SendRequestAsync<TLState>(new TLRequestGetState());
foreach (var upd in diff.OtherUpdates.OfType<TLUpdateNewChannelMessage>())
{
var tm = (upd.Message as TLMessage);
if (tm == null) { continue; } // ?
var textMessage = tm.Message;
if (tm.Media != null)
{
if (tm.Media.GetType().ToString() == "TeleSharp.TL.TLMessageMediaPhoto")
{
var tLMessageMediaPhoto = (tm.Media as TLMessageMediaPhoto);
textMessage = tLMessageMediaPhoto.Caption;
}
}
try
{
var from = (tm.ToId as TLPeerChannel).ChannelId;
long replyTo = tm.ReplyToMsgId == null ? 0 : (long)tm.ReplyToMsgId;
await AnalyzeNewMessage( ... );
}
catch (Exception exParsing)
{
HandleThisException(exParsing);
}
}
// Checking Edited/Deleted Messages
foreach(var upLong in diff.OtherUpdates.OfType<TLUpdateChannelTooLong>())
{
TLChannel theChat = null;
foreach(var chat in diff.Chats.OfType<TLChannel>())
{
if(chat.Id == upLong.ChannelId) { theChat = chat; break; }
}
if (theChat != null)
{
var x = await client.GetHistoryAsync(
new TLInputPeerChannel { ChannelId = theChat.Id, AccessHash = (long)theChat.AccessHash },
0,-1,2
); // checking only 2 last messages!
var ChMsgs = x as TLChannelMessages;
foreach (var msg in ChMsgs.Messages.OfType<TLMessage>())
{
if(msg.EditDate != null)
{
var txt = msg.Message;
if (msg.Media != null)
{
if (msg.Media.GetType().ToString() == "TeleSharp.TL.TLMessageMediaPhoto")
{
txt = (msg.Media as TLMessageMediaPhoto).Caption;
}
}
await AnalyzeEditedMessage( ... );
}
}
}
}
}
}

Async Await Stored Procedure

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

How to call a method in .cs file which was implemented in code behind?

I have a button click event in code behind file as follows:
protected void btnArchive_Click(object sender, EventArgs e)
{
try
{
if (projectId == 0)
{
return;
}
Int32 serverPathId = 0;
ProjectArchiveResponse archiveResponse;
if (!int.TryParse(this.ddlSourceServer.SelectedValue, out serverPathId))
return;
if (string.IsNullOrEmpty(hidFileCount.Value))
{
this.ShowMsg(this.divMessage, Resources.Resource.ProjectFileArchiveNotAllowed, MessageType.Failed);
//The project files couldn't be archived until archive operation was completed.
return;
}
ProjectManager projectManager = new ProjectManager(null, BasePage.GetCurrentUser(), null) { IsServiceCall = false};
try
{
archiveResponse = projectManager.StartProjectArchive(projectId, false, () =>
{
foreach (Control control in tdFileList.Controls.Cast<Control>())
{
if (control is Dell.AFP.UserControl.ProjectFileListBaseControl)
{
((ProjectFileListBaseControl)control).Refresh();
}
}
}, false);
if (archiveResponse.MassivePackageID > 0)
{
this.ViewState["transferPackageId"] = archiveResponse.MassivePackageID;
PopupMonitor(archiveResponse.MassivePackageID);
}
//handled for any erorrs while submitting massive package or any unhandled exceptions will be taken care here
if (archiveResponse._CustomError != null && !string.IsNullOrEmpty(archiveResponse._CustomError.Erorrmessage))
{
if (!archiveResponse._CustomError._Erorrtype.Equals(MessageType.Info))
logger.ErrorFormat("Error occurred with details : {0}", archiveResponse._CustomError.Erorrmessage);
ShowMsg(divMessage, archiveResponse._CustomError.Erorrmessage, (MessageType)archiveResponse._CustomError._Erorrtype);
}
}
catch (KnownErrorException ke)
{
//logger.Fatal("UnExpected exception occured. Exception Details " + ke.Message);
logger.Fatal(ke.Message);
if (ke.Error.Type.Equals(DELL.AFP.Management.Exceptions.ErrorType.Warning))
this.ShowMsg(this.divMessage, ke.Message, MessageType.Info);
else
this.ShowMsg(this.divMessage, ke.Message, MessageType.Failed);
}
catch (Exception ke)
{
logger.ErrorFormat("UnExpected exception has occured with details : {0} - {1}", ke.Message, ke.StackTrace);
//ShowMsg(divMessage, "UnExpected exception has occured. Details are logged. Please try after sometime", MessageType.Failed);
ShowMsg(divMessage,ke.Message, MessageType.Failed);
}
}
In this event I am calling a method StartProjectArchive which is in ProjectManager.cs file
StartProjectArchive method in ProjectManager.cs is as follows:
public ProjectArchiveResponse StartProjectArchive(int projectID, bool promoteAfterArchive, Action uiRefresh, bool waitTillTransfered, string archiveNotificationUrl = null)
{
ProjectArchiveResponse projectArchiveResponse = new ProjectArchiveResponse() { ProjectID = projectID, MassivePackageID = -1 };
string sourceServerPath = String.Empty;
int packageID =0;
Int32 sourceServerPathID = GetSourceServerPath(projectID, out sourceServerPath);
var filesWhichNeedsToBeArchived = GetFilesWhichNeedsToBeArchived(projectID, sourceServerPathID, uiRefresh);
if (objFilesNotInSourceServer != null && objFilesNotInSourceServer.Count > 0)
KnownErrorException.Throw("ePRJARCMISSFILE01", string.Join(",", objFilesNotInSourceServer.ToArray()));
if (filesWhichNeedsToBeArchived != null)
{
MassiveServiceClientProxy proxy = new MassiveServiceClientProxy();
Dictionary<string, string> files = new Dictionary<string, string>();
filesWhichNeedsToBeArchived.Select(file => new
{
SourcePath = file.FileName,
DestinationPath = Path.Combine(ConfigurationManager.AppSettings["ArchiveProcessPrefixFolder"],
Path.GetDirectoryName(file.FileName), Path.GetFileName(file.FileName),
projectFilelist.Where(pf => string.Compare(pf.FileName, file.FileName, true) == 0).First().VersionID.ToString(),
Path.GetFileName(file.FileName))
}).ToList().
ForEach(file =>
{
if (!files.ContainsKey(file.SourcePath))
files.Add(file.SourcePath, file.DestinationPath);
});
if (files.Count > 0)
{
string packageDescription = "AFP 4.0: " + projectID.ToString(),
targetServerGroupName = archiveServer.MassiveServerGroupName,
userSuppliedId = "AFP 4.0: " + EndUserInfo.UserName;
try
{
packageID = proxy.SubmitPackageWithDestinationPath(files, packageDescription, new[] { sourceServerPath },
targetServerGroupName, userSuppliedId, MassiveService.MassivePriority.URGENT, true);
}
catch (Exception ex)
{
if (IsServiceCall == true)
KnownErrorException.Throw("wPRJARCMASER01");
else
return new ProjectArchiveResponse() { _CustomError = new CustomError { _Erorrtype = Model.ErrorType.Failed, Erorrmessage = ex.Message } };
}
if (packageID > 0)
{
ProjectFileBizManager projectFileBM = new ProjectFileBizManager();
projectFileBM.InsertArchiveTransferPackageByProjectFileList(
GetProjectFileIDsByFileName(projectID, filesWhichNeedsToBeArchived.Select(file => file.FileName).ToArray()), filesWhichNeedsToBeArchived.Select(file => file.FileName).ToArray(), packageID, projectID, EndUserInfo.UserId);
TransferPackageBizManager transferPackageBM = new TransferPackageBizManager();
if (promoteAfterArchive)
{
transferPackageBM.UpdateTransferPackageFeature(packageID, promoteAfterArchive);
}
projectArchiveResponse.MassivePackageID = packageID;
if (waitTillTransfered)
{
Task<ProjectArchiveResponse> mainTask = Task<ProjectArchiveResponse>.Factory.StartNew(
() =>
{
Task<Enums.TransferStatusEnum> packageTransfer = Task<Enums.TransferStatusEnum>.Factory.StartNew(
() =>
{
try
{
TransferPackage transferPackage = null;
while (true)
{
transferPackage = transferPackageBM.GetTransferPackage(packageID);
if (transferPackage.TransferStatus.TransferStatusId == (int)Enums.TransferStatusEnum.Submitted || transferPackage.TransferStatus.TransferStatusId == (int)Enums.TransferStatusEnum.Transferring)
Thread.Sleep(8000);
else
break;
}
logger.DebugFormat("Massive package status : {0} for Package : {1}", (Enums.TransferStatusEnum)transferPackage.TransferStatus.TransferStatusId, transferPackage.TransferPackageId);
return (Enums.TransferStatusEnum)transferPackage.TransferStatus.TransferStatusId;
}
catch (Exception exp)
{
logger.ErrorFormat("Project Archive Error, while trying to find massive package status : {0}", exp);
return Enums.TransferStatusEnum.Submitted;
}
});
try
{
Int32 timeOutInMins = (ConfigurationManager.AppSettings["ProjectArchive_PackageMonitorTimeoutInMinutes"] == null) ? 60 :
Convert.ToInt32(ConfigurationManager.AppSettings["ProjectArchive_PackageMonitorTimeoutInMinutes"]);
if (!Task.WaitAll(new Task[] { packageTransfer }, timeOutInMins * 60 * 1000))
{
projectArchiveResponse.Timedout = true;
projectArchiveResponse.TransferStatus = Enums.TransferStatusEnum.Submitted;
}
else
projectArchiveResponse.TransferStatus = packageTransfer.Result;
logger.DebugFormat("Project Archive Response, Project ID: {0}\n Package ID : {1},\n IsTimedout : {2},\n Timeout value : {3} minutes, \n Transfer Status : {4}", projectArchiveResponse.ProjectID, projectArchiveResponse.MassivePackageID, projectArchiveResponse.Timedout, timeOutInMins, projectArchiveResponse.TransferStatus);
}
catch (Exception exp)
{
logger.ErrorFormat("Project Archive Error, while waiting to fetch massive package status : {0}", exp);
}
return projectArchiveResponse;
});
if (!string.IsNullOrEmpty(archiveNotificationUrl))
{
mainTask.ContinueWith((a) =>
{
try
{
AFPArchiveNotifyProxy archiveNotification = new AFPArchiveNotifyProxy();
ArchiveNotificationService.ProjectArchiveResponse archiveResponse = new ArchiveNotificationService.ProjectArchiveResponse()
{
MassivePackageID = a.Result.MassivePackageID,
ProjectID = a.Result.ProjectID,
IsTimedout = a.Result.Timedout,
ArchiveStatus = (Enum.Parse(typeof(ArchiveNotificationService.ArchiveStatusEnum), (a.Result.TransferStatus.ToString())) as ArchiveNotificationService.ArchiveStatusEnum?).Value
};
MassiveServiceClientProxy massiveServiceClientProxy = new MassiveServiceClientProxy();
FileTransferRequest[] fileTransferRequests = massiveServiceClientProxy.GetFileStatus(a.Result.MassivePackageID);
archiveResponse.Files = fileTransferRequests.Select(f => f.FileName).ToArray();
archiveNotification.ProjectArchiveUpdate(archiveNotificationUrl, archiveResponse);
logger.DebugFormat("Project Archive Response Notification, Project ID: {0}\n Package ID : {1},\n IsTimedout : {2},\n Archive Status :{3},\n Notification Url : {4},\n Total Files : {5}", archiveResponse.ProjectID, archiveResponse.MassivePackageID, archiveResponse.IsTimedout, archiveResponse.ArchiveStatus, archiveNotificationUrl, archiveResponse.Files.Count());
logger.DebugFormat("Package ID : {0}, Files : {1}", archiveResponse.MassivePackageID, string.Join(",", archiveResponse.Files.ToArray()));
}
catch (Exception exp)
{
logger.ErrorFormat("Project Archive Error, while invoking archive notification : {0}", exp);
}
});
projectArchiveResponse.TransferStatus = Enums.TransferStatusEnum.Submitted;
return projectArchiveResponse;
}
else
{
mainTask.Wait();
}
}
}
else
{
if (IsServiceCall == true)
KnownErrorException.Throw("ePRJARCMASS01");
else
return new ProjectArchiveResponse() { _CustomError = new CustomError { _Erorrtype = Model.ErrorType.Failed, Erorrmessage = "Massive has not returned the massive packageid" } };
}
}
else
{
// this.ShowMsg(this.divMessage, Resources.Resource.NoFilesToArchive, MessageType.Info);
if (IsServiceCall == true)
KnownErrorException.Throw("wPRJARCNOFILES01");
else
return new ProjectArchiveResponse() { _CustomError = new CustomError { _Erorrtype = Model.ErrorType.Info, Erorrmessage = "There are no files to archive" } };
}
}
return projectArchiveResponse;
}
In this we are taking a parameter as "Action uiRefresh" . we are calling this uiRefresh as method in GetFilesWhichNeedsToBeArchived which was in startArchiveProject method. This Refresh method in tunrn calls the method in code behind file. This was passed as a control when we are invoking startArchiveProject in code behind file. Now I have one more thing which I need to implement. I have a method Pop-Up files in code behind file. I need to call that in ProjectManager.cs class inside the Method GetFilesWhichNeedsTobeArchive. In that pop-up I will have a button and checkboxes. Upon the selection user I need to get the details from pop-up and then I have to continue with the remaining execution in ProjectManger.cs page.
Can someone help on this?
Assuming that you have a button named btnArchive then the add click event subscription, pointing to the method you have (which looks like click-event handle proc)
btnArchive.Click+=(s,e)=>btnArchive_Click(s,e);
Regards

Categories