コード例 #1
0
 public void RegisterSample(uint heartbeatInterval, INotificationManagerContext context)
 {
     if (context.DeviceIdentity.DeviceType.StartsWith("TestActiveSyncConnectivity"))
     {
         return;
     }
     lock (this.hbiSamples)
     {
         uint num = this.hbiSamples[this.insertionIndex];
         this.hbiSamples[this.insertionIndex] = heartbeatInterval;
         this.insertionIndex = (this.insertionIndex + 1) % this.hbiSamples.Length;
         this.hbiSum        += heartbeatInterval;
         this.hbiSum        -= num;
         if ((ulong)this.numSamples == (ulong)((long)this.hbiSamples.Length))
         {
             uint num2 = this.hbiSum / this.numSamples;
             if ((ulong)num2 <= (ulong)((long)this.heartbeatAlertThreshold))
             {
                 string text = context.CommandType.ToString();
                 AirSyncDiagnostics.LogPeriodicEvent(AirSyncEventLogConstants.Tuple_AverageHbiTooLow, text, new string[]
                 {
                     num2.ToString(CultureInfo.InvariantCulture),
                     text,
                     this.heartbeatAlertThreshold.ToString(CultureInfo.InvariantCulture)
                 });
             }
         }
         else
         {
             this.numSamples += 1U;
         }
     }
 }
コード例 #2
0
        // Token: 0x06000590 RID: 1424 RVA: 0x000210DC File Offset: 0x0001F2DC
        private static void ProcessForADAdds(IConfigurationSession scopedSession, DeviceClassCache.DeviceClassDataSet localDataSet, DeviceClassCache.DeviceClassDataSet dataSetFromAD, ref int totalADWriteCount, int perOrgDeleteCount)
        {
            int num = 0;

            foreach (DeviceClassCache.DeviceClassData deviceClassData in localDataSet)
            {
                if (totalADWriteCount >= GlobalSettings.DeviceClassCacheMaxADUploadCount)
                {
                    AirSyncDiagnostics.TraceDebug <int>(ExTraceGlobals.RequestsTracer, null, "2. Stop updating AD because the cap is reached: adUpdateCount={0}", totalADWriteCount);
                    break;
                }
                if (!dataSetFromAD.Contains(deviceClassData))
                {
                    if (dataSetFromAD.Count + num - perOrgDeleteCount >= GlobalSettings.DeviceClassPerOrgMaxADCount)
                    {
                        AirSyncDiagnostics.TraceDebug <int, int>(ExTraceGlobals.RequestsTracer, null, "Stop adding new device class node to AD because the cap is reached: dataSetFromAD.Count={0}, DeviceClassPerOrgMaxADCount={1}", dataSetFromAD.Count, GlobalSettings.DeviceClassPerOrgMaxADCount);
                        break;
                    }
                    if (dataSetFromAD.Count + num >= DeviceClassCache.ADCapWarningThreshold)
                    {
                        AirSyncDiagnostics.TraceDebug <int, int>(ExTraceGlobals.RequestsTracer, null, "Still adding new device class node to AD but the cap is close to be reached: dataSetFromAD.Count={0}, DeviceClassPerOrgMaxADCount={1}", dataSetFromAD.Count, DeviceClassCache.ADCapWarningThreshold);
                        AirSyncDiagnostics.LogPeriodicEvent(AirSyncEventLogConstants.Tuple_TooManyDeviceClassNodes, localDataSet.OrganizationId.ToString(), new string[]
                        {
                            dataSetFromAD.Count.ToString(),
                            localDataSet.OrganizationId.ToString(),
                            GlobalSettings.DeviceClassPerOrgMaxADCount.ToString()
                        });
                    }
                    DeviceClassCache.CreateOrUpdateActiveSyncDeviceClass(scopedSession, deviceClassData, localDataSet.OrganizationId);
                    num++;
                    totalADWriteCount++;
                }
            }
        }
