// Token: 0x06001CBB RID: 7355 RVA: 0x000A56CC File Offset: 0x000A38CC
 private void CreateMutexFailed(Exception e)
 {
     OwaDiagnostics.LogEvent(ClientsEventLogConstants.Tuple_TranscodingManagerInitializationFailed, string.Empty, new object[]
     {
         e.Message
     });
     throw new TranscodingFatalFaultException("Create Mutex for active transcoding service com object failed.", e, this);
 }
Exemple #2
0
 // Token: 0x06002827 RID: 10279 RVA: 0x00094998 File Offset: 0x00092B98
 private static void LogManifestExceptionToEventLogs(string fileName, Exception exception)
 {
     ExTraceGlobals.CoreTracer.TraceError <Type, string, Exception>(0L, "Exception {0} loading manifest {1}. Details: {2}", exception.GetType(), fileName, exception);
     OwaDiagnostics.LogEvent(ClientsEventLogConstants.Tuple_OwaManifestInvalid, string.Empty, new object[]
     {
         fileName,
         exception
     });
 }
 // Token: 0x06001BFF RID: 7167 RVA: 0x0006D71C File Offset: 0x0006B91C
 private static void SendInvitationMessage(UserContext userContext, ExchangePrincipal exchangePrincipal, string user, string location, string invitationLink)
 {
     try
     {
         OwaDiagnostics.SendWatsonReportsForGrayExceptions(delegate()
         {
             if (string.IsNullOrEmpty(user))
             {
                 throw new ArgumentNullException("user", "User name cannot be null when sending invite!");
             }
             if (string.IsNullOrEmpty(invitationLink))
             {
                 throw new ArgumentNullException("invitationLink", "InvitationLink cannot be null when sending invite!");
             }
             if (string.IsNullOrEmpty(location))
             {
                 throw new ArgumentNullException("location", "Document location cannot be null when sending invite!");
             }
             try
             {
                 string fileNameFromLocation = UpdateAttachmentPermissions.GetFileNameFromLocation(location);
                 userContext.LockAndReconnectMailboxSession();
                 MessageItem messageItem = MessageItem.Create(userContext.MailboxSession, userContext.MailboxSession.GetDefaultFolderId(DefaultFolderType.Inbox));
                 messageItem.From        = new Participant(exchangePrincipal);
                 messageItem.Sender      = messageItem.From;
                 messageItem.Subject     = string.Format(Strings.GuestSharingInvitationSubject, exchangePrincipal.MailboxInfo.DisplayName, fileNameFromLocation);
                 messageItem.IsDraft     = false;
                 messageItem.IsRead      = false;
                 messageItem.Recipients.Add(new Participant(user, user, "SMTP"));
                 string bodyContent = AttachmentMessageBodyGenerator.GenerateBodyForInvitation(fileNameFromLocation, invitationLink);
                 UpdateAttachmentPermissions.SetItemBody(messageItem, BodyFormat.TextHtml, bodyContent);
                 messageItem.SendWithoutSavingMessage();
             }
             catch (InvalidRecipientsException ex2)
             {
                 ExTraceGlobals.AttachmentHandlingTracer.TraceError <string>(0L, "[UpdateAttachmentPermissions : SendInvitationMessage] Exception happened when trying to send the invitation message : {0}", ex2.StackTrace);
             }
             finally
             {
                 if (userContext.MailboxSessionLockedByCurrentThread())
                 {
                     userContext.UnlockAndDisconnectMailboxSession();
                 }
             }
         });
     }
     catch (GrayException ex)
     {
         ExTraceGlobals.AttachmentHandlingTracer.TraceError <string>(0L, "[UpdateAttachmentPermissions : SendInvitationMessage] Exception happened when trying to send the invitation message : {0}", ex.StackTrace);
     }
 }
        // Token: 0x06001CB9 RID: 7353 RVA: 0x000A52D8 File Offset: 0x000A34D8
        private void OnCreateWorkerDelegate(IComWorker <ITranscoder> worker, object requestParameters)
        {
            ITranscoder worker2 = worker.Worker;

            if (worker2 == null)
            {
                OwaDiagnostics.LogEvent(ClientsEventLogConstants.Tuple_TranscodingWorkerInitializationFailed, string.Empty, new object[]
                {
                    string.Empty
                });
                throw new TranscodingFatalFaultException("TranscodingTaskManager failed to get ITranscoder interface", null, this);
            }
            TranscodingInitOption initOption = default(TranscodingInitOption);

            initOption.MaxOutputSize         = this.maxOutputSize;
            initOption.RowNumberPerExcelPage = this.rowNumberInExcel;
            initOption.HtmlOutputFormat      = this.htmlFormat;
            initOption.IsImageMode           = this.isImageMode;
            TranscodeErrorCode transcodeErrorCode = TranscodeErrorCode.Succeeded;

            try
            {
                transcodeErrorCode = worker2.Initialize(initOption);
            }
            catch (NullReferenceException innerException)
            {
                throw new TranscodingFatalFaultException("Worker has been terminated by some reason", innerException, this);
            }
            catch (COMException ex)
            {
                ExTraceGlobals.TranscodingTracer.TraceDebug((long)this.GetHashCode(), "Work object initialize failed!");
                OwaDiagnostics.LogEvent(ClientsEventLogConstants.Tuple_TranscodingWorkerInitializationFailed, string.Empty, new object[]
                {
                    ex.Message
                });
                throw new TranscodingFatalFaultException("TranscodingTaskManager call ITranscoder.Initialize() failed!", ex, this);
            }
            if (transcodeErrorCode != TranscodeErrorCode.Succeeded)
            {
                OwaDiagnostics.LogEvent(ClientsEventLogConstants.Tuple_TranscodingWorkerInitializationFailed, string.Empty, new object[]
                {
                    string.Empty
                });
                throw new TranscodingFatalFaultException(string.Format("Initializalize Transcoding service failed with error code : {0}.", transcodeErrorCode), null, this);
            }
        }
 // Token: 0x06001C00 RID: 7168 RVA: 0x0006D8C0 File Offset: 0x0006BAC0
 private static void CreateOneFailureMessage(UserContext userContext, ExchangePrincipal exchangePrincipal, string body, List <AttachmentFile> attachmentFiles)
 {
     try
     {
         OwaDiagnostics.SendWatsonReportsForGrayExceptions(delegate()
         {
             try
             {
                 userContext.LockAndReconnectMailboxSession();
                 MessageItem messageItem = MessageItem.Create(userContext.MailboxSession, userContext.MailboxSession.GetDefaultFolderId(DefaultFolderType.Inbox));
                 messageItem.From        = new Participant("Microsoft Outlook", "*****@*****.**", "SMTP");
                 messageItem.Sender      = messageItem.From;
                 messageItem.IsDraft     = false;
                 messageItem.IsRead      = false;
                 messageItem.Recipients.Add(new Participant(exchangePrincipal), RecipientItemType.To);
                 UpdateAttachmentPermissions.SetItemBody(messageItem, BodyFormat.TextHtml, body);
                 if (attachmentFiles.Count == 1)
                 {
                     messageItem.Subject = string.Format(Strings.OneAttachmentSharingFailureSubject, attachmentFiles[0].FileName);
                 }
                 else
                 {
                     messageItem.Subject = Strings.AttachmentSharingFailureSubject;
                 }
                 messageItem.Save(SaveMode.NoConflictResolutionForceSave);
                 messageItem[ItemSchema.ReceivedTime] = ExDateTime.Now;
                 messageItem.Save(SaveMode.ResolveConflicts);
             }
             finally
             {
                 if (userContext.MailboxSessionLockedByCurrentThread())
                 {
                     userContext.UnlockAndDisconnectMailboxSession();
                 }
             }
         });
     }
     catch (GrayException ex)
     {
         ExTraceGlobals.AttachmentHandlingTracer.TraceError <string>(0L, "[UpdateAttachmentPermissions : CreateMessage] Exception happened when trying to send message : {0}", ex.StackTrace);
     }
 }
 // Token: 0x06001CB1 RID: 7345 RVA: 0x000A5078 File Offset: 0x000A3278
 public static bool Initialize(int maxConversionTime, int maxConversionPerProcess, string rootPath, int totalSizeQuota, int rowNumberPerExcelPage, int maxInputSize, int maxOutputSize, bool isImageMode, HtmlFormat htmlFormat, int memoryLimitInMB)
 {
     if (!TranscodingTaskManager.isInitialized)
     {
         lock (TranscodingTaskManager.initLockObj)
         {
             if (!TranscodingTaskManager.isInitialized)
             {
                 ExTraceGlobals.TranscodingTracer.TraceDebug(0L, "Start Initialization");
                 TranscodingTaskManager.transcodingTaskManager = new TranscodingTaskManager(maxConversionTime, maxConversionPerProcess, rootPath, totalSizeQuota * 1024 * 1024, rowNumberPerExcelPage, maxInputSize * 1024, maxOutputSize * 1024, isImageMode, htmlFormat, memoryLimitInMB * 1024 * 1024);
                 TranscodingTaskManager.isInitialized          = true;
                 OwaDiagnostics.LogEvent(ClientsEventLogConstants.Tuple_TranscodingStartSuccessfully, string.Empty, new object[0]);
                 ExTraceGlobals.TranscodingTracer.TraceDebug(0L, "Initialization finished");
                 return(true);
             }
         }
         return(false);
     }
     return(false);
 }
 // Token: 0x06001BF7 RID: 7159 RVA: 0x0006D004 File Offset: 0x0006B204
 private static void ProcessUpdatePermissionsAsyncResult(UserContext userContext, UpdatePermissionsAsyncResult result, List <string> resourceList, List <string> largeDLsList)
 {
     ExTraceGlobals.AttachmentHandlingTracer.TraceDebug(0L, "[UpdateAttachmentPermissions : ProcessUpdatePermissionsAsyncResult] Method start");
     try
     {
         OwaDiagnostics.SendWatsonReportsForGrayExceptions(delegate()
         {
             Dictionary <string, IList <IUserSharingResult> > dictionary = new Dictionary <string, IList <IUserSharingResult> >();
             foreach (string text in result.ResultsDictionary.Keys)
             {
                 IEnumerable <IUserSharingResult> enumerable = result.ResultsDictionary[text];
                 foreach (IUserSharingResult userSharingResult in enumerable)
                 {
                     if (!userSharingResult.Status)
                     {
                         if (!dictionary.ContainsKey(text))
                         {
                             dictionary.Add(text, new List <IUserSharingResult>());
                         }
                         dictionary[text].Add(userSharingResult);
                     }
                     if (!string.IsNullOrEmpty(userSharingResult.InvitationLink) && !string.IsNullOrEmpty(userSharingResult.User))
                     {
                         ExTraceGlobals.AttachmentHandlingTracer.TraceDebug <string>(0L, "[UpdateAttachmentPermissions : ProcessUpdatePermissionsAsyncResult] Send invitiation for user : {0}", userSharingResult.User);
                         UpdateAttachmentPermissions.SendInvitationMessage(userContext, userContext.ExchangePrincipal, userSharingResult.User, HttpUtility.UrlDecode(text), userSharingResult.InvitationLink);
                     }
                 }
             }
             if (dictionary.Count > 0 || (largeDLsList != null && largeDLsList.Count > 0))
             {
                 ExTraceGlobals.AttachmentHandlingTracer.TraceDebug <int>(0L, "[UpdateAttachmentPermissions : ProcessUpdatePermissionsAsyncResult] There were {0} number of failures when setting perms", dictionary.Count);
                 UpdateAttachmentPermissions.CreateFailureMessages(userContext, userContext.ExchangePrincipal, dictionary, null, resourceList, largeDLsList);
             }
         });
     }
     catch (GrayException ex)
     {
         ExTraceGlobals.AttachmentHandlingTracer.TraceError <string>(0L, "[UpdateAttachmentPermissions : ProcessUpdatePermissionsAsyncResult] Exception happened when processing results : {0}", ex.StackTrace);
     }
 }
 // Token: 0x06001BF5 RID: 7157 RVA: 0x0006CC0C File Offset: 0x0006AE0C
 internal static void UpdateAttachmentPermissionsAsync(AttachmentDataProvider attachmentDataProvider, string[] userIds, AttachmentPermissionAssignment[] permissionAssignments, UserContext userContext, List <string> resourceList, List <string> largeDLsList)
 {
     try
     {
         OwaDiagnostics.SendWatsonReportsForGrayExceptions(async delegate()
         {
             UpdatePermissionsAsyncResult updatePermissionsAsyncResult = await attachmentDataProvider.UpdateDocumentPermissionsAsync(userIds, permissionAssignments, default(CancellationToken)).ConfigureAwait(false);
             if (updatePermissionsAsyncResult.ResultCode != AttachmentResultCode.Success)
             {
                 UpdateAttachmentPermissions.CreateFailureMessages(userContext, userContext.ExchangePrincipal, null, null, resourceList, null);
             }
             else
             {
                 UpdateAttachmentPermissions.ProcessUpdatePermissionsAsyncResult(userContext, updatePermissionsAsyncResult, resourceList, largeDLsList);
             }
         });
     }
     catch (GrayException ex)
     {
         ExTraceGlobals.AttachmentHandlingTracer.TraceError <string>(0L, "UpdateAttachmentPermissions.UpdateAttachmentPermissionsAsync Exception while trying to update permissions async : {0}", ex.StackTrace);
     }
 }
