StorageProgress Report function is not called by GetFileAsync - c#

I'm trying to download resources file for my game from Firebase Storage, and to show downloading progress. But I came to strange behavior of GetFileAsync function. The Report function of StorageProgress is not called periodically during file downloading how it is described in reference. Report function is called during saving to disk, after the file is placed into memory(downloaded). What I'm doing wrong?
string resourcesURL = "URL_TO_RESOURCE_FILE"; // https://firebasestorage.googleapis.com/......
public void UpdateProgress(float val)
{
labelProgress.text = Mathf.RoundToInt(val * 100f) + "%";
circleProgress.fillAmount = val;
}
void OnDownloadClick()
{
SetDownloadingView();
string saveToPath = GetParentFolder() + "/resources.bin";
StorageReference fileRef = FirebaseBackend.Instance.GetStorage().GetReferenceFromUrl(resourcesURL);
StorageProgress<Firebase.Storage.DownloadState> progressHandler = new StorageProgress<Firebase.Storage.DownloadState>(state =>
{
Debug.Log(String.Format ("Progress: {0} of {1} bytes transferred.", state.BytesTransferred, state.TotalByteCount));
UpdateProgress(state.BytesTransferred / state.TotalByteCount);
});
Task dwnTask = fileRef.GetFileAsync
(
saveToPath,
progressHandler,
CancellationToken.None
);
dwnTask.ContinueWith(resultTask =>
{
if (!resultTask.IsFaulted && !resultTask.IsCanceled)
{
ResetView();
Debug.Log("Download finished!");
}
else
{
ResetView();
Debug.Log("Download fail!");
}
});
}
Unity version is 5.5.0f3
Firebase Unity SDK version is 3.0.1

You may not be doing anything wrong at all.
According to this post, this is a Firebase bug that is to be addressed in the next Firebase update.

Try with an IEnumerator, this is my code with the storage progress working:
protected IEnumerator downloadObject(string target_file, string target_path, int item_index)
{
if (target_file != "")
{
FirebaseStorage storage = FirebaseStorage.DefaultInstance;
string local_url = target_path.Replace("\\", "/").Replace("//", "/");
StorageReference storage_ref =
storage.GetReferenceFromUrl(FB_Conf.gsURL + target_file);
Task task = null;
try
{
task = storage_ref.GetFileAsync(local_url,
new Firebase.Storage.StorageProgress<DownloadState>((DownloadState state) =>
{
// called periodically during the download
long tbyte = state.TotalByteCount;
file_progress = (float)state.BytesTransferred / (float)tbyte;
}), CancellationToken.None);
}
catch (Exception exc)
{
Debug.Log("Get file async error: " + exc.Message);
}
if (task != null)
{
yield return new WaitUntil(() => task.IsCompleted);
task.ContinueWith((resultTask) =>
{
if ((resultTask.IsFaulted) || (resultTask.IsCanceled))
{
error_count++;
string msg = (resultTask.IsCanceled) ? "Download error." : "";
if ((resultTask.Exception != null) &&
(resultTask.Exception.InnerExceptions.Count > 0) &&
(resultTask.Exception.InnerExceptions[0] is Firebase.Storage.StorageException))
msg = ((Firebase.Storage.StorageException)resultTask.Exception.InnerExceptions[0]).HttpResultCode.ToString();
else if (resultTask.Exception != null)
msg = resultTask.Exception.Message;
}
});
}
else
{
error_count++;
}
}
}

Related

Allow an account access to only one mobile app and browser on website