コード例 #3
0
 internal void SendABQNotificationMail()
 {
     using (MailboxSession mailboxSession = MailboxSession.OpenAsSystemService(this.context.User.ExchangePrincipal, this.context.Request.Culture, "Client=ActiveSync;Action=ABQMail"))
     {
         this.cultureInfo = mailboxSession.PreferedCulture;
         MicrosoftExchangeRecipient exchangeRecipient = this.organizationSettings.GetExchangeRecipient();
         StoreObjectId defaultFolderId = mailboxSession.GetDefaultFolderId(DefaultFolderType.Inbox);
         using (MessageItem messageItem = MessageItem.Create(mailboxSession, defaultFolderId))
         {
             this.ConstructUserNotificationMail(messageItem);
             messageItem.From = ((exchangeRecipient == null) ? new Participant(mailboxSession.MailboxOwner) : new Participant(exchangeRecipient));
             messageItem.Recipients.Add(new Participant(mailboxSession.MailboxOwner), RecipientItemType.To);
             messageItem[MessageItemSchema.IsDraft] = false;
             messageItem[MessageItemSchema.IsRead]  = false;
             messageItem.Save(SaveMode.NoConflictResolution);
             messageItem.Load(new PropertyDefinition[0]);
             this.globalInfo.ABQMailId    = messageItem.Id.ObjectId;
             this.globalInfo.ABQMailState = ABQMailState.MailPosted;
         }
         defaultFolderId = mailboxSession.GetDefaultFolderId(DefaultFolderType.Drafts);
         if (this.globalInfo.DeviceAccessState == DeviceAccessState.Quarantined)
         {
             using (MessageItem messageItem2 = MessageItem.Create(mailboxSession, defaultFolderId))
             {
                 foreach (SmtpAddress smtpAddress in this.organizationSettings.AdminMailRecipients)
                 {
                     Participant participant;
                     if (smtpAddress.IsValidAddress && Participant.TryParse(smtpAddress.ToString(), out participant) && participant != null)
                     {
                         messageItem2.Recipients.Add(participant, RecipientItemType.To);
                     }
                 }
                 if (messageItem2.Recipients.Count > 0)
                 {
                     this.ConstructAdminNotificationMail(messageItem2);
                     messageItem2.From = ((exchangeRecipient == null) ? new Participant(mailboxSession.MailboxOwner) : new Participant(exchangeRecipient));
                     messageItem2.SendWithoutSavingMessage();
                 }
                 else
                 {
                     AirSyncDiagnostics.TraceError(ExTraceGlobals.RequestsTracer, null, "ABQMail:No valid AdminMailRecipients to send Admin mail to!");
                     if (VariantConfiguration.InvariantNoFlightingSnapshot.ActiveSync.ActiveSyncDiagnosticsLogABQPeriodicEvent.Enabled)
                     {
                         AirSyncDiagnostics.LogPeriodicEvent(AirSyncEventLogConstants.Tuple_NoAdminMailRecipientsError, "NoAdminMailRecipients", new string[0]);
                     }
                 }
             }
         }
     }
 }
コード例 #4
0
 private void BackEndReadContent(IAsyncResult asynchronousResult)
 {
     lock (this)
     {
         if (this.requestWasTimedOut)
         {
             AirSyncDiagnostics.TraceDebug(ExTraceGlobals.RequestsTracer, this, "ProxyHandler.BackEndReadContent() Request was timed out while waiting for lock!");
             string text = this.remoteUri.Host.ToString();
             AirSyncDiagnostics.LogPeriodicEvent(AirSyncEventLogConstants.Tuple_ProxyResultTimedOut, text, new string[]
             {
                 text
             });
             return;
         }
     }
     try
     {
         AirSyncDiagnostics.TraceDebug <Uri, string>(ExTraceGlobals.RequestsTracer, this, "ProxyHandler.BackEndReadContent called for serverName: {0}, user {1}", this.remoteUri, this.userName);
         this.UnregisterTimeoutWaitHandle();
         int num = this.backEndResponseStream.EndRead(asynchronousResult);
         if (num > 0)
         {
             this.frontEndHttpContext.Response.OutputStream.Write(this.asyncBuffer, 0, num);
             this.backEndResponseStream = this.httpWebResponse.GetResponseStream();
             this.pendingAsyncOperation = ProxyHandler.PendingOperationState.BackEndReadContent;
             IAsyncResult asyncResult = this.backEndResponseStream.BeginRead(this.asyncBuffer, 0, this.asyncBuffer.Length, new AsyncCallback(this.BackEndReadContent), null);
             if (!asyncResult.CompletedSynchronously)
             {
                 this.RegisterTimeoutWaitHandle(asyncResult, (int)GlobalSettings.ProxyHandlerShortTimeout.TotalMilliseconds);
             }
         }
         else
         {
             this.UnregisterTimeoutWaitHandle();
             this.frontEndResult.InvokeCallback();
             this.ReleaseResources();
         }
     }
     catch (Exception ex)
     {
         AirSyncUtility.ExceptionToStringHelper arg = new AirSyncUtility.ExceptionToStringHelper(ex);
         AirSyncDiagnostics.TraceError <AirSyncUtility.ExceptionToStringHelper>(ExTraceGlobals.RequestsTracer, this, "ProxyHandler.BackEndReadContent caught an exception\r\n{0}", arg);
         if (this.backEndWebRequest != null)
         {
             this.backEndWebRequest.Abort();
             this.backEndWebRequest = null;
         }
         this.HandleException(ex);
     }
 }