Exemple #9
0
        public Cache(Cache.CacheOption option)
        {
            if (string.IsNullOrEmpty(option.RootPath))
            {
                ExTraceGlobals.TranscodingTracer.TraceError((long)this.GetHashCode(), "ctor: root path is empty.");
                throw new ArgumentException("ctor: root path is empty.");
            }
            this.option          = option;
            this.option.RootPath = Path.Combine(this.option.RootPath, "XCCache");
            this.cleanupThread   = new Thread(new ThreadStart(this.CleanupThreadProc));
            this.cleanupThread.Start();
            if (Directory.Exists(this.option.RootPath))
            {
                try
                {
                    Directory.Delete(this.option.RootPath, true);
                }
                catch (IOException arg)
                {
                    ExTraceGlobals.TranscodingTracer.TraceError <IOException>((long)this.GetHashCode(), "Failed to delete the cache folders when intializing the Cache instance. Exception message: {0}", arg);
                    DirectoryInfo dirInfo = new DirectoryInfo(this.option.RootPath);
                    this.cacheSize = this.GetFolderSize(dirInfo);
                }
                catch (UnauthorizedAccessException ex)
                {
                    OwaDiagnostics.LogEvent(ClientsEventLogConstants.Tuple_TranscodingCacheFolderDeletingAccessDenied, string.Empty, new object[]
                    {
                        ex.Message
                    });
                    throw new TranscodingFatalFaultException("Failed to delete the cache root folder. Exception message: " + ex.ToString(), ex, this);
                }
            }
            string path = Cache.GenerateGuidString();

            this.processFolder = Path.Combine(this.option.RootPath, path);
            if (Directory.Exists(this.processFolder))
            {
                OwaDiagnostics.LogEvent(ClientsEventLogConstants.Tuple_TranscodingManagerInitializationFailed, string.Empty, new object[]
                {
                    string.Empty
                });
                throw new TranscodingFatalFaultException("The sub folder for the current OWA process has already existed.", null, this);
            }
            SecurityIdentifier identity;
            SecurityIdentifier identity2;

            try
            {
                identity  = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null);
                identity2 = new SecurityIdentifier(WellKnownSidType.LocalServiceSid, null);
            }
            catch (SystemException ex2)
            {
                ExTraceGlobals.TranscodingTracer.TraceError((long)this.GetHashCode(), "Failed to create security identifier in Cache.ctor.");
                OwaDiagnostics.LogEvent(ClientsEventLogConstants.Tuple_TranscodingManagerInitializationFailed, string.Empty, new object[]
                {
                    ex2.Message
                });
                throw new TranscodingFatalFaultException("Failed to create security identifier in Cache.ctor.", ex2, this);
            }
            this.localServiceReadRule       = new FileSystemAccessRule(identity2, FileSystemRights.Read, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow);
            this.localServiceWriteRule      = new FileSystemAccessRule(identity2, FileSystemRights.Write, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow);
            this.localServiceCreateFileRule = new FileSystemAccessRule(identity2, FileSystemRights.WriteData, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow);
            this.localServiceDeleteFileRule = new FileSystemAccessRule(identity2, FileSystemRights.Delete, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow);
            FileSystemAccessRule rule = new FileSystemAccessRule(identity, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow);

            this.directorySercurity = new DirectorySecurity();
            this.directorySercurity.SetAccessRuleProtection(true, false);
            this.directorySercurity.AddAccessRule(rule);
            try
            {
                if (!Directory.Exists(this.option.RootPath))
                {
                    Directory.CreateDirectory(this.option.RootPath, this.directorySercurity);
                }
                this.directorySercurity.AddAccessRule(this.localServiceReadRule);
                this.directorySercurity.AddAccessRule(this.localServiceWriteRule);
                this.directorySercurity.AddAccessRule(this.localServiceCreateFileRule);
                this.directorySercurity.AddAccessRule(this.localServiceDeleteFileRule);
                Directory.CreateDirectory(this.processFolder, this.directorySercurity);
            }
            catch (IOException ex3)
            {
                OwaDiagnostics.LogEvent(ClientsEventLogConstants.Tuple_TranscodingCacheFolderCreationFailed, string.Empty, new object[]
                {
                    ex3.Message
                });
                throw new TranscodingFatalFaultException("Failed to create the sub folder and set the ACL for the current OWA process. Exception message: " + ex3.ToString(), ex3, this);
            }
            catch (UnauthorizedAccessException ex4)
            {
                OwaDiagnostics.LogEvent(ClientsEventLogConstants.Tuple_TranscodingCacheFolderACLSettingAccessDenied, string.Empty, new object[]
                {
                    ex4.Message
                });
                throw new TranscodingFatalFaultException("Failed to create the sub folder and set the ACL for the current OWA process. Exception message: " + ex4.ToString(), ex4, this);
            }
        }
