How to detect edited or deleted messages on telegram TLSharp - c#

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

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

Is there a C# API to regenerate Shared Access Keys for an Azure Service Bus Namespace?

I've found APIs to regenerate keys for queues and topics, like:
TopicDescription topicDescription = namespaceManager.GetTopic(topicName);
SharedAccessAuthorizationRule rule;
bool topicSuccess = topicDescription.Authorization.TryGetSharedAccessAuthorizationRule("RootManageSharedAccessKey", out rule);
if (topicSuccess)
{
string newkey = SharedAccessAuthorizationRule.GenerateRandomKey();
rule.PrimaryKey = newkey;
namespaceManager.UpdateTopic(topicDescription);
}
The docs online claim that "you can configure the SharedAccessAuthorizationRule rule on the Service Bus namespaces, queues, or topics", however I can only find the C# API for queues and topics. I found a REST API for the namespace level, but nothing else.
Is there a supported way to regenerate the namespace-level keys?
You can regenerate the namespace key using Microsoft.Azure.Management.ServiceBus.Fluent library.
There is a method RegenerateKeysAsync available in this library to regenerate the access keys of the namespace.
All the namespace level operations can be done using this library.
You can follow this code repo for examples
Azure SDK for .NET
below code you would be interested in
public async Task<AzureOperationResponse<AccessKeys>> RegenerateKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, RegenerateAccessKeyParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
}
}
if (namespaceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName");
}
if (namespaceName != null)
{
if (namespaceName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50);
}
if (namespaceName.Length < 6)
{
throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6);
}
}
if (authorizationRuleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "authorizationRuleName");
}
if (authorizationRuleName != null)
{
if (authorizationRuleName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "authorizationRuleName", 50);
}
if (authorizationRuleName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "authorizationRuleName", 1);
}
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (parameters != null)
{
parameters.Validate();
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("namespaceName", namespaceName);
tracingParameters.Add("authorizationRuleName", authorizationRuleName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "RegenerateKeys", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}/regenerateKeys").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName));
_url = _url.Replace("{authorizationRuleName}", System.Uri.EscapeDataString(authorizationRuleName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<AccessKeys>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<AccessKeys>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
Hope it helps.
MV

Issue with System.Threading.Tasks.Task.Factory.StartNew() in UWP?

I am working on Windows 10 UWP app and my requirement is to upload 5 images on the server with unique value. So, I have used System.Threading.Tasks.Task.Factory.StartNew().Now, when I checked while debugging, I found that randomly sometimes for 2 images, it sends same unique key. Can someone suggest is it better to use System.Threading.Tasks.Task.Factory.StartNew()?
All the images are sent using a web service. My sample code for this is following
WebServiceUtility serviceUtility = new WebServiceUtility();
List<System.Threading.Tasks.Task> tasks = new List<System.Threading.Tasks.Task>();
var cancelSource = new CancellationTokenSource();
cancellationToken = cancelSource.Token;
System.Threading.Tasks.Task currentTask = null;
List<System.Threading.Tasks.Task> uploadTasks = new List<System.Threading.Tasks.Task>();
List<string> uploadedImageIdList = new List<string>();
foreach (var image in _imageCollection)
{
if (!cancellationToken.IsCancellationRequested)
{
currentTask = await System.Threading.Tasks.Task.Factory.StartNew(async () =>
{
string imageName = string.Empty;
string imagePath = string.Empty;
if (image.IsEvidenceImage)
{
imageName = image.EvidencePath.Split('\\')[1];
imagePath = image.EvidencePath;
}
else
{
imageName = image.EvidencePath.Split('#')[1].Split('\\')[1];
imagePath = image.EvidencePath.Split('#')[1];
}
byte[] _imageAsByteArray = await GetEvidenceFromIsoStore(imagePath);
if (null != _imageAsByteArray && _imageAsByteArray.Length > 0)
{
IRestResponse response = await serviceUtility.UploadImage
(_imageAsByteArray, imageName,
new RequestDataGenerator().generateRequestDataForMediaUpload(
(null != _imageItem.I_IS_PRIMARY && "1".Equals(_imageItem.I_IS_PRIMARY) ? "1" : "0"),
evidenceName
));
if (response != null && response.RawBytes.Length > 0)
{
var successMessage = MCSExtensions.CheckWebserviceResponseCode(response.StatusCode);
if (successMessage.Equals(Constants.STATUS_CODE_SUCCESS))
{
byte[] decryptedevidenceresponse = WebserviceED.finaldecryptedresponse(response.RawBytes);
string responseString = Encoding.UTF8.GetString(decryptedevidenceresponse, 0, decryptedevidenceresponse.Length);
JObject reponseObject = JObject.Parse(responseString);
//Debug.WriteLine("Evidence Upload Response : " + Environment.NewLine);
uploadedimageIdList.Add(reponseObject["P_RET_ID"].ToString());
try
{
if (image.IsEvidenceImage)
{
if (await FileExists(image.EvidencePath))
{
StorageFile file = await localFolder.GetFileAsync(image.EvidencePath);
await file.DeleteAsync();
}
}
else
{
string[] evidenceMedia = image.EvidencePath.Split('#');
foreach (string evidenceItem in evidenceMedia)
{
if (await FileExists(evidenceItem))
{
StorageFile file = await localFolder.GetFileAsync(evidenceItem);
await file.DeleteAsync();
}
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
else
{
UserMessageUtil.ShowMessage(successMessage);
}
}
}
}, cancellationToken);
uploadTasks.Add(currentTask);
}
}
await System.Threading.Tasks.Task.WhenAll(uploadTasks.ToArray());
Just make it a separate method:
...
foreach (var image in _imageCollection)
{
if (!cancellationToken.IsCancellationRequested)
{
currentTask = UploadAsync(...);
uploadTasks.Add(currentTask);
}
}
await Task.WhenAll(uploadTasks);
async Task UploadAsync(...)
{
string imageName = string.Empty;
string imagePath = string.Empty;
...
}
Or, a bit more simply at the call site:
...
var uploadTasks = _imageCollection.Select(x => UploadAsync(...));
await Task.WhenAll(uploadTasks);

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

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