コード例 #5
0
        private HttpWebRequest CopyClientRequest(HttpRequest clientrequest, Uri proxyuri)
        {
            string         b = HttpRequestHeader.Authorization.ToString();
            HttpWebRequest httpWebRequest = this.CreateWebRequest(proxyuri);

            httpWebRequest.Method = clientrequest.HttpMethod;
            for (int i = 0; i < clientrequest.Headers.Count; i++)
            {
                string text = clientrequest.Headers.Keys[i];
                if ((!(text == b) || !this.proxyInfo.CanImpersonate) && !WebHeaderCollection.IsRestricted(text))
                {
                    httpWebRequest.Headers[text] = clientrequest.Headers[text];
                }
            }
            CertificateValidationManager.SetComponentId(httpWebRequest, "AirSync");
            foreach (string text2 in this.proxyInfo.AdditionalHeaders.Keys)
            {
                httpWebRequest.Headers[text2] = this.proxyInfo.AdditionalHeaders[text2];
            }
            if (GlobalSettings.IsGCCEnabled)
            {
                if (GlobalSettings.AreGccStoredSecretKeysValid)
                {
                    string text3 = httpWebRequest.Headers["x-gcc-proxyinfo"];
                    if (string.IsNullOrEmpty(text3) || (!string.IsNullOrEmpty(text3) && !ProxyHandler.HasValidAuthString(text3)))
                    {
                        StringBuilder stringBuilder = new StringBuilder(GccUtils.GetAuthStringForThisServer());
                        stringBuilder.Append(", ");
                        stringBuilder.Append(clientrequest.ServerVariables["REMOTE_ADDR"]);
                        stringBuilder.Append(", ");
                        stringBuilder.Append(clientrequest.ServerVariables["LOCAL_ADDR"]);
                        httpWebRequest.Headers["x-gcc-proxyinfo"] = stringBuilder.ToString();
                    }
                }
                else
                {
                    AirSyncDiagnostics.LogPeriodicEvent(AirSyncEventLogConstants.Tuple_NoGccStoredSecretKey, "NoGccStoredSecretKey", new string[0]);
                    AirSyncDiagnostics.TraceError(ExTraceGlobals.RequestsTracer, null, "No gcc stored secret key");
                }
            }
            httpWebRequest.Referer     = clientrequest.Url.AbsoluteUri;
            httpWebRequest.ContentType = clientrequest.ContentType;
            httpWebRequest.UserAgent   = clientrequest.UserAgent;
            return(httpWebRequest);
        }
コード例 #6
0
        private static void HandleMultipleDefaultPolicies(MobileMailboxPolicy[] defaultPolicies, ADObjectId organizationalUnitRoot, ProtocolLogger protocollogger)
        {
            StringBuilder stringBuilder = new StringBuilder();

            for (int i = 0; i < defaultPolicies.Length; i++)
            {
                if (i != 0)
                {
                    stringBuilder.Append(",");
                }
                stringBuilder.Append(defaultPolicies[i].Identity);
            }
            AirSyncDiagnostics.LogPeriodicEvent(AirSyncEventLogConstants.Tuple_MultipleDefaultMobileMailboxPoliciesDetected, "MultipleDefaultMobileMailboxPoliciesDetected", new string[]
            {
                organizationalUnitRoot.Parent.Name,
                stringBuilder.ToString()
            });
            protocollogger.SetValue(ProtocolLoggerData.Error, "MultipleDefaultPoliciesDetected");
        }