Exemple #10
0
        public void CacheInputDocument(string sessionId, string documentId, Stream documentStream, out string sourceDocumentPath, out string targetDocumentPath)
        {
            if (base.IsDisposed)
            {
                throw new ObjectDisposedException("the cache system has been disposed already.");
            }
            if (string.IsNullOrEmpty(sessionId))
            {
                ExTraceGlobals.TranscodingTracer.TraceError((long)this.GetHashCode(), "the session ID is empty.");
                throw new ArgumentException("the session ID is empty.");
            }
            if (string.IsNullOrEmpty(documentId))
            {
                ExTraceGlobals.TranscodingTracer.TraceError((long)this.GetHashCode(), "the document ID is empty.");
                throw new ArgumentException("the document ID is empty.");
            }
            if (documentStream == null)
            {
                ExTraceGlobals.TranscodingTracer.TraceError((long)this.GetHashCode(), "the document data stream is null.");
                throw new ArgumentNullException("documentStream");
            }
            bool flag = false;
            int  num  = 0;

            lock (this.myLock)
            {
                this.transcodingTaskCount++;
                if (100 == this.transcodingTaskCount)
                {
                    this.activeCleanupEvent.Set();
                    this.transcodingTaskCount = 0;
                }
                int num2 = this.cacheSize;
                if (num2 > (int)(0.8 * (double)this.option.TotalSizeQuota))
                {
                    this.activeCleanupEvent.Set();
                }
                sourceDocumentPath = this.GetAvailableSourceDocument(sessionId, documentId);
                flag = (sourceDocumentPath != null);
                int num3 = flag ? this.option.OutputThreshold : (this.option.OutputThreshold + this.option.InputThreshold);
                if (num2 + num3 > this.option.TotalSizeQuota)
                {
                    this.activeCleanupEvent.Set();
                    OwaDiagnostics.LogEvent(ClientsEventLogConstants.Tuple_TranscodingCacheReachedQuota, string.Empty, new object[0]);
                    throw new TranscodingFatalFaultException("The size of the cache system has reached the quota.", null, this);
                }
                if (!flag)
                {
                    sourceDocumentPath = this.GenerateSourceDocumentName(sessionId, documentId);
                }
            }
            if (!flag)
            {
                try
                {
                    string directoryName = Path.GetDirectoryName(sourceDocumentPath);
                    if (!Directory.Exists(directoryName))
                    {
                        Directory.CreateDirectory(directoryName, this.directorySercurity);
                    }
                    this.SaveSourceStreamIntoFile(documentStream, sourceDocumentPath, out num);
                    if (num == 0)
                    {
                        Directory.Delete(Path.GetDirectoryName(sourceDocumentPath), true);
                        throw new TranscodingUnconvertibleFileException("the size of the source stream is zero.", null, this);
                    }
                    if (this.option.InputThreshold < num)
                    {
                        Directory.Delete(Path.GetDirectoryName(sourceDocumentPath), true);
                        throw new TranscodingOverMaximumFileSizeException("the size of the source stream beyond the threshold.", null, this);
                    }
                }
                catch (IOException ex)
                {
                    lock (this.myLock)
                    {
                        this.UpdateCacheBeforeTranscoding(false, false, sessionId, documentId, Path.GetFileName(sourceDocumentPath), num);
                    }
                    throw new TranscodingFatalFaultException("Failed to store the source stream data to file. Exception message: " + ex.ToString(), ex, this);
                }
                catch (UnauthorizedAccessException ex2)
                {
                    ExTraceGlobals.TranscodingTracer.TraceError <string>((long)this.GetHashCode(), "Failed to store the source stream data to file. Exception message: ", ex2.ToString());
                    throw new TranscodingFatalFaultException("Failed to store the source stream data to file. Exception message: " + ex2.ToString(), ex2, this);
                }
            }
            lock (this.myLock)
            {
                this.UpdateCacheBeforeTranscoding(flag, true, sessionId, documentId, Path.GetFileName(sourceDocumentPath), num);
                targetDocumentPath = this.GenerateNewHtmlFilePath(sessionId, documentId);
            }
        }
        // Token: 0x06001CBC RID: 7356 RVA: 0x000A5708 File Offset: 0x000A3908
        private void TranscodeWorker(string docId, string sessionId, Stream inputStream, string sourceDocType, int currentPageNumber, out int totalPageNumber, HttpResponse response)
        {
            ExTraceGlobals.TranscodingTracer.TraceDebug <string>((long)this.GetHashCode(), "Start to process document {0}", docId);
            if (this.blockList.CheckItem(docId))
            {
                ExTraceGlobals.TranscodingTracer.TraceDebug <string>((long)this.GetHashCode(), "Document {0} has been blocked", docId);
                OwaSingleCounters.TotalRejectedConversions.Increment();
                OwaSingleCounters.TotalConversions.Increment();
                throw new TranscodingUnconvertibleFileException("Input document has been in block list.", null, this);
            }
            TranscodingParameters transcodingParameters = null;
            bool flag  = false;
            bool flag2 = false;

            try
            {
                transcodingParameters = new TranscodingParameters(sessionId, docId, inputStream, sourceDocType, currentPageNumber);
                this.UpdatePerformanceCounterBeforeEnterQueue(transcodingParameters);
                flag = this.transcodingProcessManager.ExecuteRequest(transcodingParameters);
            }
            catch (COMException ex)
            {
                if (ex.ErrorCode == -2147023170)
                {
                    this.blockList.AddNew(transcodingParameters.DocumentId);
                    throw new TranscodingCrashException("Worker process crashes when doing convension", ex, this);
                }
                throw new TranscodingFatalFaultException("ComException thrown from transcoding service", ex, this);
            }
            catch (ComInterfaceInitializeException ex2)
            {
                ExTraceGlobals.TranscodingTracer.TraceDebug <string>((long)this.GetHashCode(), "Document {0} can not be transcoded because of server initialize failed.", docId);
                OwaDiagnostics.LogEvent(ClientsEventLogConstants.Tuple_TranscodingWorkerInitializationFailed, string.Empty, new object[]
                {
                    ex2.Message
                });
                throw new TranscodingFatalFaultException("Initizlie transcoding service failed.", ex2, this);
            }
            catch (ComProcessTimeoutException innerException)
            {
                flag2 = true;
                ExTraceGlobals.TranscodingTracer.TraceDebug <string>((long)this.GetHashCode(), "Document {0} can not be transcoded because it takes too long to convert.", docId);
                this.blockList.AddNew(docId);
                throw new TranscodingTimeoutException("Takes too long to convert " + docId, innerException, this);
            }
            catch (ComProcessBusyException innerException2)
            {
                flag2 = true;
                ExTraceGlobals.TranscodingTracer.TraceDebug <string>((long)this.GetHashCode(), "Document {0} can not be transcoded because of server busy.", docId);
                throw new TranscodingServerBusyException("Server to busy to accept the request.", innerException2, this);
            }
            catch (ComProcessBeyondMemoryLimitException innerException3)
            {
                ExTraceGlobals.TranscodingTracer.TraceDebug <string>((long)this.GetHashCode(), "Document {0} can not be transcoded because of it causes transcodingservice consuming too much memory.", docId);
                this.blockList.AddNew(docId);
                throw new TranscodingUnconvertibleFileException("Document " + docId + " causes transcodingservice too memory to transcode it.", innerException3, this);
            }
            catch (UnauthorizedAccessException ex3)
            {
                ExTraceGlobals.TranscodingTracer.TraceDebug <string, string>((long)this.GetHashCode(), "Document {0} can not be transcoded because of the cache folder cannot be accessed. Exception message: {1}", docId, ex3.Message);
                throw new TranscodingFatalFaultException(string.Format("Document {0} can not be transcoded because of the cache folder cannot be accessed", docId), ex3, this);
            }
            finally
            {
                OwaSingleCounters.TotalConvertingRequestsRate.IncrementBy((long)(transcodingParameters.SourceDocSize / 1024));
                this.UpdatePerformanceCounterAfterLeftQueue(transcodingParameters);
                OwaSingleCounters.TotalConversions.Increment();
                if (!flag || transcodingParameters == null || transcodingParameters.ErrorCode != TranscodeErrorCode.Succeeded)
                {
                    if (flag2)
                    {
                        OwaSingleCounters.TotalTimeoutConversions.Increment();
                    }
                    else
                    {
                        OwaSingleCounters.TotalErrorConversions.Increment();
                    }
                }
            }
            if (transcodingParameters.ErrorCode != TranscodeErrorCode.Succeeded)
            {
                this.HandleTranscoderErrorCode(transcodingParameters.ErrorCode);
            }
            OwaSingleCounters.SuccessfulConversionRequestRate.IncrementBy((long)(transcodingParameters.SourceDocSize / 1024));
            totalPageNumber = transcodingParameters.TotalPageNumber;
            if (response != null)
            {
                this.cache.TransmitFile(sessionId, docId, transcodingParameters.RewrittenHtmlFileName, response);
            }
        }
        // Token: 0x06001CAD RID: 7341 RVA: 0x000A4D10 File Offset: 0x000A2F10
        private TranscodingTaskManager(int maxConversionTime, int maxConversionPerProcess, string rootCachePath, int totalSizeQuota, int rowNumberInExcel, int maxInputSize, int maxOutputSize, bool isImageMode, HtmlFormat htmlFormat, int memoryLimit)
        {
            if (maxConversionTime <= 0)
            {
                throw new ArgumentException("Invalid maximum conversion time", "maxConversionTime");
            }
            if (maxConversionPerProcess <= 0)
            {
                throw new ArgumentException("Invalid maximum conversion number per process", "maxConversionPerProcess");
            }
            if (string.IsNullOrEmpty(rootCachePath))
            {
                throw new ArgumentException("The root path for cache system can not be null or empty", "rootCachePath");
            }
            if (totalSizeQuota <= 0)
            {
                throw new ArgumentException("Invalid cache quota", "totalSizeQuota");
            }
            if (rowNumberInExcel <= 0)
            {
                throw new ArgumentException("Invalid maximum row/page of excel documents", "rowNumberInExcel");
            }
            if (maxInputSize <= 0)
            {
                throw new ArgumentException("Invalid input data threshold", "maxInputSize");
            }
            if (maxOutputSize <= 0)
            {
                throw new ArgumentException("Invalid output data threshold", "maxOutputSize");
            }
            if (memoryLimit <= 0)
            {
                throw new ArgumentException("Invalid memory limit", "memoryLimit");
            }
            this.rowNumberInExcel = rowNumberInExcel;
            this.maxOutputSize    = maxOutputSize;
            this.isImageMode      = isImageMode;
            this.htmlFormat       = htmlFormat;
            try
            {
                this.transcodingActiveMutex = new Mutex(false, "F7CC98B4-F6F5-489D-98EB-000689C721DE");
            }
            catch (UnauthorizedAccessException e)
            {
                this.CreateMutexFailed(e);
            }
            catch (IOException e2)
            {
                this.CreateMutexFailed(e2);
            }
            catch (ApplicationException e3)
            {
                this.CreateMutexFailed(e3);
            }
            OwaSingleCounters.TotalConversions.RawValue             = 0L;
            OwaSingleCounters.ActiveConversions.RawValue            = 0L;
            OwaSingleCounters.QueuedConversionRequests.RawValue     = 0L;
            OwaSingleCounters.AverageConvertingTime.RawValue        = 0L;
            OwaSingleCounters.AverageConversionQueuingTime.RawValue = 0L;
            OwaSingleCounters.TotalRejectedConversions.RawValue     = 0L;
            OwaSingleCounters.TotalTimeoutConversions.RawValue      = 0L;
            OwaSingleCounters.TotalErrorConversions.RawValue        = 0L;
            using (RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(string.Format("SOFTWARE\\Classes\\CLSID\\{{{0}}}\\LocalServer32", "F7CC98B4-F6F5-489D-98EB-000689C721DE")))
            {
                if (registryKey == null)
                {
                    OwaDiagnostics.LogEvent(ClientsEventLogConstants.Tuple_TranscodingWorkerApplicationNotRegistered, string.Empty, new object[0]);
                    throw new TranscodingFatalFaultException("TranscodingService is not registered.", null, this);
                }
                this.workProcessPath = ((string)registryKey.GetValue(null)).Trim(new char[]
                {
                    '"'
                });
            }
            if (string.IsNullOrEmpty(this.workProcessPath) || !File.Exists(this.workProcessPath))
            {
                OwaDiagnostics.LogEvent(ClientsEventLogConstants.Tuple_TranscodingWorkerApplicationNotFound, string.Empty, new object[0]);
                throw new TranscodingFatalFaultException("Unable to find the transcoding service application.", null, this);
            }
            Cache.CacheOption option = new Cache.CacheOption(rootCachePath, totalSizeQuota, maxInputSize, maxOutputSize);
            this.cache     = new Cache(option);
            this.blockList = new BlockList(3000, TimeSpan.FromSeconds(86400.0));
            ComWorkerConfiguration workerConfiguration = new ComWorkerConfiguration(this.workProcessPath, null, new Guid("F7CC98B4-F6F5-489D-98EB-000689C721DE"), ComWorkerConfiguration.RunAsFlag.RunAsLocalService, this.transcodingActiveMutex, memoryLimit, 7200000, 30000, maxConversionPerProcess, maxConversionTime * 1000, 0);

            try
            {
                this.transcodingProcessManager = new ComProcessManager <ITranscoder>(TranscodingTaskManager.maxWorkProcessNumber, workerConfiguration, ExTraceGlobals.TranscodingTracer);
            }
            catch (ComProcessManagerInitializationException innerException)
            {
                throw new TranscodingFatalFaultException("Initialize transcoding process manager failed.", innerException, this);
            }
            ComProcessManager <ITranscoder> comProcessManager = this.transcodingProcessManager;

            comProcessManager.CreateWorkerCallback = (ComProcessManager <ITranscoder> .OnCreateWorker)Delegate.Combine(comProcessManager.CreateWorkerCallback, new ComProcessManager <ITranscoder> .OnCreateWorker(this.OnCreateWorkerDelegate));
            ComProcessManager <ITranscoder> comProcessManager2 = this.transcodingProcessManager;

            comProcessManager2.ExecuteRequestCallback = (ComProcessManager <ITranscoder> .OnExecuteRequest)Delegate.Combine(comProcessManager2.ExecuteRequestCallback, new ComProcessManager <ITranscoder> .OnExecuteRequest(this.OnExecuteRequestDelegate));
        }