Example #1
0
 protected void SafeCloseLoggingStream()
 {
     if (this.syncCycleLogStream != null)
     {
         try
         {
             this.syncCycleLogStream.SetLength(this.syncCycleLogStream.Position);
             this.syncCycleLogStream.Close();
             this.syncCycleLogStream = null;
             this.SyncInfoEntry.Logger.Save();
         }
         catch (IOException exception)
         {
             ProtocolLog.LogError(this.loggingComponent, this.loggingContext, "SafeCloseLoggingStream: Failed with IOException", exception);
         }
         catch (StorageTransientException exception2)
         {
             ProtocolLog.LogError(this.loggingComponent, this.loggingContext, "SafeCloseLoggingStream: Failed with StorageTransientException", exception2);
         }
         catch (StoragePermanentException exception3)
         {
             ProtocolLog.LogError(this.loggingComponent, this.loggingContext, "SafeCloseLoggingStream: Failed with StoragePermanentException", exception3);
         }
     }
 }
Example #2
0
 protected void SafeInitializeLoggingStream()
 {
     try
     {
         if (this.SyncInfoEntry.Logger != null)
         {
             this.syncCycleLogStream = this.SyncInfoEntry.Logger.GetStream();
         }
         else
         {
             ProtocolLog.LogError(this.loggingComponent, this.loggingContext, "SafeInitializeLoggingStream: Logger is null and possibly caused by corruption of log stream configuration", new ArgumentException());
         }
     }
     catch (IOException exception)
     {
         ProtocolLog.LogError(this.loggingComponent, this.loggingContext, "SafeInitializeLoggingStream: Failed with IOException", exception);
     }
     catch (StorageTransientException exception2)
     {
         ProtocolLog.LogError(this.loggingComponent, this.loggingContext, "SafeInitializeLoggingStream: Failed with StorageTransientException", exception2);
     }
     catch (StoragePermanentException exception3)
     {
         ProtocolLog.LogError(this.loggingComponent, this.loggingContext, "SafeInitializeLoggingStream: Failed with StoragePermanentException", exception3);
     }
 }
Example #3
0
 protected bool HandleShutDown()
 {
     if (this.Job != null && this.Job.IsShuttingdown)
     {
         this.resourceMonitor.ResetBudget();
         ProtocolLog.LogInformation(this.loggingComponent, this.loggingContext, "HandleShutDown: Shutdown the job by invoke callback");
         this.executionAsyncResult.InvokeCallback(null);
         return(true);
     }
     return(false);
 }
Example #4
0
        public static string GetExceptionLogString(Exception e)
        {
            if (e == null)
            {
                throw new ArgumentNullException("e is null");
            }
            string        empty = string.Empty;
            List <string> list  = null;
            List <string> list2 = null;

            ProtocolLog.GetExceptionTypeAndDetails(e, out list, out list2, out empty, true);
            return(empty);
        }
Example #5
0
 private void UpdateSyncMetadataOnSyncFailure()
 {
     try
     {
         ExDateTime?   exDateTime    = this.GetSyncMetadataValue("LastSuccessfulSyncTime") as ExDateTime?;
         ExDateTime?   exDateTime2   = this.GetSyncMetadataValue("FirstAttemptedSyncTime") as ExDateTime?;
         ExDateTime?   exDateTime3   = this.GetSyncMetadataValue("LastFailedSyncEmailTime") as ExDateTime?;
         StringBuilder stringBuilder = new StringBuilder();
         stringBuilder.AppendLine(ProtocolLog.GetExceptionLogString(this.LastError));
         if (this.LastError is SharePointException)
         {
             stringBuilder.AppendLine("SharePointException Diagnostic Info:");
             stringBuilder.AppendLine(((SharePointException)this.LastError).DiagnosticInfo);
         }
         this.SetSyncMetadataValue("LastSyncFailure", stringBuilder.ToString());
         this.SetSyncMetadataValue("LastFailedSyncTime", ExDateTime.UtcNow);
         ExDateTime?exDateTime4 = exDateTime ?? exDateTime2;
         if ((exDateTime3 == null || ExDateTime.UtcNow - exDateTime3 > TimeSpan.FromHours(24.0)) && exDateTime4 != null && ExDateTime.UtcNow - exDateTime4 > TimeSpan.FromHours(12.0))
         {
             StoreObjectId destFolderId = Utils.EnsureSyncIssueFolder(this.mailboxSession);
             using (MessageItem messageItem = MessageItem.Create(this.mailboxSession, destFolderId))
             {
                 LocalizedString empty = LocalizedString.Empty;
                 messageItem.From    = new Participant(this.Job.SyncInfoEntry.MailboxPrincipal);
                 messageItem.Subject = this.GetSyncIssueEmailErrorString(this.LastError.Message, out empty);
                 using (TextWriter textWriter = messageItem.Body.OpenTextWriter(BodyFormat.TextHtml))
                 {
                     messageItem.Body.Reset();
                     using (HtmlWriter htmlWriter = new HtmlWriter(textWriter))
                     {
                         htmlWriter.WriteStartTag(HtmlTagId.P);
                         htmlWriter.WriteText(empty);
                         htmlWriter.WriteEndTag(HtmlTagId.P);
                     }
                 }
                 messageItem.IsDraft = false;
                 messageItem.MarkAsUnread(true);
                 messageItem.Save(SaveMode.NoConflictResolutionForceSave);
                 this.SetSyncMetadataValue("LastFailedSyncEmailTime", ExDateTime.UtcNow);
             }
         }
     }
     catch (StorageTransientException exception)
     {
         ProtocolLog.LogError(this.loggingComponent, this.loggingContext, "UpdateSyncMetadataOnSyncFailure: Failed with StorageTransientException", exception);
     }
     catch (StoragePermanentException exception2)
     {
         ProtocolLog.LogError(this.loggingComponent, this.loggingContext, "UpdateSyncMetadataOnSyncFailure: Failed with StoragePermanentException", exception2);
     }
 }