コード例 #7
0
        private void TimeoutCallback(object state, bool timedOut)
        {
            if (!timedOut)
            {
                AirSyncDiagnostics.TraceInfo <ProxyHandler.PendingOperationState, TimeSpan>(ExTraceGlobals.RequestsTracer, null, "ProxyHandler.TimeoutCallback() Async request is being completed in the callback. State {0}! Processing time {1}", this.pendingAsyncOperation, ExDateTime.Now - this.issueTime);
                return;
            }
            IAsyncResult asyncResult = state as IAsyncResult;

            lock (this)
            {
                if (asyncResult.IsCompleted || this.requestWasTimedOut || this.frontEndResult == null || this.frontEndResult.IsCompleted)
                {
                    AirSyncDiagnostics.TraceInfo(ExTraceGlobals.RequestsTracer, this, "ProxyHandler.TimeoutCallback() Request was completed while waiting for lock. State {0} AsyncResult.IsCompleted {1} requestWasTimedOut {2} frontEndResult.IsCompleted {3}!", new object[]
                    {
                        this.pendingAsyncOperation,
                        asyncResult.IsCompleted,
                        this.requestWasTimedOut,
                        this.frontEndResult == null || this.frontEndResult.IsCompleted
                    });
                }
                else
                {
                    AirSyncDiagnostics.TraceInfo <ProxyHandler.PendingOperationState, IAsyncResult>(ExTraceGlobals.RequestsTracer, this, "ProxyHandler.TimeoutCallback() Aborting request that timed out in state {0} ASyncResult {1}!", this.pendingAsyncOperation, asyncResult);
                    string text = this.proxyInfo.RemoteUri.Host.ToString();
                    AirSyncDiagnostics.LogPeriodicEvent(AirSyncEventLogConstants.Tuple_ProxyResultTimedOut, text, new string[]
                    {
                        text
                    });
                    this.requestWasTimedOut = true;
                    this.backEndWebRequest.Abort();
                    this.frontEndHttpContext.Response.StatusCode = 503;
                    this.frontEndResult.InvokeCallback();
                    this.ReleaseResources();
                }
            }
        }