I'm doing a task that allow an account access to only one mobile app and browser on website(When login on other mobile app or browser on website, this current mobile app or browser website will return to login page when call APi). My idea is creating Dictionary> on AddSingleton Class to save userName and Token.
The request call to API will check whether this account and token are existed on Dictionary> or not. Everything work on local (dev) but when i deploy on server,
Dictionary> clear (dispose) all value saved before automatically .
Anybody know why or have any idea for this issue. Thanks all.
Declare On Startup:
services.AddSingleton<DictionaryAccount, DictionaryAccount>();
Event When Call Api On Startup:
OnTokenValidated = AdditionalValidation
Fuction AdditionalValidation on startup:
public Task AdditionalValidation(TokenValidatedContext context)
{
bool check = true;
var securityToken = context.SecurityToken as JwtSecurityToken;
var claim = securityToken.Claims.SingleOrDefault(t => t.Type == "unique_name");
//1 - web ; 2 - mobile
var platform = securityToken.Claims.SingleOrDefault(t => t.Type == "platform");
try
{
if (TurnOff != 1)
{
if (platform.Value != null)
{
try
{
int type = int.Parse(platform.Value);
string email = securityToken.Claims.SingleOrDefault(t => t.Type == "Email").Value;
if(!string.IsNullOrEmpty(email) && !string.IsNullOrEmpty(securityToken.RawData))
{
using (var serviceScope = _app.ApplicationServices.CreateScope())
{
var _context = serviceScope.ServiceProvider.GetRequiredService<DictionaryAccount>();
check = _context.CheckValidSession(type, email, securityToken.RawData, _logger);
}
}
}
catch (Exception e)
{
_logger.LogError("Fail login startUp " + e.ToString());
context.Response.StatusCode = (int)HttpStatusCode.RequestedRangeNotSatisfiable;
context.Fail("Failed additional validation");
}
}
if (!check)
{
context.Response.StatusCode = (int)HttpStatusCode.RequestedRangeNotSatisfiable;
context.Fail("Failed additional validation");
}
}
}
catch(Exception e)
{
_logger.LogError("Fail login startUp " + e.ToString());
context.Response.StatusCode = (int)HttpStatusCode.RequestedRangeNotSatisfiable;
context.Fail("Failed additional validation");
}
return Task.CompletedTask;
}
Function CheckValidSession:
public bool CheckValidSession(int type, string email, string token, ILogger<AuthController> _logger)
{
string outConnection;
try
{
//1 - web ; 2 - mobile
_logger.LogWarning("login write log email: " +email);
_logger.LogWarning("login write log type: " +type);
_logger.LogWarning("login write log token: " + token);
_logger.LogWarning("login write log list" + string.Join(",", accountListWebsite.Select(x => x.Key).ToArray()));
var item = accountListWebsite.Select(x => x.Value).ToList();
for (int i = 0; i < item.Count; i++)
{
_logger.LogWarning("Token In list: " + string.Join(",", accountListWebsite.Select(x => x.Value).ToList()[0].ToArray()));
}
if (type == 1)
{
if (accountListWebsite[email].TryGetValue(token, out outConnection))
{
_logger.LogWarning("return true");
return true;
}
}
else if(type == 2)
{
if (accountListMobile[email].TryGetValue(token, out outConnection))
{
return true;
}
}
return false;
}
catch(Exception e)
{
_logger.LogWarning("Exception return false " + e.ToString(), e.Message);
bool check = false;
return check;
}
}
Function CreateDictionaryAccountWeb: -> called this function when login success
public bool CreateDictionaryAccountWeb(string email, string token, int count, ILogger<AuthController> logger)
{
_logger = logger;
Count = count;
bool result = true;
try
{
lock (accountListWebsite)
{
HashSet<string> emails;
if (!accountListWebsite.TryGetValue(email, out emails))
{
emails = new HashSet<string>();
accountListWebsite.Add(email, emails);
}
_logger.LogWarning("login write log " + string.Join(",", accountListWebsite.Select(x => x.Key).ToArray()));
lock (accountListWebsite)
{
if (emails != null && emails.Count >= 0) {
if (!emails.Any(x => x.Contains(token))) {
if (emails.Count >= count)
{
var temp = emails.First();
if (temp != token)
emails.Remove(temp);
}
_logger.LogWarning("login token " + token);
emails.Add(token);
}
}
else
{
emails.Add(token);
}
}
}
}
catch (Exception e)
{
_logger.LogError("Fail login" + e.ToString());
result = false;
}
return result;
}
My Log:

create a file and upload the chunks to the in team drive from C#

I Have to Upload the file to my teamdrive, the file has been created to team drive but I can not upload the file chunks to it. So, please help to solve it.
On Writing a Chunk I am facing the Error of "The remote server returned an error: (404) Not Found."
I am getting the Teamdrive ID and the File ID which has been created.
/*** Creation of a File to Team Drive ***/
f_ObjFile.TeamDriveId = "/*TeamDrive ID*/";
try
{
f_ObjNewFile.Parents = f_ObjFile.Parents; // f_ObjFile = <Team Driv ID>
f_ObjNewFile.Name = f_ObjFile.Name;
f_ObjNewFile.MimeType = f_ObjFile.MimeType;
f_ObjNewFile.TeamDriveId = f_ObjFile.TeamDriveId;
f_CreateRequest = GoogleHelper.InvokeApiCall(() => { return this.DriveServiceObj.Files.Create(f_ObjNewFile); }, this);
if (f_CreateRequest != null)
{
f_CreateRequest.SupportsTeamDrives = true;
f_CreateRequest.Fields = "*";
f_ObjNewFile = GoogleHelper.InvokeApiCall(() => { return f_CreateRequest.Execute(); }, this);
}
f_ObjDocumentItem = new DocumentItem(UserEmailID, f_ObjNewFile);
f_ObjDocumentItem.ItemID = f_ObjNewFile.Id;
string f_Url = GoogleHelper.CreateChunkURL("https://www.googleapis.com/upload/drive/v3/files/{0}?uploadType=resumable", f_ObjNewFile.Id);
f_ObjDocumentItem.ChunkUploadURL = InitiateResumeRequest(f_Url, f_ObjNewFile.Id);
}
catch(Exception ex) { }
finally
{
f_ObjNewFile = null;
f_CreateRequest = null;
}
/* Writing the chunks to the file in TeamDrive */
try
{
httpRequest = GoogleHelper.CreateHttpWebRequestObj(f_ObjChunkData.ChunkUploadURL,true);
httpRequest.Method = GoogleConstant.PATCH;
httpRequest.ContentLength = f_ObjChunkData.FileData.Length;
httpRequest.SendChunked = true;
httpRequest.Headers["Content-Range"] = "bytes " + f_ObjChunkData.StartOffset +
"-" +
f_ObjChunkData.EndOffset + "/" +
f_ObjChunkData.FileSize.ToString();
using (System.IO.Stream f_ObjHttpStream = GoogleHelper.InvokeApiCall(() => { return httpRequest.GetRequestStream(); }, this))
{
if (f_ObjHttpStream != null)
{
System.IO.MemoryStream f_ChunkStream = null;
f_ChunkStream = new System.IO.MemoryStream(f_ObjChunkData.FileData);
f_ChunkStream.CopyTo(f_ObjHttpStream);
f_ObjHttpStream.Flush();
f_ObjHttpStream.Close();
f_ChunkStream.Close();
f_ChunkStream = null;
}
}
using (HttpWebResponse httpResponse = GoogleHelper.InvokeApiCall(() => { return (HttpWebResponse)(httpRequest.GetResponse()); }, this))
{
if (httpResponse != null)
{
if (httpResponse.StatusCode == HttpStatusCode.OK)
{
httpResponse.Close();
}
}
}
}
catch (Exception ex) { }
In Followin Line :
string f_Url = GoogleHelper.CreateChunkURL("https://www.googleapis.com/upload/drive/v3/files/{0}?uploadType=resumable", f_ObjNewFile.Id);
Insted Of
"https://www.googleapis.com/upload/drive/v3/files/{0}?uploadType=resumable"
Use following URL :
https://www.googleapis.com/upload/drive/v3/files/{0}?uploadType=resumable&supportsTeamDrives=true
and its Done...
Now you can upload the chunks...

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( ... );
}
}
}
}
}
}