Example #6
0
        private static void LogEvent(ProtocolLog.Component component, ProtocolLog.EventType eventType, LoggingContext loggingContext, string data, Exception exception)
        {
            if (string.IsNullOrEmpty(data))
            {
                throw new ArgumentNullException("data");
            }
            ProtocolLog.InitializeIfNeeded();
            LogRowFormatter logRowFormatter = new LogRowFormatter(ProtocolLog.LogSchema);

            logRowFormatter[1] = component;
            logRowFormatter[2] = eventType;
            if (loggingContext != null)
            {
                logRowFormatter[5] = loggingContext.MailboxGuid.ToString();
                logRowFormatter[3] = loggingContext.TransactionId.ToString();
                logRowFormatter[4] = loggingContext.User;
                logRowFormatter[6] = loggingContext.Context;
            }
            logRowFormatter[7] = data;
            if (exception != null)
            {
                List <string> list  = null;
                List <string> list2 = null;
                string        value = null;
                ProtocolLog.GetExceptionTypeAndDetails(exception, out list, out list2, out value, false);
                logRowFormatter[8] = list[0];
                logRowFormatter[9] = list2[0];
                if (list.Count > 1)
                {
                    logRowFormatter[10] = list[list.Count - 1];
                    logRowFormatter[11] = list2[list2.Count - 1];
                }
                logRowFormatter[12] = value;
            }
            ProtocolLog.instance.logInstance.Append(logRowFormatter, 0);
            if (loggingContext != null && loggingContext.LoggingStream != null)
            {
                try
                {
                    logRowFormatter.Write(loggingContext.LoggingStream);
                }
                catch (StorageTransientException)
                {
                }
                catch (StoragePermanentException)
                {
                }
            }
        }
Example #7
0
 private void ProtectedExecution(AsyncCallback callback, IAsyncResult asyncResult)
 {
     try
     {
         GrayException.MapAndReportGrayExceptions(delegate()
         {
             callback(asyncResult);
         });
     }
     catch (GrayException ex)
     {
         ProtocolLog.LogError(this.loggingComponent, this.loggingContext, "WrapCallbackWithUnhandledExceptionAndSendReport: Failed with unexpected exception", ex);
         this.executionAsyncResult.InvokeCallback(ex);
     }
 }
Example #8
0
 protected override void End()
 {
     try
     {
         if (base.LastError != null)
         {
             ProtocolLog.LogCycleFailure(this.loggingComponent, this.loggingContext, "The sync cycle completed with error", base.LastError);
         }
         else
         {
             ProtocolLog.LogCycleSuccess(this.loggingComponent, this.loggingContext, "The sync cycle completed successfully");
         }
         this.SafeCloseLoggingStream();
     }
     finally
     {
         base.End();
     }
 }