コード例 #8
0
 private void BackEndGetResponse(IAsyncResult asynchronousResult)
 {
     lock (this)
     {
         if (this.requestWasTimedOut)
         {
             AirSyncDiagnostics.TraceDebug(ExTraceGlobals.RequestsTracer, this, "ProxyHandler.BackEndGetResponse() Request was timed out while waiting for lock!");
             string text = this.remoteUri.Host.ToString();
             AirSyncDiagnostics.LogPeriodicEvent(AirSyncEventLogConstants.Tuple_ProxyResultTimedOut, text, new string[]
             {
                 text
             });
             return;
         }
     }
     try
     {
         AirSyncDiagnostics.TraceDebug <Uri, string>(ExTraceGlobals.RequestsTracer, this, "ProxyHandler.BackEndGetResponse called for serverName: {0}, user {1}", this.remoteUri, this.userName);
         this.UnregisterTimeoutWaitHandle();
         try
         {
             this.httpWebResponse = (HttpWebResponse)this.backEndWebRequest.EndGetResponse(asynchronousResult);
         }
         catch (WebException ex)
         {
             if (ex.Status == WebExceptionStatus.ProtocolError)
             {
                 HttpWebResponse httpWebResponse = ex.Response as HttpWebResponse;
                 if (httpWebResponse == null)
                 {
                     this.HandleException(ex);
                     return;
                 }
                 if (httpWebResponse.StatusCode == (HttpStatusCode)441)
                 {
                     httpWebResponse.Close();
                     if (!this.proxyInfo.AttemptProxyLogin)
                     {
                         AirSyncDiagnostics.TraceDebug <string>(ExTraceGlobals.RequestsTracer, this, "BackEndGetResponse(): authentication failure for {0}.", this.userName);
                         this.TryUnregisterTimeoutWaitHandle();
                         this.frontEndHttpContext.Response.StatusCode = 403;
                         this.frontEndResult.InvokeCallback();
                         return;
                     }
                     AirSyncDiagnostics.Assert(!this.proxyInfo.RequiresImpersonation && this.proxyInfo.AdditionalHeaders != null);
                     AirSyncDiagnostics.TraceDebug <string>(ExTraceGlobals.RequestsTracer, this, "BackEndGetResponse(): proxy login required for {0}.", this.userName);
                     if (this.proxyLoginAttempts > 0)
                     {
                         AirSyncDiagnostics.TraceFunction(ExTraceGlobals.RequestsTracer, this, "BackEndGetResponse(): too many login attempts.");
                         this.protocolLogger.SetValue(ProtocolLoggerData.Error, "TooManyProxyLoginAttempts");
                         this.TryUnregisterTimeoutWaitHandle();
                         this.frontEndHttpContext.Response.StatusCode = 403;
                         this.frontEndResult.InvokeCallback();
                         return;
                     }
                     this.proxyLoginAttempts++;
                     this.IssueProxyLoginRequest();
                     return;
                 }
                 else
                 {
                     if (httpWebResponse.Headers != null)
                     {
                         WebHeaderCollection headers = httpWebResponse.Headers;
                         string text2 = headers["WWW-Authenticate"];
                         if (text2 != null && text2.IndexOf("Negotiate ") == -1)
                         {
                             if (this.HasBeenProxiedByMServ)
                             {
                                 this.protocolLogger.SetValue(ProtocolLoggerData.Error, "Datacenter Config issue upon MServ proxy");
                             }
                             else
                             {
                                 this.protocolLogger.SetValue(ProtocolLoggerData.Error, "NTLM not on the destination CAS");
                                 string text3 = this.proxyInfo.RemoteUri.Host.ToString();
                                 AirSyncDiagnostics.LogPeriodicEvent(AirSyncEventLogConstants.Tuple_SecondCasFailureNTLM, text3, new string[]
                                 {
                                     text3
                                 });
                             }
                         }
                     }
                     this.httpWebResponse = httpWebResponse;
                 }
             }
             else
             {
                 if (ex.Status == WebExceptionStatus.TrustFailure)
                 {
                     AirSyncDiagnostics.TraceDebug <string>(ExTraceGlobals.RequestsTracer, this, "SSL Certification failed for {0}.", this.proxyInfo.RemoteUri.Host);
                     this.protocolLogger.SetValue(ProtocolLoggerData.Error, "SSL Certification Failed.");
                     string text4 = this.proxyInfo.RemoteUri.Host.ToString();
                     AirSyncDiagnostics.LogPeriodicEvent(AirSyncEventLogConstants.Tuple_SecondCasFailureSSL, text4, new string[]
                     {
                         text4
                     });
                     this.HandleException(ex);
                     return;
                 }
                 this.HandleException(ex);
                 return;
             }
         }
         if (GlobalSettings.ProxyHeaders != null && GlobalSettings.ProxyHeaders.Length > 0)
         {
             this.frontEndHttpContext.Response.ContentType = string.Empty;
             for (int i = 0; i < this.httpWebResponse.Headers.Count; i++)
             {
                 string text5 = this.httpWebResponse.Headers.Keys[i];
                 for (int j = 0; j < GlobalSettings.ProxyHeaders.Length; j++)
                 {
                     if (string.Equals(text5, GlobalSettings.ProxyHeaders[j], StringComparison.OrdinalIgnoreCase))
                     {
                         this.frontEndHttpContext.Response.AppendHeader(text5, this.httpWebResponse.Headers[text5]);
                     }
                 }
             }
         }
         this.backEndResponseStream = this.httpWebResponse.GetResponseStream();
         this.frontEndHttpContext.Response.StatusCode        = (int)this.httpWebResponse.StatusCode;
         this.frontEndHttpContext.Response.StatusDescription = this.httpWebResponse.StatusDescription;
         this.pendingAsyncOperation = ProxyHandler.PendingOperationState.BackEndReadContent;
         IAsyncResult asyncResult = this.backEndResponseStream.BeginRead(this.asyncBuffer, 0, this.asyncBuffer.Length, new AsyncCallback(this.BackEndReadContent), null);
         if (!asyncResult.CompletedSynchronously)
         {
             this.RegisterTimeoutWaitHandle(asyncResult, (int)GlobalSettings.ProxyHandlerShortTimeout.TotalMilliseconds);
         }
     }
     catch (Exception ex2)
     {
         AirSyncUtility.ExceptionToStringHelper arg = new AirSyncUtility.ExceptionToStringHelper(ex2);
         AirSyncDiagnostics.TraceError <AirSyncUtility.ExceptionToStringHelper>(ExTraceGlobals.RequestsTracer, this, "ProxyHandler.BackEndGetResponse caught an exception\r\n{0}", arg);
         if (this.backEndWebRequest != null)
         {
             this.backEndWebRequest.Abort();
             this.backEndWebRequest = null;
         }
         this.HandleException(ex2);
     }
 }