PHAssetChangeRequest Cocoa error -1

I need to save downloaded video to gallery on iPhone, but getting error:
The operation couldnt be completed. (Cocoa error -1/)
Tried also to do this through webClient.DownloadDataAsync(), getting same error. Here is my listing:
public async Task<string> DownloadFile(string fileUri)
{
var tcs = new TaskCompletionSource<string>();
string fileName = fileUri.Split('/').Last();
var documentsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string videoFileName = System.IO.Path.Combine(documentsDirectory, fileName);
var webClient = new WebClient();
webClient.DownloadFileCompleted += (s, e) =>
{
var authStatus = await PHPhotoLibrary.RequestAuthorizationAsync();
if(authStatus == PHAuthorizationStatus.Authorized){
var fetchOptions = new PHFetchOptions();
var collections = PHAssetCollection.FetchAssetCollections(PHAssetCollectionType.Album, PHAssetCollectionSubtype.Any, fetchOptions);
collection = collections.firstObject as PHAssetCollection;
PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() => {
var assetCreationRequest = PHAssetChangeRequest.FromVideo(NSUrl.FromFileName(videoFileName));
var assetPlaceholder = assetCreationRequest.PlaceholderForCreatedAsset;
var albumChangeRequest = PHAssetCollectionChangeRequest.ChangeRequest(collection);
albumChangeRequest.AddAssets(new PHObject[] { assetPlaceholder });
}, delegate (bool status, NSError error) {
if (status)
{
Console.Write("Video added");
tcs.SetResult("success");
}
});
}
try
{
webClient.DownloadFileAsync(new Uri(fileUri), videoFileName);
}
catch (Exception e)
{
tcs.SetException(e);
}
return await tcs.Task;
}
Any help would be appreciated. Thanks.
(Cocoa error -1/)
Are you sure that you actually have valid data/mp4 from your download?
Are you using SSL (https), otherwise have you applied for an ATS exception in your info.plist?
Check the phone/simulator console output for errors concerning ATS
Note: I typically use NSUrlSession directly to avoid the HttpClient wrapper...
Example using NSUrlSession task:
var videoURL = NSUrl.FromString(urlString);
var videoPath = NSFileManager.DefaultManager.GetUrls(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User)[0];
NSUrlSession.SharedSession.CreateDownloadTask(videoURL, (location, response, createTaskError) =>
{
if (location != null && createTaskError == null)
{
var destinationURL = videoPath.Append(response?.SuggestedFilename ?? videoURL.LastPathComponent, false);
// If file exists, it is already downloaded, but for debugging, delete it...
if (NSFileManager.DefaultManager.FileExists(destinationURL.Path)) NSFileManager.DefaultManager.Remove(destinationURL, out var deleteError);
NSFileManager.DefaultManager.Move(location, destinationURL, out var moveError);
if (moveError == null)
{
PHPhotoLibrary.RequestAuthorization((status) =>
{
if (status.HasFlag(PHAuthorizationStatus.Authorized))
{
PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() =>
{
PHAssetChangeRequest.FromVideo(destinationURL);
}, (complete, requestError) =>
{
if (!complete && requestError != null)
Console.WriteLine(requestError);
});
}
});
}
else
Console.WriteLine(moveError);
}
else
Console.WriteLine(createTaskError);
}).Resume();
Note: To confirm your code, try using a known valid secure URL source:
https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4 via “Video For Everybody” Test Page

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