Example #9
0
 public bool UpdateNextBatch()
 {
     for (int i = 0; i < this.membershipSynchronizer.workLoadSize; i++)
     {
         if (!this.usersEnumerator.MoveNext())
         {
             return(false);
         }
         MembershipSynchronizer.UsersToUpdateShowInMyClient.UserToUpdate userToUpdate = this.usersEnumerator.Current;
         bool      flag;
         Exception ex;
         this.membershipSynchronizer.membershipHelper.SetShowInMyClient(userToUpdate.Id, userToUpdate.IsAdd, out flag, out ex);
         if (ex != null)
         {
             ProtocolLog.LogError(this.membershipSynchronizer.loggingComponent, this.membershipSynchronizer.loggingContext, string.Format("MembershipSynchronizer.SetShowInMyClient: failed to SetShowInMyClient for user {0}", userToUpdate.Id), ex);
         }
     }
     return(true);
 }
 public override IAsyncResult BeginExecute(AsyncCallback executeCallback, object state)
 {
     this.executeStopwatch     = Stopwatch.StartNew();
     this.executionAsyncResult = new LazyAsyncResult(null, state, executeCallback);
     try
     {
         this.InitializeSyncMetadata();
         base.UpdateSyncMetadataOnBeginSync();
     }
     catch (StorageTransientException ex)
     {
         ProtocolLog.LogError(this.loggingComponent, this.loggingContext, "SiteSynchronizer.BeginExecute:failed with StorageTransientException", ex);
         this.executionAsyncResult.InvokeCallback(ex);
         return(this.executionAsyncResult);
     }
     catch (StoragePermanentException ex2)
     {
         ProtocolLog.LogError(this.loggingComponent, this.loggingContext, "SiteSynchronizer.BeginExecute:failed with StoragePermanentException", ex2);
         this.executionAsyncResult.InvokeCallback(ex2);
         return(this.executionAsyncResult);
     }
     this.OnGetDocumentLibraryListsComplete(this.executionAsyncResult);
     return(this.executionAsyncResult);
 }
        protected virtual void OnGetDocumentLibraryListsComplete(IAsyncResult asyncResult)
        {
            if (asyncResult == null)
            {
                throw new InvalidOperationException("OnGetDocumentLibraryListsComplete: asyncResult cannot be null here.");
            }
            ProtocolLog.LogInformation(this.loggingComponent, this.loggingContext, string.Format("SiteSynchronizer.BeginExecute", new object[0]));
            bool flag = (base.SyncOption & SyncOption.CurrentDocumentLibsOnly) == SyncOption.CurrentDocumentLibsOnly;
            Dictionary <Guid, List> dictionary = new Dictionary <Guid, List>();

            if (!flag)
            {
                try
                {
                    this.InitializeDocumentLibraryList(dictionary);
                    if (base.HandleShutDown())
                    {
                        return;
                    }
                }
                catch (WebException e)
                {
                    SharePointException value = new SharePointException(this.siteUri.AbsoluteUri, e, false);
                    this.executionAsyncResult.InvokeCallback(value);
                    return;
                }
                catch (IOException value2)
                {
                    this.executionAsyncResult.InvokeCallback(value2);
                    return;
                }
                catch (ClientRequestException value3)
                {
                    this.executionAsyncResult.InvokeCallback(value3);
                    return;
                }
                catch (ServerException value4)
                {
                    this.executionAsyncResult.InvokeCallback(value4);
                    return;
                }
            }
            List <StoreObjectId>             list        = new List <StoreObjectId>();
            List <List>                      list2       = new List <List>();
            Dictionary <StoreObjectId, List> dictionary2 = new Dictionary <StoreObjectId, List>();

            try
            {
                using (Folder folder = Folder.Bind(this.mailboxSession, DefaultFolderType.Root))
                {
                    using (QueryResult queryResult = folder.FolderQuery(FolderQueryFlags.None, new ExistsFilter(FolderSchema.LinkedId), null, new PropertyDefinition[]
                    {
                        FolderSchema.LinkedId,
                        FolderSchema.Id,
                        FolderSchema.DisplayName,
                        FolderSchema.LinkedUrl,
                        FolderSchema.LinkedSiteAuthorityUrl
                    }))
                    {
                        object[][] rows;
                        do
                        {
                            rows = queryResult.GetRows(10000);
                            for (int i = 0; i < rows.Length; i++)
                            {
                                Guid          guid     = (Guid)rows[i][0];
                                StoreObjectId objectId = ((VersionedId)rows[i][1]).ObjectId;
                                string        a        = rows[i][2] as string;
                                string        text     = rows[i][3] as string;
                                string        text2    = rows[i][4] as string;
                                Uri           uri      = null;
                                if (!string.IsNullOrEmpty(text2))
                                {
                                    uri = new Uri(text2);
                                }
                                if (string.IsNullOrEmpty(text))
                                {
                                    this.executionAsyncResult.InvokeCallback(new ArgumentNullException("LinkedUrl is null for folder " + objectId.ToString()));
                                }
                                if (!flag)
                                {
                                    List list3 = null;
                                    if (dictionary.TryGetValue(guid, out list3))
                                    {
                                        if (!string.Equals(a, list3.Title, StringComparison.Ordinal) || (uri != null && !UriComparer.IsEqual(uri, this.siteUri)) || (this.Job.SyncOption & SyncOption.FullSync) == SyncOption.FullSync)
                                        {
                                            dictionary2[objectId] = dictionary[guid];
                                        }
                                        this.documentLibraryInfos.Enqueue(new DocumentLibraryInfo(objectId, list3.Id, list3.RootFolder.ServerRelativeUrl));
                                        dictionary.Remove(guid);
                                    }
                                    else
                                    {
                                        list.Add(objectId);
                                    }
                                }
                                else
                                {
                                    this.documentLibraryInfos.Enqueue(new DocumentLibraryInfo(objectId, guid, new Uri(text).AbsolutePath));
                                }
                            }
                        }while (rows.Length != 0);
                        list2.AddRange(dictionary.Values);
                    }
                    if (list.Count > 0)
                    {
                        folder.DeleteObjects(DeleteItemFlags.HardDelete, list.ToArray());
                    }
                    foreach (KeyValuePair <StoreObjectId, List> keyValuePair in dictionary2)
                    {
                        if (base.HandleShutDown())
                        {
                            return;
                        }
                        using (Folder folder2 = Folder.Bind(this.mailboxSession, keyValuePair.Key))
                        {
                            Uri  uri2  = new Uri(new Uri(this.siteUri.GetLeftPart(UriPartial.Authority)), keyValuePair.Value.RootFolder.ServerRelativeUrl);
                            bool flag2 = Utils.HasFolderUriChanged(folder2, uri2);
                            if (flag2)
                            {
                                folder2[FolderSchema.SharePointChangeToken] = string.Empty;
                                folder2[FolderSchema.LinkedUrl]             = uri2.AbsoluteUri;
                                folder2[FolderSchema.LinkedSiteUrl]         = this.siteUri.AbsoluteUri;
                                string valueOrDefault = folder2.PropertyBag.GetValueOrDefault <string>(FolderSchema.LinkedUrl, string.Empty);
                                ProtocolLog.LogInformation(this.loggingComponent, this.loggingContext, string.Format("SiteSynchronizer: Document Library URL has changed from {0} to {1}", valueOrDefault, uri2.AbsoluteUri));
                            }
                            folder2.DisplayName = keyValuePair.Value.Title;
                            folder2[FolderSchema.LinkedSiteAuthorityUrl] = this.siteUri.AbsoluteUri;
                            folder2.Save();
                        }
                    }
                    foreach (List list4 in list2)
                    {
                        if (base.HandleShutDown())
                        {
                            return;
                        }
                        using (Folder folder3 = Folder.Create(this.mailboxSession, folder.Id.ObjectId, StoreObjectType.ShortcutFolder, list4.Title, CreateMode.OpenIfExists))
                        {
                            folder3[FolderSchema.LinkedId] = list4.Id;
                            Uri uri3 = new Uri(new Uri(this.siteUri.GetLeftPart(UriPartial.Authority)), list4.RootFolder.ServerRelativeUrl);
                            folder3[FolderSchema.LinkedUrl]               = uri3.AbsoluteUri;
                            folder3[FolderSchema.LinkedSiteUrl]           = this.siteUri.AbsoluteUri;
                            folder3[FolderSchema.LinkedListId]            = list4.Id;
                            folder3[FolderSchema.IsDocumentLibraryFolder] = true;
                            folder3[FolderSchema.LinkedSiteAuthorityUrl]  = this.siteUri.AbsoluteUri;
                            folder3.Save();
                            folder3.Load();
                            ProtocolLog.LogInformation(this.loggingComponent, this.loggingContext, string.Format("SiteSynchronizer: Create or update top level document library Name:{0}, LinkedUrl: {1}, LinkedId {2}, ListId {3}", new object[]
                            {
                                folder3.DisplayName,
                                folder3[FolderSchema.LinkedUrl],
                                folder3[FolderSchema.LinkedId],
                                folder3[FolderSchema.LinkedListId]
                            }));
                            this.documentLibraryInfos.Enqueue(new DocumentLibraryInfo(folder3.Id.ObjectId, list4.Id, list4.RootFolder.ServerRelativeUrl));
                        }
                    }
                }
                base.SyncResult = this.documentLibraryInfos;
                this.executionAsyncResult.InvokeCallback(null);
            }
            catch (StorageTransientException value5)
            {
                this.executionAsyncResult.InvokeCallback(value5);
            }
            catch (StoragePermanentException value6)
            {
                this.executionAsyncResult.InvokeCallback(value6);
            }
        }
        public override IAsyncResult BeginExecute(AsyncCallback executeCallback, object state)
        {
            this.executionAsyncResult = new LazyAsyncResult(null, state, executeCallback);
            this.performanceCounter.Start(OperationType.EndToEnd);
            try
            {
                this.InitializeSyncMetadata();
                base.UpdateSyncMetadataOnBeginSync();
            }
            catch (StorageTransientException ex)
            {
                ProtocolLog.LogError(this.loggingComponent, this.loggingContext, "MaintenanceSynchronizer.BeginExecute: failed with StorageTransientException", ex);
                this.executionAsyncResult.InvokeCallback(ex);
                return(this.executionAsyncResult);
            }
            catch (StoragePermanentException ex2)
            {
                ProtocolLog.LogError(this.loggingComponent, this.loggingContext, "MaintenanceSynchronizer.BeginExecute: failed with StoragePermanentException", ex2);
                this.executionAsyncResult.InvokeCallback(ex2);
                return(this.executionAsyncResult);
            }
            ProtocolLog.LogInformation(this.loggingComponent, this.loggingContext, "MaintenanceSynchronizer.BeginExecute");
            Exception value = null;
            Uri       uri;
            string    b;

            if (this.recordedSiteUrl != null && this.webCollectionUrl != null && this.TryGetSharePointSiteUrlAndTitle(this.webCollectionUrl, this.webId, out uri, out b, out value))
            {
                if (UriComparer.IsEqual(this.recordedSiteUrl, uri))
                {
                    if (string.Equals(this.displayName, b))
                    {
                        goto IL_286;
                    }
                }
                try
                {
                    IRecipientSession tenantOrRootOrgRecipientSession = DirectorySessionFactory.Default.GetTenantOrRootOrgRecipientSession(null, null, CultureInfo.InvariantCulture.LCID, false, ConsistencyMode.IgnoreInvalid, null, ADSessionSettings.FromOrganizationIdWithoutRbacScopesServiceOnly(this.orgId), 189, "BeginExecute", "f:\\15.00.1497\\sources\\dev\\data\\src\\storage\\LinkedFolder\\MaintenanceSynchronizer.cs");
                    ADUser            aduser = tenantOrRootOrgRecipientSession.FindByExchangeGuid(this.TeamMailboxGuid) as ADUser;
                    if (aduser == null)
                    {
                        value = new ObjectNotFoundException(new LocalizedString("Cannot find the team mailbox by mailbox guid " + this.TeamMailboxGuid));
                    }
                    else
                    {
                        aduser.SharePointUrl = uri;
                        aduser.DisplayName   = b;
                        tenantOrRootOrgRecipientSession.Save(aduser);
                        ProtocolLog.LogInformation(this.loggingComponent, this.loggingContext, "MaintenanceSynchronizer.BeginExecute: updated new SharePoint site URL: " + uri);
                        if (!UriComparer.IsEqual(this.recordedSiteUrl, uri))
                        {
                            RpcClientWrapper.EnqueueTeamMailboxSyncRequest(this.mailboxSession.MailboxOwner.MailboxInfo.Location.ServerFqdn, this.mailboxSession.MailboxOwner.MailboxInfo.MailboxGuid, QueueType.TeamMailboxDocumentSync, this.mailboxSession.MailboxOwner.MailboxInfo.OrganizationId, "Maintenance Synchronizer", tenantOrRootOrgRecipientSession.LastUsedDc, SyncOption.Default);
                            RpcClientWrapper.EnqueueTeamMailboxSyncRequest(this.mailboxSession.MailboxOwner.MailboxInfo.Location.ServerFqdn, this.mailboxSession.MailboxOwner.MailboxInfo.MailboxGuid, QueueType.TeamMailboxMembershipSync, this.mailboxSession.MailboxOwner.MailboxInfo.OrganizationId, "Maintenance Synchronizer", tenantOrRootOrgRecipientSession.LastUsedDc, SyncOption.Default);
                        }
                    }
                }
                catch (DataSourceOperationException ex3)
                {
                    value = ex3;
                }
                catch (DataValidationException ex4)
                {
                    value = ex4;
                }
                catch (TransientException ex5)
                {
                    value = ex5;
                }
            }
IL_286:
            this.executionAsyncResult.InvokeCallback(value);
            return(this.executionAsyncResult);
        }