コード例 #9
0
        // Token: 0x060000B7 RID: 183 RVA: 0x00007A20 File Offset: 0x00005C20
        private ActiveSyncDevices CreateActiveSyncDeviceContainer(bool retryIfFailed)
        {
            ActiveSyncDevices container = new ActiveSyncDevices();

            try
            {
                container.Name = "ExchangeActiveSyncDevices";
                container.SetId(this.userId.GetChildId(container.Name));
                container.OrganizationId = this.organizationId;
                ADNotificationAdapter.RunADOperation(delegate()
                {
                    this.session.Save(container);
                    this.session.DomainController = container.OriginatingServer;
                });
            }
            catch (ADObjectAlreadyExistsException innerException)
            {
                container = this.GetActiveSyncDeviceContainer();
                if (container == null)
                {
                    throw new AirSyncPermanentException(HttpStatusCode.InternalServerError, StatusCode.ServerErrorRetryLater, innerException, false)
                          {
                              ErrorStringForProtocolLogger = "ADObjectAlreadyExistsException:ButDevicesContainerDoesNotExist"
                          };
                }
            }
            catch (ADOperationException ex)
            {
                AirSyncDiagnostics.LogPeriodicEvent(AirSyncEventLogConstants.Tuple_UnableToCreateADDevicesContainer, container.Name, new string[]
                {
                    this.userId.ToDNString(),
                    ex.Message
                });
                throw new AirSyncPermanentException(HttpStatusCode.InternalServerError, StatusCode.ServerErrorRetryLater, ex, false)
                      {
                          ErrorStringForProtocolLogger = "ADOperationException1:" + ex.Message
                      };
            }
            bool flag = false;

            try
            {
                this.SetActiveSyncDeviceContainerPermissions(container);
                flag = true;
            }
            catch (ADNoSuchObjectException innerException2)
            {
                if (retryIfFailed)
                {
                    return(this.CreateActiveSyncDeviceContainer(false));
                }
                throw new AirSyncPermanentException(HttpStatusCode.InternalServerError, StatusCode.ServerErrorRetryLater, innerException2, false)
                      {
                          ErrorStringForProtocolLogger = "ADNoSuchObjectException:OnDevicesContainerPermsSet"
                      };
            }
            catch (ADOperationException ex2)
            {
                AirSyncDiagnostics.LogPeriodicEvent(AirSyncEventLogConstants.Tuple_UnableToCreateADDevicesContainer, "ExchangeActiveSyncDevices", new string[]
                {
                    this.userId.ToDNString(),
                    ex2.Message
                });
                throw new AirSyncPermanentException(HttpStatusCode.InternalServerError, StatusCode.ServerErrorRetryLater, ex2, false)
                      {
                          ErrorStringForProtocolLogger = "ADOperationException2:" + ex2.Message
                      };
            }
            finally
            {
                if (!flag)
                {
                    try
                    {
                        ADNotificationAdapter.RunADOperation(delegate()
                        {
                            this.session.Delete(container);
                        });
                    }
                    catch (LocalizedException arg)
                    {
                        AirSyncDiagnostics.TraceError <LocalizedException>(this.tracer, this, "Failed to delete user container {0}", arg);
                    }
                }
            }
            return(container);
        }