Example #13
0
        private bool UpdateAccessTokenIfNeeded(Uri sharepointUrl, ExchangePrincipal siteMailbox, ICredentials accessingUserCredential, ClientSecurityContext accessingUserSecurityContext, int sessionHashCode, out Exception exception, bool isTest = false)
        {
            exception = null;
            if (siteMailbox == null)
            {
                throw new ArgumentNullException("siteMailbox");
            }
            if (accessingUserSecurityContext == null)
            {
                throw new ArgumentNullException("accessingUserSecurityContext");
            }
            if (sharepointUrl == null)
            {
                ExTraceGlobals.SiteMailboxPermissionCheckTracer.TraceDebug <string>((long)sessionHashCode, "SharepointAccessManager.UpdateAccessTokenIfNeeded: Skip site mailbox {0} because its Sharepoint URL is null", siteMailbox.MailboxInfo.PrimarySmtpAddress.ToString());
                return(false);
            }
            ExTraceGlobals.SiteMailboxPermissionCheckTracer.TraceDebug <ClientSecurityContext, string, string>((long)sessionHashCode, "SharepointAccessManager.UpdateAccessTokenIfNeeded: Entered with user {0}, site mailbox {1}, URL {2}", accessingUserSecurityContext, siteMailbox.MailboxInfo.PrimarySmtpAddress.ToString(), sharepointUrl.AbsoluteUri);
            LoggingContext loggingContext = new LoggingContext(siteMailbox.MailboxInfo.MailboxGuid, sharepointUrl.AbsoluteUri, accessingUserSecurityContext.ToString(), null);
            AccessState    accessState    = AccessState.Denied;
            bool           flag           = false;

            SharepointAccessManager.Key key = this.GetKey(accessingUserSecurityContext.UserSid, siteMailbox.MailboxInfo.MailboxGuid);
            if (!SharepointAccessManager.Instance.TryGetValue(key, out accessState))
            {
                flag = true;
                ExTraceGlobals.SiteMailboxPermissionCheckTracer.TraceDebug((long)sessionHashCode, "SharepointAccessManager.UpdateAccessTokenIfNeeded: Cache miss, query Sharepoint");
                SharepointAccessManager.PermissionCheckerClient permissionCheckerClient = new SharepointAccessManager.PermissionCheckerClient(sessionHashCode, siteMailbox.MailboxInfo.MailboxGuid, sharepointUrl.AbsoluteUri, accessingUserSecurityContext.UserSid, key, accessingUserCredential, this.requestTimeout, this.requestThroughLocalProxy, isTest);
                LazyAsyncResult lazyAsyncResult = (LazyAsyncResult)permissionCheckerClient.BeginExecute(new AsyncCallback(SharepointAccessManager.OnCheckComplete), permissionCheckerClient);
                int             num             = (int)this.synchronousWaitTimeout.TotalSeconds * 2;
                int             num2            = 0;
                while (!lazyAsyncResult.IsCompleted || lazyAsyncResult.Result == null)
                {
                    Thread.Sleep(500);
                    num2++;
                    if (num2 > num)
                    {
                        break;
                    }
                }
                object result = lazyAsyncResult.Result;
                if (!(result is AccessState))
                {
                    exception = ((lazyAsyncResult.Result is Exception) ? (lazyAsyncResult.Result as Exception) : new TimeoutException("Timed out"));
                    WebException ex = exception as WebException;
                    if (ex != null)
                    {
                        SharePointException exception2 = new SharePointException(sharepointUrl.AbsoluteUri, ex, false);
                        ExTraceGlobals.SiteMailboxPermissionCheckTracer.TraceError <WebExceptionStatus, string, Exception>((long)permissionCheckerClient.SessionHashCode, "SharepointAccessManager.UpdateAccessTokenIfNeeded: Query failed with WebException. Status: {0}, Message: {1}, InnerException: {2}", ex.Status, ex.Message, ex.InnerException);
                        ProtocolLog.LogError(ProtocolLog.Component.SharepointAccessManager, loggingContext, "Query failed with SharePointException", exception2);
                    }
                    else
                    {
                        ExTraceGlobals.SiteMailboxPermissionCheckTracer.TraceError <Type, string, Exception>((long)permissionCheckerClient.SessionHashCode, "SharepointAccessManager.UpdateAccessTokenIfNeeded: Query failed with {0}, Message: {1}, InnerException: {2}", exception.GetType(), exception.Message, exception.InnerException);
                        ProtocolLog.LogError(ProtocolLog.Component.SharepointAccessManager, loggingContext, string.Format("Query failed with {0}", exception.GetType()), exception);
                    }
                    return(false);
                }
                accessState = (AccessState)result;
            }
            else if (accessState == AccessState.Pending)
            {
                ExTraceGlobals.SiteMailboxPermissionCheckTracer.TraceDebug((long)sessionHashCode, "SharepointAccessManager.UpdateAccessTokenIfNeeded: Skip because there is an pending request");
                return(true);
            }
            if (accessState == AccessState.Allowed)
            {
                if (!accessingUserSecurityContext.AddGroupSids(new SidBinaryAndAttributes[]
                {
                    new SidBinaryAndAttributes(WellKnownSids.SiteMailboxGrantedAccessMembers, 4U)
                }))
                {
                    ExTraceGlobals.SiteMailboxPermissionCheckTracer.TraceError((long)sessionHashCode, "SharepointAccessManager.UpdateAccessTokenIfNeeded: Failed to add SiteMailboxGrantedAccessMembers group sid to access token");
                    return(false);
                }
                ExTraceGlobals.SiteMailboxPermissionCheckTracer.TraceDebug <ClientSecurityContext, string, string>((long)sessionHashCode, "SharepointAccessManager.UpdateAccessTokenIfNeeded: Access is allowed for user {0}, site mailbox {1}, URL {2}", accessingUserSecurityContext, siteMailbox.MailboxInfo.PrimarySmtpAddress.ToString(), sharepointUrl.AbsoluteUri);
                if (flag)
                {
                    ProtocolLog.LogInformation(ProtocolLog.Component.SharepointAccessManager, loggingContext, string.Format("Allow access for site mailbox {0}, URL {1}", siteMailbox.MailboxInfo.PrimarySmtpAddress.ToString(), sharepointUrl));
                }
            }
            else if (flag)
            {
                ProtocolLog.LogInformation(ProtocolLog.Component.SharepointAccessManager, loggingContext, string.Format("Deny access for site mailbox {0}, URL {1}", siteMailbox.MailboxInfo.PrimarySmtpAddress.ToString(), sharepointUrl));
            }
            return(true);
        }
Example #14
0
 private void Initialize()
 {
     ProtocolLog.instance.logInstance = new Log(ProtocolLog.GetLogFileName(), new LogHeaderFormatter(ProtocolLog.LogSchema), "TeamMailboxSyncLog");
     ProtocolLog.instance.logInstance.Configure(Path.Combine(ExchangeSetupContext.InstallPath, "Logging\\TeamMailbox\\"), ProtocolLog.LogMaxAge, 262144000L, 10485760L);
 }
Example #15
0
 public static void LogError(ProtocolLog.Component component, LoggingContext loggingContext, string data, Exception exception)
 {
     ProtocolLog.LogEvent(component, ProtocolLog.EventType.Error, loggingContext, data, exception);
 }
Example #16
0
        protected virtual Exception ProcessNewOwnersAndMembers(Guid mailboxGuid, List <ADObjectId> newOwners, List <ADObjectId> newMembers)
        {
            Exception ex = null;

            try
            {
                this.mailbox = (this.recipientSession.FindByExchangeGuid(mailboxGuid) as ADUser);
                if (this.mailbox == null)
                {
                    throw new ObjectNotFoundException(new LocalizedString("Cannot find the team mailbox by mailbox guid " + mailboxGuid));
                }
                this.tm = TeamMailbox.FromDataObject(this.mailbox);
            }
            catch (ADTransientException ex2)
            {
                ex = ex2;
            }
            catch (ADExternalException ex3)
            {
                ex = ex3;
            }
            catch (ADOperationException ex4)
            {
                ex = ex4;
            }
            catch (DataValidationException ex5)
            {
                ex = ex5;
            }
            catch (ObjectNotFoundException ex6)
            {
                ex = ex6;
            }
            if (ex != null)
            {
                ProtocolLog.LogError(this.loggingComponent, this.loggingContext, string.Format("MembershipSynchronizer.ProcessNewOwnersAndMembers: Failed to find team mailbox {0}", (this.mailbox == null) ? mailboxGuid.ToString() : this.mailbox.PrimarySmtpAddress.ToString()), ex);
                return(ex);
            }
            this.membershipHelper = new TeamMailboxMembershipHelper(this.tm, this.recipientSession);
            TeamMailboxNotificationHelper teamMailboxNotificationHelper = null;

            if (this.isFirstSync)
            {
                teamMailboxNotificationHelper = new TeamMailboxNotificationHelper(this.tm, this.recipientSession);
                ADObjectId adobjectId = (this.tm.OwnersAndMembers.Count > 0) ? this.tm.OwnersAndMembers[0] : null;
                try
                {
                    if (adobjectId != null)
                    {
                        List <ADObjectId> list = MembershipSynchronizer.ListForSingleId(adobjectId);
                        ProtocolLog.LogStatistics(this.loggingComponent, this.loggingContext, string.Format("MembershipSynchronizer.ProcessNewOwnersAndMembers: the following users have been added to team mailbox {0}: {1}", this.mailbox.PrimarySmtpAddress, MembershipSynchronizer.GetUsersString(list)));
                        int count = this.tm.Owners.Count;
                        teamMailboxNotificationHelper.SendNotification(list, TeamMailboxNotificationType.MemberInvitation);
                    }
                }
                catch (StorageTransientException ex7)
                {
                    ex = ex7;
                }
                catch (StoragePermanentException ex8)
                {
                    ex = ex8;
                }
                if (ex != null)
                {
                    ProtocolLog.LogError(this.loggingComponent, this.loggingContext, string.Format("MembershipSynchronizer.ProcessNewOwnersAndMembers: failed sending notifications for team mailbox {0}", this.mailbox.PrimarySmtpAddress), ex);
                }
            }
            new List <ADObjectId>();
            IList <ADObjectId> newUserList = TeamMailbox.MergeUsers(newOwners, newMembers);
            IList <ADObjectId> userList;
            IList <ADObjectId> list2;
            bool flag = this.membershipHelper.UpdateTeamMailboxUserList(this.tm.Owners, newOwners, out userList, out list2);
            IList <ADObjectId> list3;
            IList <ADObjectId> list4;
            bool flag2 = this.membershipHelper.UpdateTeamMailboxUserList(this.tm.OwnersAndMembers, newUserList, out list3, out list4);

            if (flag || flag2)
            {
                TeamMailbox.DiffUsers(list3, userList);
                try
                {
                    this.membershipHelper.SetTeamMailboxUserPermissions(list3, list4, null, true);
                }
                catch (OverflowException ex9)
                {
                    ex = ex9;
                }
                catch (COMException ex10)
                {
                    ex = ex10;
                }
                catch (UnauthorizedAccessException ex11)
                {
                    ex = ex11;
                }
                catch (TransientException ex12)
                {
                    ex = ex12;
                }
                catch (DataSourceOperationException ex13)
                {
                    ex = ex13;
                }
                if (ex != null)
                {
                    ProtocolLog.LogError(this.loggingComponent, this.loggingContext, string.Format("MembershipSynchronizer.ProcessNewOwnersAndMembers: failed setting AD permissions for team mailbox {0}", this.mailbox.PrimarySmtpAddress), ex);
                    return(ex);
                }
                ProtocolLog.LogStatistics(this.loggingComponent, this.loggingContext, string.Format("MembershipSynchronizer.ProcessNewOwnersAndMembers: the following users have been added to team mailbox {0}: {1}", this.mailbox.PrimarySmtpAddress, MembershipSynchronizer.GetUsersString(list3)));
                ProtocolLog.LogStatistics(this.loggingComponent, this.loggingContext, string.Format("MembershipSynchronizer.ProcessNewOwnersAndMembers: the following users have been removed from team mailbox {0}: {1}", this.mailbox.PrimarySmtpAddress, MembershipSynchronizer.GetUsersString(list4)));
                try
                {
                    this.teamMailboxSecurityRefresher.Refresh(this.mailbox, this.recipientSession);
                }
                catch (DatabaseNotFoundException ex14)
                {
                    ex = ex14;
                }
                catch (ObjectNotFoundException ex15)
                {
                    ex = ex15;
                }
                if (ex != null)
                {
                    ProtocolLog.LogError(this.loggingComponent, this.loggingContext, string.Format("MembershipSynchronizer.ProcessNewOwnersAndMembers: failed setting team mailbox {0} store permissions for userToAdd {1} and usersToRemove {2}", this.mailbox.PrimarySmtpAddress, MembershipSynchronizer.GetUsersString(list3), MembershipSynchronizer.GetUsersString(list4)), ex);
                }
                if (teamMailboxNotificationHelper == null)
                {
                    teamMailboxNotificationHelper = new TeamMailboxNotificationHelper(this.tm, this.recipientSession);
                }
                try
                {
                    teamMailboxNotificationHelper.SendNotification(list3, TeamMailboxNotificationType.MemberInvitation);
                }
                catch (StorageTransientException ex16)
                {
                    ex = ex16;
                }
                catch (StoragePermanentException ex17)
                {
                    ex = ex17;
                }
                if (ex != null)
                {
                    ProtocolLog.LogError(this.loggingComponent, this.loggingContext, string.Format("MembershipSynchronizer.ProcessNewOwnersAndMembers: failed sending member invitation for team mailbox {0}", this.mailbox.PrimarySmtpAddress), ex);
                }
                this.usersToUpdateShowInMyClient = new MembershipSynchronizer.UsersToUpdateShowInMyClient(list3, list4, this);
                while (this.usersToUpdateShowInMyClient.UpdateNextBatch())
                {
                    TimeSpan timeSpan;
                    this.IsThrottleDelayNeeded(out timeSpan);
                }
            }
            return(ex);
        }