コード例 #10
0
        public void ParseQueryNode(XmlElement queryNode)
        {
            this.searchCriteriaBuilder = new MailboxSearchCriteriaBuilder(this.context.Request.Culture);
            if (!this.mailboxSession.Mailbox.IsContentIndexingEnabled)
            {
                AirSyncDiagnostics.LogPeriodicEvent(AirSyncEventLogConstants.Tuple_ContentIndexingNotEnabled, "ContentIndexingNotEnabled", new string[]
                {
                    this.mailboxSession.MailboxOwner.MailboxInfo.Location.ServerFqdn
                });
            }
            this.queryFilter = this.searchCriteriaBuilder.ParseTopLevelClassAndFolders(queryNode, this.mailboxSession.Mailbox.IsContentIndexingEnabled, this.versionFactory, this.context);
            this.schemaCache = this.searchCriteriaBuilder.SchemaCache;
            if (this.FolderIdMappingSyncState == null || !this.FolderIdMappingSyncState.Contains(CustomStateDatumType.FullFolderTree))
            {
                AirSyncDiagnostics.TraceDebug <string>(ExTraceGlobals.AlgorithmTracer, this, "FolderIdMappingSyncState error: {0}", (this.FolderIdMappingSyncState != null) ? "no FullFolderTree" : "FolderIdMappingSyncState is null");
                throw new SearchNeedToFolderSyncException();
            }
            List <string>   list            = this.searchCriteriaBuilder.FolderScope;
            FolderIdMapping folderIdMapping = (FolderIdMapping)this.FolderIdMappingSyncState[CustomStateDatumType.IdMapping];
            FolderTree      folderTree      = (FolderTree)this.FolderIdMappingSyncState[CustomStateDatumType.FullFolderTree];

            if (list.Count == 0)
            {
                this.folderScope = new StoreId[]
                {
                    this.mailboxSession.GetDefaultFolderId(DefaultFolderType.Root)
                };
            }
            else
            {
                int num = 0;
                this.folderScope = new StoreId[list.Count];
                foreach (string text in list)
                {
                    StoreObjectId storeObjectId = null;
                    if (text == "0")
                    {
                        storeObjectId = this.mailboxSession.GetDefaultFolderId(DefaultFolderType.Root);
                    }
                    else
                    {
                        SyncCollection.CollectionTypes collectionType = AirSyncUtility.GetCollectionType(text);
                        if (collectionType != SyncCollection.CollectionTypes.Mailbox && collectionType != SyncCollection.CollectionTypes.Unknown)
                        {
                            throw new AirSyncPermanentException(StatusCode.InvalidCombinationOfIDs, false)
                                  {
                                      ErrorStringForProtocolLogger = "BadIdComboInMbxSearch"
                                  };
                        }
                        MailboxSyncItemId mailboxSyncItemId = folderIdMapping[text] as MailboxSyncItemId;
                        if (mailboxSyncItemId != null)
                        {
                            if (folderTree.IsSharedFolder(mailboxSyncItemId))
                            {
                                throw new AirSyncPermanentException(StatusCode.Sync_InvalidParameters, false)
                                      {
                                          ErrorStringForProtocolLogger = "AccessDeniedInMbxSearch"
                                      };
                            }
                            storeObjectId = (StoreObjectId)mailboxSyncItemId.NativeId;
                        }
                    }
                    if (storeObjectId == null)
                    {
                        throw new SearchNeedToFolderSyncException();
                    }
                    try
                    {
                        using (Folder.Bind(this.mailboxSession, storeObjectId))
                        {
                        }
                    }
                    catch (ObjectNotFoundException)
                    {
                        throw new SearchNeedToFolderSyncException();
                    }
                    this.folderScope[num++] = storeObjectId;
                }
            }
            foreach (object obj in folderTree)
            {
                ISyncItemId       syncItemId         = (ISyncItemId)obj;
                MailboxSyncItemId mailboxSyncItemId2 = syncItemId as MailboxSyncItemId;
                if (mailboxSyncItemId2 != null && (folderTree.IsHidden(syncItemId) || folderTree.IsSharedFolder(syncItemId)))
                {
                    this.searchCriteriaBuilder.ExcludedFolders.Add((StoreObjectId)mailboxSyncItemId2.NativeId);
                }
            }
            if (this.mailboxSchemaOptions.HasBodyPartPreferences)
            {
                if (this.searchCriteriaBuilder.Conversation == null)
                {
                    AirSyncDiagnostics.TraceDebug(ExTraceGlobals.AlgorithmTracer, this, "<BodyPartPreference> is only supported when search for ConversationId");
                    throw new AirSyncPermanentException(StatusCode.Sync_ObjectNotFound, false)
                          {
                              ErrorStringForProtocolLogger = "BodyPartNotSupported"
                          };
                }
                this.searchCriteriaBuilder.Conversation.LoadBodySummaries();
            }
        }