Example #17
0
        protected virtual void OnGetUsersComplete(IAsyncResult asyncResult)
        {
            if (asyncResult == null)
            {
                throw new InvalidOperationException("OnGetUsersComplete: asyncResult or the AsynState cannot be null here.");
            }
            if (base.HandleShutDown())
            {
                return;
            }
            Exception ex        = null;
            XmlReader xmlReader = this.EndGetUsers((ICancelableAsyncResult)asyncResult, out ex);

            if (ex != null)
            {
                this.executionAsyncResult.InvokeCallback(ex);
                return;
            }
            List <ADObjectId> list    = new List <ADObjectId>();
            bool          flag        = false;
            Guid          mailboxGuid = this.Job.SyncInfoEntry.MailboxGuid;
            List <string> list2       = new List <string>();
            List <string> list3       = new List <string>();

            try
            {
                using (xmlReader)
                {
                    MembershipSynchronizer.ParseUsers(xmlReader, MembershipSynchronizer.isMultiTenant, out list2, out list3);
                }
            }
            catch (XmlException value)
            {
                this.executionAsyncResult.InvokeCallback(value);
                return;
            }
            foreach (string text in list2)
            {
                try
                {
                    Exception  ex2;
                    ADRawEntry adrawEntry = TeamMailboxNameIdResolver.Resolve(this.recipientSession, text, out ex2);
                    if (ex2 != null)
                    {
                        ProtocolLog.LogError(this.loggingComponent, this.loggingContext, string.Format("MembershipSynchronizer.OnGetUsersComplete: Skip the update for user {0} because we failed to resolve it", text), ex2);
                    }
                    else if (adrawEntry != null)
                    {
                        if (TeamMailboxMembershipHelper.IsUserQualifiedType(adrawEntry))
                        {
                            if (this.newOwners.Count + list.Count >= 1800)
                            {
                                flag = true;
                                break;
                            }
                            list.Add(adrawEntry.Id);
                        }
                        else
                        {
                            ProtocolLog.LogStatistics(this.loggingComponent, this.loggingContext, string.Format("MembershipSynchronizer.OnGetUsersComplete: Drop unqualified owner {0} for team mailbox {1}", adrawEntry.Id, mailboxGuid));
                        }
                    }
                }
                catch (NonUniqueRecipientException exception)
                {
                    ProtocolLog.LogError(this.loggingComponent, this.loggingContext, string.Format("MembershipSynchronizer.OnGetUsersComplete: Skip the update for user {0} because of NonUniqueRecipientException", text), exception);
                }
            }
            if (!this.doneDownloadingOwners)
            {
                this.newOwners             = list;
                this.doneDownloadingOwners = true;
                this.BeginDownloadUsers(new AsyncCallback(this.OnGetUsersComplete), false);
                return;
            }
            this.newMembers = list;
            if (flag)
            {
                ProtocolLog.LogError(this.loggingComponent, this.loggingContext, string.Format("MembershipSynchronizer.OnGetUsersComplete: the total user count is more than TotalOwnersAndMembersLimit ({0}), updated {1} users only for team mailbox {2}.", 1800, 1800, mailboxGuid), new NotSupportedException());
            }
            Exception value2 = this.ProcessNewOwnersAndMembers(mailboxGuid, this.newOwners, this.newMembers);

            this.executionAsyncResult.InvokeCallback(value2);
        }
Example #18
0
 public static void LogInformation(ProtocolLog.Component component, LoggingContext loggingContext, string data)
 {
     ProtocolLog.LogEvent(component, ProtocolLog.EventType.Information, loggingContext, data, null);
 }
Example #19
0
 public static void LogCycleSuccess(ProtocolLog.Component component, LoggingContext loggingContext, string data)
 {
     ProtocolLog.LogEvent(component, ProtocolLog.EventType.CycleSuccess, loggingContext, data, null);
 }
Example #20
0
 public static void LogStatistics(ProtocolLog.Component component, LoggingContext loggingContext, string data)
 {
     ProtocolLog.LogEvent(component, ProtocolLog.EventType.Statistics, loggingContext, data, null);
 }
Example #21
0
 public static void LogCycleFailure(ProtocolLog.Component component, LoggingContext loggingContext, string data, Exception exception)
 {
     ProtocolLog.LogEvent(component, ProtocolLog.EventType.CycleFailure, loggingContext, data, exception);
 }