private void ReadAndInitializeExceptionPerfCounterSettings()
        {
            string text  = ConfigurationManager.AppSettings["MailboxOfflineExQueueSize"];
            string text2 = ConfigurationManager.AppSettings["ConnectionFailedTransientExQueueSize"];
            string text3 = ConfigurationManager.AppSettings["StorageTransientExQueueSize"];
            string text4 = ConfigurationManager.AppSettings["StoragePermanentExQueueSize"];
            int    num;

            if (!string.IsNullOrEmpty(text) && int.TryParse(text, out num) && num > 0)
            {
                PerformanceCounterManager.MailboxOfflineExResultsQueueSize = num;
            }
            int num2;

            if (!string.IsNullOrEmpty(text2) && int.TryParse(text2, out num2) && num2 > 0)
            {
                PerformanceCounterManager.ConnectionFailedTransientExResultsQueueSize = num2;
            }
            int num3;

            if (!string.IsNullOrEmpty(text4) && int.TryParse(text4, out num3) && num3 > 0)
            {
                PerformanceCounterManager.StoragePermanentExResultsQueueSize = num3;
            }
            int num4;

            if (!string.IsNullOrEmpty(text3) && int.TryParse(text3, out num4) && num4 > 0)
            {
                PerformanceCounterManager.StorageTransientExResultsQueueSize = num4;
            }
            PerformanceCounterManager.InitializeExPerfCountersQueueSizes();
        }
Example #2
0
        // Token: 0x06000FE0 RID: 4064 RVA: 0x000630C4 File Offset: 0x000612C4
        private void UpdateExceptionsPerfCountersQueues(Exception ex)
        {
            bool result  = true;
            bool result2 = true;
            bool result3 = true;
            bool result4 = true;

            if (ex != null)
            {
                if (ex is MailboxOfflineException)
                {
                    result = false;
                }
                else if (ex is ConnectionFailedTransientException)
                {
                    result2 = false;
                }
                else if (ex is StoragePermanentException)
                {
                    result3 = false;
                }
                else if (ex is StorageTransientException)
                {
                    result4 = false;
                }
            }
            PerformanceCounterManager.AddMailboxOfflineExResult(result);
            PerformanceCounterManager.AddConnectionFailedTransientExResult(result2);
            PerformanceCounterManager.AddStoragePermanantExResult(result3);
            PerformanceCounterManager.AddStorageTransientExResult(result4);
        }
        public void Build()
        {
            var logger              = resolver.Resolve <ILogger>();
            var applicationConfig   = resolver.Resolve <LeaseProviderServiceConfiguration>();
            var socketFactory       = new SocketFactory(resolver.Resolve <SocketConfiguration>());
            var synodConfigProvider = new SynodConfigurationProvider(applicationConfig.LeaseProvider.Synod);

#if NET47
            var instanceNameResolver      = resolver.Resolve <IInstanceNameResolver>() ?? new InstanceNameResolver();
            var performanceCounterManager = new PerformanceCounterManager <KinoPerformanceCounters>(instanceNameResolver, logger);
#else
            var performanceCounterManager = default(IPerformanceCounterManager <KinoPerformanceCounters>);
#endif
            var intercomMessageHub = new IntercomMessageHub(socketFactory,
                                                            synodConfigProvider,
                                                            performanceCounterManager,
                                                            logger);
            var ballotGenerator = new BallotGenerator(applicationConfig.LeaseProvider.Lease);
            kino          = new kino(resolver);
            messageHub    = kino.GetMessageHub();
            leaseProvider = new LeaseProvider(intercomMessageHub,
                                              ballotGenerator,
                                              synodConfigProvider,
                                              applicationConfig.LeaseProvider.Lease,
                                              applicationConfig.LeaseProvider,
                                              messageHub,
                                              logger);
            var serializer = new ProtobufMessageSerializer();
            kino.AssignActor(new LeaseProviderActor(leaseProvider, serializer, applicationConfig.LeaseProvider, logger));
            kino.AssignActor(new InstanceDiscoveryActor(leaseProvider, applicationConfig.LeaseProvider));
            kino.AssignActor(new InstanceBuilderActor(leaseProvider, applicationConfig.LeaseProvider));
            kino.AssignActor(new ExceptionHandlerActor(logger));
        }
        private IPerformanceCounterManager <KinoPerformanceCounters> CreatePerfCountersManager()
        {
            var instanceNamedResolver = new InstanceNameResolver();
            var perfCountersManager   = new PerformanceCounterManager <KinoPerformanceCounters>(instanceNamedResolver, logger);

            return(perfCountersManager);
        }
Example #5
0
 public static void TerminateSession(IMailboxContext userContext, CacheItemRemovedReason abandonedReason)
 {
     ExTraceGlobals.UserContextTracer.TraceDebug(0L, "UserContextManager.TerminateSession");
     if (userContext == null)
     {
         throw new ArgumentNullException("userContext");
     }
     try
     {
         userContext.LogBreadcrumb("TerminateSession");
         string text = string.Empty;
         if (userContext.LogonIdentity != null && userContext.LogonIdentity.UserSid != null)
         {
             text = userContext.LogonIdentity.UserSid.ToString();
         }
         if (!string.IsNullOrEmpty(text))
         {
             PerformanceCounterManager.UpdatePerfCounteronUserContextDeletion(text, false, false, Globals.ArePerfCountersEnabled);
         }
     }
     finally
     {
         userContext.Dispose();
         userContext = null;
     }
 }
Example #6
0
        public MainForm()
        {
            InitializeComponent();

            Disposed += MainForm_Disposed;

            m_PerformanceCounterManager = new PerformanceCounterManager();
        }
Example #7
0
        public void GroupThrowsNullExceptionWhenGroupNameIsNull()
        {
            var serializer = JsonUtility.CreateDefaultSerializer();
            var counters   = new PerformanceCounterManager();
            var connection = new Mock <IConnection>();
            var invoker    = new Mock <IHubPipelineInvoker>();
            var hubContext = new HubContext(connection.Object, invoker.Object, "test");

            Assert.Throws <ArgumentException>(() => hubContext.Clients.Group(null));
        }
Example #8
0
        // Token: 0x06000FDD RID: 4061 RVA: 0x00062EB8 File Offset: 0x000610B8
        private void OnEndRequest(object sender, EventArgs e)
        {
            ExTraceGlobals.CoreCallTracer.TraceDebug(0L, "OwaModule.OnEndRequest");
            HttpApplication httpApplication = (HttpApplication)sender;

            if (this.ShouldInterceptRequest(httpApplication.Context, false))
            {
                if (!Globals.IsInitialized)
                {
                    return;
                }
                HttpContext context    = httpApplication.Context;
                OwaContext  owaContext = OwaContext.Get(context);
                if (owaContext == null)
                {
                    return;
                }
                try
                {
                    this.requestInspector.OnEndRequest(owaContext);
                }
                finally
                {
                    if (Globals.FilterETag && VariantConfiguration.GetSnapshot(MachineSettingsContext.Local, null, null).OwaDeployment.FilterETag.Enabled)
                    {
                        context.Response.Headers.Remove("ETag");
                    }
                    long requestLatencyMilliseconds = owaContext.RequestLatencyMilliseconds;
                    if (Globals.OwaVDirType == OWAVDirType.OWA && Globals.ArePerfCountersEnabled)
                    {
                        if (RequestDispatcher.IsUserInitiatedRequest(context.Request))
                        {
                            PerformanceCounterManager.UpdateResponseTimePerformanceCounter(requestLatencyMilliseconds, OwaContext.Current.RequestExecution == RequestExecution.Proxy);
                        }
                        OwaSingleCounters.TotalRequests.Increment();
                        if (owaContext.ErrorInformation != null)
                        {
                            OwaSingleCounters.TotalRequestsFailed.Increment();
                            Exception exception = owaContext.ErrorInformation.Exception;
                            this.UpdateExceptionsPerfCountersQueues(exception);
                        }
                        else
                        {
                            this.UpdateExceptionsPerfCountersQueues(null);
                        }
                        if (owaContext.RequestExecution == RequestExecution.Proxy)
                        {
                            OwaSingleCounters.ProxiedUserRequests.Increment();
                        }
                    }
                    ExTraceGlobals.RequestTracer.TraceDebug <string, long>((long)owaContext.GetHashCode(), "Response: HTTP {0}, time:{1} ms.", owaContext.HttpContext.Response.Status, requestLatencyMilliseconds);
                    OwaDiagnostics.ClearThreadTracing();
                }
            }
        }
Example #9
0
        internal static void RecordUserContextCreation(OwaIdentity logonIdentity, UserContext userContext)
        {
            if (logonIdentity == null)
            {
                throw new ArgumentNullException("logonIdentity");
            }
            if (userContext == null)
            {
                throw new ArgumentNullException("userContext");
            }
            string userName = logonIdentity.UserSid.ToString();

            PerformanceCounterManager.UpdatePerfCounteronUserContextCreation(userName, userContext.IsProxy, userContext.IsBasicExperience, Globals.ArePerfCountersEnabled);
        }
        private IEnumerator <int> ProcessWebResponse(AsyncEnumerator ae, HttpWebResponse webResponse)
        {
            PerformanceCounterManager.AddEwsRequestResult(this.IsOkToProcess(webResponse));
            this.HttpContext.Response.ContentType = webResponse.ContentType;
            using (Stream responseInStream = webResponse.GetResponseStream())
            {
                AsyncResult asyncResult = ae.AddAsyncEnumerator((AsyncEnumerator ae1) => ProxyToEwsEventHandler.CopyStream(ae1, responseInStream, this.HttpContext.Response.OutputStream));
                yield return(1);

                asyncResult.End();
            }
            ae.End();
            yield break;
        }
Example #11
0
        public void SanitizesInstanceNames(string instanceName, string expectedSanitizedName)
        {
            // Details on how to sanitize instance names are at http://msdn.microsoft.com/en-us/library/vstudio/system.diagnostics.performancecounter.instancename

            // Arrange
            var traceManager = new Mock <ITraceManager>();

            traceManager.Setup(tm => tm[It.IsAny <string>()]).Returns <string>(name => new TraceSource(name));

            // Act
            var perfCountersMgr = new PerformanceCounterManager(traceManager.Object);

            perfCountersMgr.Initialize(instanceName, CancellationToken.None);

            // Assert
            Assert.Equal(expectedSanitizedName, perfCountersMgr.InstanceName);
        }
Example #12
0
        private IRendezvousService Build()
        {
            var logger              = resolver.Resolve <ILogger>();
            var applicationConfig   = resolver.Resolve <RendezvousServiceConfiguration>();
            var socketFactory       = new SocketFactory(applicationConfig.Socket);
            var synodConfigProvider = new SynodConfigurationProvider(applicationConfig.Synod);

#if NET47
            var instanceNameResolver = resolver.Resolve <IInstanceNameResolver>() ?? new InstanceNameResolver();

            var performanceCounterManager = new PerformanceCounterManager <KinoPerformanceCounters>(instanceNameResolver,
                                                                                                    logger);
#else
            var performanceCounterManager = default(IPerformanceCounterManager <KinoPerformanceCounters>);
#endif
            var intercomMessageHub = new IntercomMessageHub(socketFactory,
                                                            synodConfigProvider,
                                                            performanceCounterManager,
                                                            logger);
            var ballotGenerator    = new BallotGenerator(applicationConfig.Lease);
            var roundBasedRegister = new RoundBasedRegister(intercomMessageHub,
                                                            ballotGenerator,
                                                            synodConfigProvider,
                                                            applicationConfig.Lease,
                                                            logger);
            var leaseProvider = new LeaseProvider(roundBasedRegister,
                                                  ballotGenerator,
                                                  applicationConfig.Lease,
                                                  synodConfigProvider,
                                                  logger);

            var serializer     = new ProtobufMessageSerializer();
            var configProvider = new RendezvousConfigurationProvider(applicationConfig.Rendezvous);
            var service        = new RendezvousService(leaseProvider,
                                                       synodConfigProvider,
                                                       socketFactory,
                                                       serializer,
                                                       configProvider,
                                                       performanceCounterManager,
                                                       logger);

            return(service);
        }
        private void ReadAndInitializeIMPerfCounterSettings()
        {
            int    signInFailureQueueSize      = 100;
            int    sentMessageFailureQueueSize = 100;
            string text  = ConfigurationManager.AppSettings["SignInFailureQueueSize"];
            string text2 = ConfigurationManager.AppSettings["SentMessageFailureQueueSize"];
            int    num;

            if (!string.IsNullOrEmpty(text) && int.TryParse(text, out num) && num > 0)
            {
                signInFailureQueueSize = num;
            }
            int num2;

            if (!string.IsNullOrEmpty(text2) && int.TryParse(text2, out num2) && num2 > 0)
            {
                sentMessageFailureQueueSize = num2;
            }
            PerformanceCounterManager.InitializeIMQueueSizes(signInFailureQueueSize, sentMessageFailureQueueSize);
        }
Example #14
0
        public void SendThrowsNullExceptionWhenConnectionIdsAreNull()
        {
            var serializer = JsonUtility.CreateDefaultSerializer();
            var counters   = new PerformanceCounterManager();

            var connection = new Connection(new Mock <IMessageBus>().Object,
                                            serializer,
                                            "signal",
                                            "connectonid",
                                            new[] { "test" },
                                            new string[] { },
                                            new Mock <ITraceManager>().Object,
                                            new AckHandler(completeAcksOnTimeout: false,
                                                           ackThreshold: TimeSpan.Zero,
                                                           ackInterval: TimeSpan.Zero),
                                            counters,
                                            new Mock <IProtectedData>().Object);

            Assert.Throws <ArgumentNullException>(() => connection.Send((IList <string>)null, new object()));
        }
Example #15
0
        public void SendingCommandObjectSetsCommandOnBus()
        {
            var     messageBus = new Mock <IMessageBus>();
            var     counters   = new PerformanceCounterManager();
            Message message    = null;

            messageBus.Setup(m => m.Publish(It.IsAny <Message>())).Returns <Message>(m =>
            {
                message = m;
                return(TaskAsyncHelper.Empty);
            });

            var serializer   = JsonUtility.CreateDefaultSerializer();
            var traceManager = new Mock <ITraceManager>();
            var connection   = new Connection(messageBus.Object,
                                              serializer,
                                              "signal",
                                              "connectonid",
                                              new[] { "a", "signal", "connectionid" },
                                              new string[] { },
                                              traceManager.Object,
                                              new AckHandler(completeAcksOnTimeout: false,
                                                             ackThreshold: TimeSpan.Zero,
                                                             ackInterval: TimeSpan.Zero),
                                              counters,
                                              new Mock <IProtectedData>().Object,
                                              new MemoryPool());

            connection.Send("a", new Command
            {
                CommandType = CommandType.AddToGroup,
                Value       = "foo"
            });

            Assert.NotNull(message);
            Assert.True(message.IsCommand);
            var command = serializer.Parse <Command>(message.Value, message.Encoding);

            Assert.Equal(CommandType.AddToGroup, command.CommandType);
            Assert.Equal("foo", command.Value);
        }
Example #16
0
        public void ClientThrowsNullExceptionWhenConnectionIdIsNull()
        {
            Func <string, ClientHubInvocation, IList <string>, Task> send = (signal, value, exclude) => Task.Factory.StartNew(() => { });

            var serializer = new JsonNetSerializer();
            var counters   = new PerformanceCounterManager();
            var connection = new Connection(new Mock <IMessageBus>().Object,
                                            serializer,
                                            "signal",
                                            "connectonid",
                                            new[] { "test" },
                                            new string[] { },
                                            new Mock <ITraceManager>().Object,
                                            new AckHandler(completeAcksOnTimeout: false,
                                                           ackThreshold: TimeSpan.Zero,
                                                           ackInterval: TimeSpan.Zero),
                                            counters,
                                            new Mock <IProtectedData>().Object);

            var hubContext = new HubContext(send, "test", connection);

            Assert.Throws <ArgumentException>(() => hubContext.Clients.Client(null));
        }
        public void AcksAreSentToAckSubscriber()
        {
            // Arrange
            var waitCommand = new Command {
                WaitForAck = true
            };
            var ackerId     = "acker";
            var waiterId    = "waiter";
            var messageId   = "messageId";
            var maxMessages = 1;

            var ackHandler = new Mock <IAckHandler>();

            ackHandler.Setup(m => m.TriggerAck(waitCommand.Id)).Returns(false);

            var     messageBus  = new Mock <IMessageBus>();
            Message waitMessage = null;
            Message ackMessage  = null;

            messageBus.Setup(m => m.Publish(It.IsAny <Message>())).Returns <Message>(m =>
            {
                if (m.WaitForAck)
                {
                    waitMessage = m;
                }
                else if (m.IsAck)
                {
                    ackMessage = m;
                }

                return(TaskAsyncHelper.Empty);
            });

            var loggerFactory = new Mock <ILoggerFactory>();
            var counters      = new PerformanceCounterManager(loggerFactory.Object);

            var serializer       = JsonUtility.CreateDefaultSerializer();
            var waiterConnection = new Connection(messageBus.Object,
                                                  serializer,
                                                  "signal",
                                                  waiterId,
                                                  new string[] { },
                                                  new string[] { },
                                                  loggerFactory.Object,
                                                  ackHandler.Object,
                                                  counters,
                                                  new Mock <IProtectedData>().Object,
                                                  new MemoryPool());

            // Act
            waiterConnection.Send(ackerId, waitCommand);

            // Assert
            Assert.NotNull(waitMessage);
            Assert.Equal(waiterId, waitMessage.Source);
            Assert.Equal(PrefixHelper.GetConnectionId(ackerId), waitMessage.Key);

            // Arrange some more now that we have a waitMessage
            var messages = new List <ArraySegment <Message> >()
            {
                new ArraySegment <Message>(new[] { waitMessage })
            };
            var messageResult = new MessageResult(messages, 1);

            var ackerConnection = new Connection(messageBus.Object,
                                                 serializer,
                                                 "signal",
                                                 ackerId,
                                                 new string[] { },
                                                 new string[] { },
                                                 loggerFactory.Object,
                                                 ackHandler.Object,
                                                 counters,
                                                 new Mock <IProtectedData>().Object,
                                                 new Mock <IMemoryPool>().Object);

            ackerConnection.WriteCursor = _ => { };

            messageBus.Setup(m => m.Subscribe(ackerConnection,
                                              messageId,
                                              It.IsAny <Func <MessageResult, object, Task <bool> > >(),
                                              maxMessages,
                                              It.IsAny <object>()))
            .Callback <ISubscriber,
                       string,
                       Func <MessageResult, object, Task <bool> >,
                       int,
                       object>((subsciber, cursor, callback, max, state) =>
            {
                callback(messageResult, state);
            });

            // Act
            ackerConnection.Receive(messageId, (_, __) => TaskAsyncHelper.False, maxMessages, null);

            // Assert
            Assert.NotNull(ackMessage);
            Assert.Equal(ackerId, ackMessage.Source);
            Assert.Equal(AckSubscriber.Signal, ackMessage.Key);
        }
Example #18
0
        public void RequestCompletesAfterFaultedInitializeResponse()
        {
            // Arrange
            var testContext         = new TestContext("/test/echo/connect");
            var counters            = new PerformanceCounterManager(new Mock <ILoggerFactory>().Object);
            var heartBeat           = new Mock <ITransportHeartbeat>();
            var json                = new JsonSerializer();
            var transportConnection = new Mock <ITransportConnection>();
            var loggerFactory       = new Mock <ILoggerFactory>();
            var memoryPool          = new Mock <IMemoryPool>();
            var applicationLifetime = new Mock <IApplicationLifetime>();

            applicationLifetime.SetupGet(m => m.ApplicationStopping).Returns(CancellationToken.None);

            var logger = new Mock <ILogger>();

            loggerFactory.Setup(m => m.Create(It.IsAny <string>())).Returns(logger.Object);

            transportConnection.Setup(m => m.Receive(It.IsAny <string>(),
                                                     It.IsAny <Func <PersistentResponse, object, Task <bool> > >(),
                                                     It.IsAny <int>(),
                                                     It.IsAny <object>()))
            .Returns <string, Func <PersistentResponse, object, Task <bool> >, int, object>(
                (messageId, callback, maxMessages, state) =>
                new DisposableAction(() => callback(new PersistentResponse(), state))
                );

            var transport = new Mock <ForeverTransport>(testContext.MockHttpContext.Object, json, heartBeat.Object, counters, applicationLifetime.Object, loggerFactory.Object, memoryPool.Object)
            {
                CallBase = true
            };

            var queue = new TaskQueue();

            transport.Setup(t => t.EnqueueOperation(It.IsAny <Func <object, Task> >(), It.IsAny <object>()))
            .Returns <Func <object, Task>, object>(
                (writeAsync, state) => queue.Enqueue(writeAsync, state));

            transport.Setup(t => t.InitializeResponse(It.IsAny <ITransportConnection>()))
            .Returns <ITransportConnection>(
                pr => TaskAsyncHelper.FromError(new Exception()));

            transport.Setup(t => t.Send(It.IsAny <PersistentResponse>()))
            .Returns <PersistentResponse>(
                pr => transport.Object.EnqueueOperation(() => TaskAsyncHelper.Empty));

            var tcs = new TaskCompletionSource <bool>();

            transport.Object.AfterRequestEnd = (ex) =>
            {
                // Trip the cancellation token
                tcs.TrySetResult(transport.Object.WriteQueue.IsDrained);
            };

            // Act
            transport.Object.ProcessRequest(transportConnection.Object);

            // Assert
            Assert.True(tcs.Task.Wait(TimeSpan.FromSeconds(2)));
            Assert.True(tcs.Task.Result);
        }
Example #19
0
        // Token: 0x06000942 RID: 2370 RVA: 0x000424EC File Offset: 0x000406EC
        public Folder Execute(UserContext userContext, Folder folder, SearchScope searchScope, string searchString, bool newSearch, bool asyncSearch)
        {
            if (userContext == null)
            {
                throw new ArgumentNullException("userContext");
            }
            if (folder == null)
            {
                throw new ArgumentNullException("folder");
            }
            MailboxSession   mailboxSession   = (MailboxSession)folder.Session;
            QueryFilter      queryFilter      = SearchFilterGenerator.Execute(searchString, mailboxSession.Mailbox.IsContentIndexingEnabled, userContext.UserCulture, new PolicyTagMailboxProvider(userContext.MailboxSession), folder, searchScope, this.advancedQueryFilter);
            string           text             = (queryFilter == null) ? string.Empty : queryFilter.ToString();
            OwaStoreObjectId owaStoreObjectId = OwaStoreObjectId.CreateFromStoreObject(folder);
            SearchFolder     searchFolder     = null;
            bool             flag             = false;
            Folder           result;

            try
            {
                if (userContext.SearchFolderId != null)
                {
                    if (!newSearch && userContext.LastSearchFolderId.Equals(owaStoreObjectId) && userContext.LastSearchQueryFilter.CompareTo(text) == 0 && userContext.LastSearchScope == searchScope)
                    {
                        try
                        {
                            searchFolder = SearchFolder.Bind(userContext.SearchFolderId.GetSession(userContext), userContext.SearchFolderId.StoreObjectId, FolderSearch.PrefetchProperties);
                        }
                        catch (ObjectNotFoundException)
                        {
                        }
                        if (searchFolder != null)
                        {
                            if (asyncSearch)
                            {
                                SearchPerformanceData searchPerformanceData = userContext.MapiNotificationManager.GetSearchPerformanceData(mailboxSession);
                                if (searchPerformanceData != null)
                                {
                                    searchPerformanceData.RefreshStart();
                                }
                                OwaContext.Current.SearchPerformanceData = searchPerformanceData;
                            }
                            flag = true;
                            return(searchFolder);
                        }
                    }
                    if (userContext.IsPushNotificationsEnabled)
                    {
                        userContext.MapiNotificationManager.CancelSearchNotifications(mailboxSession);
                        userContext.MapiNotificationManager.AddSearchFolderDeleteList(mailboxSession, userContext.SearchFolderId.StoreObjectId);
                    }
                    else
                    {
                        mailboxSession.Delete(DeleteItemFlags.HardDelete, new StoreId[]
                        {
                            userContext.SearchFolderId.StoreObjectId
                        });
                    }
                    userContext.SearchFolderId = null;
                }
                using (Folder folder2 = Folder.Bind(mailboxSession, userContext.GetSearchFoldersId(mailboxSession).StoreObjectId))
                {
                    searchFolder = SearchFolder.Create(mailboxSession, folder2.Id.ObjectId, "OWA Search " + userContext.Key.UserContextId + " " + DateTime.UtcNow.ToString("o"), CreateMode.CreateNew);
                }
                searchFolder.Save();
                searchFolder.Load(FolderSearch.PrefetchProperties);
                userContext.SearchFolderId        = OwaStoreObjectId.CreateFromStoreObject(searchFolder);
                userContext.LastSearchFolderId    = owaStoreObjectId;
                userContext.LastSearchQueryFilter = text;
                userContext.LastSearchScope       = searchScope;
                if (queryFilter == null)
                {
                    flag   = true;
                    result = searchFolder;
                }
                else
                {
                    bool      flag2 = FolderSearch.FailNonContentIndexedSearch(folder, queryFilter);
                    bool      flag3;
                    StoreId[] folderScope;
                    if (searchScope == SearchScope.SelectedFolder || !mailboxSession.Mailbox.IsContentIndexingEnabled)
                    {
                        flag3       = false;
                        folderScope = new StoreId[]
                        {
                            folder.Id.ObjectId
                        };
                    }
                    else if (searchScope == SearchScope.SelectedAndSubfolders)
                    {
                        flag3       = true;
                        folderScope = new StoreId[]
                        {
                            folder.Id.ObjectId
                        };
                    }
                    else
                    {
                        if (searchScope != SearchScope.AllFoldersAndItems && searchScope != SearchScope.AllItemsInModule)
                        {
                            throw new ArgumentOutOfRangeException();
                        }
                        flag3       = true;
                        folderScope = new StoreId[]
                        {
                            userContext.GetRootFolderId(mailboxSession)
                        };
                    }
                    if (searchScope != SearchScope.SelectedFolder)
                    {
                        if (!folder.Id.ObjectId.Equals(userContext.JunkEmailFolderId))
                        {
                            QueryFilter queryFilter2 = new ComparisonFilter(ComparisonOperator.NotEqual, StoreObjectSchema.ParentItemId, userContext.JunkEmailFolderId);
                            queryFilter = new AndFilter(new QueryFilter[]
                            {
                                queryFilter,
                                queryFilter2
                            });
                        }
                        StoreObjectId storeObjectId = userContext.GetDeletedItemsFolderId((MailboxSession)folder.Session).StoreObjectId;
                        if (!folder.Id.ObjectId.Equals(storeObjectId))
                        {
                            QueryFilter queryFilter3 = new ComparisonFilter(ComparisonOperator.NotEqual, StoreObjectSchema.ParentItemId, storeObjectId);
                            queryFilter = new AndFilter(new QueryFilter[]
                            {
                                queryFilter,
                                queryFilter3
                            });
                        }
                    }
                    ExTraceGlobals.MailDataTracer.TraceDebug((long)this.GetHashCode(), "Search\nFilter: {0}\nDeep Traversal: {1}\nFolder: {2}\nContent Indexing Enabled: {3}", new object[]
                    {
                        queryFilter,
                        flag3,
                        folder.Id,
                        mailboxSession.Mailbox.IsContentIndexingEnabled ? "Yes" : "No"
                    });
                    SearchFolderCriteria searchFolderCriteria = new SearchFolderCriteria(queryFilter, folderScope);
                    searchFolderCriteria.DeepTraversal               = flag3;
                    searchFolderCriteria.MaximumResultsCount         = new int?(1000);
                    searchFolderCriteria.FailNonContentIndexedSearch = flag2;
                    SearchPerformanceData searchPerformanceData;
                    if (!userContext.IsPushNotificationsEnabled || !asyncSearch)
                    {
                        searchPerformanceData = new SearchPerformanceData();
                        searchPerformanceData.StartSearch(searchString);
                        IAsyncResult asyncResult = searchFolder.BeginApplyOneTimeSearch(searchFolderCriteria, null, null);
                        Stopwatch    stopwatch   = Utilities.StartWatch();
                        bool         flag4       = asyncResult.AsyncWaitHandle.WaitOne(30000, false);
                        searchPerformanceData.Complete(!flag4, true);
                        if (flag4)
                        {
                            searchFolder.EndApplyOneTimeSearch(asyncResult);
                        }
                        else
                        {
                            ExTraceGlobals.MailTracer.TraceDebug((long)this.GetHashCode(), "FolderSearch.Execute. Search timed out.");
                            if (Globals.ArePerfCountersEnabled)
                            {
                                OwaSingleCounters.SearchesTimedOut.Increment();
                            }
                        }
                        Utilities.StopWatch(stopwatch, "FolderSearch.Execute (Wait for search to complete)");
                        if (Globals.ArePerfCountersEnabled)
                        {
                            PerformanceCounterManager.UpdateSearchTimePerformanceCounter(stopwatch.ElapsedMilliseconds);
                            OwaSingleCounters.TotalSearches.Increment();
                        }
                        searchFolder.Save();
                        searchFolder.Load(FolderSearch.PrefetchProperties);
                    }
                    else
                    {
                        userContext.MapiNotificationManager.InitSearchNotifications(mailboxSession, userContext.SearchFolderId.StoreObjectId, searchFolder, searchFolderCriteria, searchString);
                        searchPerformanceData = userContext.MapiNotificationManager.GetSearchPerformanceData(mailboxSession);
                    }
                    if (!flag2)
                    {
                        searchPerformanceData.SlowSearchEnabled();
                    }
                    OwaContext.Current.SearchPerformanceData = searchPerformanceData;
                    flag   = true;
                    result = searchFolder;
                }
            }
            finally
            {
                if (!flag && searchFolder != null)
                {
                    searchFolder.Dispose();
                }
            }
            return(result);
        }
Example #20
0
        public void RequestCompletesAfterFaultedInitializeResponse()
        {
            // Arrange
            var response = new Mock <IResponse>();

            response.Setup(m => m.CancellationToken).Returns(CancellationToken.None);
            var request = new Mock <IRequest>();
            var qs      = new NameValueCollection();

            qs["connectionId"] = "1";
            request.Setup(m => m.QueryString).Returns(new NameValueCollectionWrapper(qs));
            request.Setup(m => m.LocalPath).Returns("/test/echo/connect");
            var counters            = new PerformanceCounterManager();
            var heartBeat           = new Mock <ITransportHeartbeat>();
            var json                = new JsonSerializer();
            var hostContext         = new HostContext(request.Object, response.Object);
            var transportConnection = new Mock <ITransportConnection>();
            var traceManager        = new Mock <ITraceManager>();

            traceManager.Setup(m => m[It.IsAny <string>()]).Returns(new System.Diagnostics.TraceSource("foo"));

            transportConnection.Setup(m => m.Receive(It.IsAny <string>(),
                                                     It.IsAny <Func <PersistentResponse, object, Task <bool> > >(),
                                                     It.IsAny <int>(),
                                                     It.IsAny <object>()))
            .Returns <string, Func <PersistentResponse, object, Task <bool> >, int, object>(
                (messageId, callback, maxMessages, state) =>
                new DisposableAction(() => callback(new PersistentResponse(), state))
                );

            var transport = new Mock <ForeverTransport>(hostContext, json, heartBeat.Object, counters, traceManager.Object)
            {
                CallBase = true
            };

            var queue = new TaskQueue();

            transport.Setup(t => t.EnqueueOperation(It.IsAny <Func <object, Task> >(), It.IsAny <object>()))
            .Returns <Func <object, Task>, object>(
                (writeAsync, state) => queue.Enqueue(writeAsync, state));

            transport.Setup(t => t.InitializeResponse(It.IsAny <ITransportConnection>()))
            .Returns <ITransportConnection>(
                pr => TaskAsyncHelper.FromError(new Exception()));

            transport.Setup(t => t.Send(It.IsAny <PersistentResponse>()))
            .Returns <PersistentResponse>(
                pr => transport.Object.EnqueueOperation(() => TaskAsyncHelper.Empty));

            var tcs = new TaskCompletionSource <bool>();

            transport.Object.AfterRequestEnd = (ex) =>
            {
                // Trip the cancellation token
                tcs.TrySetResult(transport.Object.WriteQueue.IsDrained);
            };

            // Act
            transport.Object.ProcessRequest(transportConnection.Object);

            // Assert
            Assert.True(tcs.Task.Wait(TimeSpan.FromSeconds(2)));
            Assert.True(tcs.Task.Result);
        }
Example #21
0
 internal void ExecuteApplicationStart(object sender, EventArgs e)
 {
     ExTraceGlobals.CoreCallTracer.TraceDebug(0L, "Global.Application_Start");
     try
     {
         if (OwaApplicationBase.IsRunningDfpowa)
         {
             string          localPath   = new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath;
             DirectoryInfo[] directories = Directory.GetParent(Directory.GetParent(localPath).FullName).GetDirectories("Config");
             if (directories.Length > 0)
             {
                 VariantConfiguration.Initialize(directories[0].FullName);
             }
         }
         Globals.Initialize(this.OwaVDirType);
         Kerberos.FlushTicketCache();
         SmallIconManager.Initialize();
         ThemeManager.Initialize();
         FormsRegistryManager.Initialize(HttpRuntime.AppDomainAppPath);
         ADCustomPropertyParser.Initialize(HttpRuntime.AppDomainAppPath);
         PerformanceCounterManager.InitializePerformanceCounters();
         ProxyEventHandler.Initialize();
         ExRpcModule.Bind();
         UIExtensionManager.Initialize();
         HelpProvider.Initialize(HelpProvider.HelpAppName.Owa);
         this.ExecuteApplicationSpecificStart();
     }
     catch (OwaSmallIconManagerInitializationException initializationError)
     {
         ExTraceGlobals.CoreTracer.TraceDebug(0L, "Application initialization failed");
         Globals.InitializationError = initializationError;
         return;
     }
     catch (OwaThemeManagerInitializationException initializationError2)
     {
         ExTraceGlobals.CoreTracer.TraceDebug(0L, "Application initialization failed");
         Globals.InitializationError = initializationError2;
         return;
     }
     catch (OwaFormsRegistryInitializationException initializationError3)
     {
         ExTraceGlobals.CoreTracer.TraceDebug(0L, "Application initialization failed");
         Globals.InitializationError = initializationError3;
         return;
     }
     catch (OwaInvalidConfigurationException ex)
     {
         ExTraceGlobals.CoreTracer.TraceDebug(0L, "Application initialization failed because of a problem with configuration: " + ex.Message);
         Globals.InitializationError = ex;
         return;
     }
     catch (OwaWin32Exception ex2)
     {
         ExTraceGlobals.CoreTracer.TraceDebug <int>(0L, "Application initialization failed with a win32 error: {0}", ex2.LastError);
         Globals.InitializationError = ex2;
         return;
     }
     catch (Exception initializationError4)
     {
         ExTraceGlobals.CoreTracer.TraceDebug(0L, "Application initialization failed");
         Globals.InitializationError = initializationError4;
         throw;
     }
     Globals.IsInitialized = true;
     ExTraceGlobals.CoreTracer.TraceDebug(0L, "Application initialization succeeded");
     if (Globals.IsPreCheckinApp)
     {
         OwaDiagnostics.Logger.LogEvent(ClientsEventLogConstants.Tuple_DfpOwaStartedSuccessfully, string.Empty, new object[0]);
         return;
     }
     OwaDiagnostics.Logger.LogEvent(ClientsEventLogConstants.Tuple_OwaStartedSuccessfully, string.Empty, new object[0]);
 }
Example #22
0
        internal static void RecordUserContextDeletion(OwaIdentity logonIdentity, UserContext userContext)
        {
            string userName = logonIdentity.UserSid.ToString();

            PerformanceCounterManager.UpdatePerfCounteronUserContextDeletion(userName, userContext.IsProxy, userContext.IsBasicExperience, Globals.ArePerfCountersEnabled);
        }
Example #23
0
        public void Build()
        {
            AssertDependencyResolverSet();

            var configurationProvider             = new ConfigurationProvider(resolver.Resolve <KinoConfiguration>());
            var scaleOutSocketConfiguration       = configurationProvider.GetScaleOutConfiguration();
            var clusterMembershipConfiguration    = configurationProvider.GetClusterMembershipConfiguration();
            var clusterHealthMonitorConfiguration = configurationProvider.GetClusterHealthMonitorConfiguration();
            var heartBeatSenderConfiguration      = configurationProvider.GetHeartBeatSenderConfiguration();
            var socketConfiguration = configurationProvider.GetSocketConfiguration();
            var rendezvousEndpoints = configurationProvider.GetRendezvousEndpointsConfiguration();
            var socketFactory       = new SocketFactory(socketConfiguration);
            var logger = resolver.Resolve <ILogger>();
            var roundRobinDestinationList  = new RoundRobinDestinationList(logger);
            var internalRoutingTable       = new InternalRoutingTable(roundRobinDestinationList);
            var externalRoutingTable       = new ExternalRoutingTable(roundRobinDestinationList, logger);
            var localSocketFactory         = new LocalSocketFactory();
            var routerLocalSocket          = new LocalSocket <IMessage>();
            var internalRegistrationSocket = new LocalSocket <InternalRouteRegistration>();

#if NET47
            var instanceNameResolver      = resolver.Resolve <IInstanceNameResolver>() ?? new InstanceNameResolver();
            var performanceCounterManager = new PerformanceCounterManager <KinoPerformanceCounters>(instanceNameResolver,
                                                                                                    logger);
#else
            var performanceCounterManager = default(IPerformanceCounterManager <KinoPerformanceCounters>);
#endif

            var hashCodeProvider = resolver.Resolve <Func <HMAC> >() ?? (() => HMAC.Create("HMACMD5"));

            var securityProvider = resolver.Resolve <ISecurityProvider>()
                                   ?? new SecurityProvider(hashCodeProvider,
                                                           resolver.Resolve <IDomainScopeResolver>(),
                                                           resolver.Resolve <IDomainPrivateKeyProvider>());
            var heartBeatSenderConfigurationManager = new HeartBeatSenderConfigurationManager(heartBeatSenderConfiguration);
            var configurationStorage = resolver.Resolve <IConfigurationStorage <RendezvousClusterConfiguration> >()
                                       ?? new RendezvousClusterConfigurationReadonlyStorage(rendezvousEndpoints);
            var rendezvousCluster = new RendezvousCluster(configurationStorage);

            var scaleoutConfigurationProvider = new ServiceLocator <ScaleOutConfigurationManager,
                                                                    NullScaleOutConfigurationManager,
                                                                    IScaleOutConfigurationManager>(clusterMembershipConfiguration,
                                                                                                   new ScaleOutConfigurationManager(scaleOutSocketConfiguration),
                                                                                                   new NullScaleOutConfigurationManager())
                                                .GetService();
            var connectedPeerRegistry = new ConnectedPeerRegistry(clusterHealthMonitorConfiguration);
            var clusterHealthMonitor  = new ServiceLocator <ClusterHealthMonitor,
                                                            NullClusterHealthMonitor,
                                                            IClusterHealthMonitor>(clusterMembershipConfiguration,
                                                                                   new ClusterHealthMonitor(socketFactory,
                                                                                                            localSocketFactory,
                                                                                                            securityProvider,
                                                                                                            routerLocalSocket,
                                                                                                            connectedPeerRegistry,
                                                                                                            clusterHealthMonitorConfiguration,
                                                                                                            logger),
                                                                                   new NullClusterHealthMonitor())
                                        .GetService();

            var heartBeatSender = new ServiceLocator <HeartBeatSender,
                                                      NullHeartBeatSender,
                                                      IHeartBeatSender>(clusterMembershipConfiguration,
                                                                        new HeartBeatSender(socketFactory,
                                                                                            heartBeatSenderConfigurationManager,
                                                                                            scaleoutConfigurationProvider,
                                                                                            logger),
                                                                        new NullHeartBeatSender())
                                  .GetService();
            var scaleOutListener = new ServiceLocator <ScaleOutListener,
                                                       NullScaleOutListener,
                                                       IScaleOutListener>(clusterMembershipConfiguration,
                                                                          new ScaleOutListener(socketFactory,
                                                                                               routerLocalSocket,
                                                                                               scaleoutConfigurationProvider,
                                                                                               securityProvider,
                                                                                               performanceCounterManager,
                                                                                               logger),
                                                                          new NullScaleOutListener())
                                   .GetService();
            var autoDiscoverSender = new AutoDiscoverySender(rendezvousCluster,
                                                             socketFactory,
                                                             clusterMembershipConfiguration,
                                                             performanceCounterManager,
                                                             logger);
            var autoDiscoveryListener = new AutoDiscoveryListener(rendezvousCluster,
                                                                  socketFactory,
                                                                  scaleoutConfigurationProvider,
                                                                  clusterMembershipConfiguration,
                                                                  performanceCounterManager,
                                                                  routerLocalSocket,
                                                                  logger);
            var routeDiscovery = new RouteDiscovery(autoDiscoverSender,
                                                    scaleoutConfigurationProvider,
                                                    clusterMembershipConfiguration,
                                                    securityProvider,
                                                    logger);
            var clusterMonitor = new ServiceLocator <ClusterMonitor,
                                                     NullClusterMonitor,
                                                     IClusterMonitor>(clusterMembershipConfiguration,
                                                                      new ClusterMonitor(scaleoutConfigurationProvider,
                                                                                         autoDiscoverSender,
                                                                                         autoDiscoveryListener,
                                                                                         heartBeatSenderConfigurationManager,
                                                                                         routeDiscovery,
                                                                                         securityProvider,
                                                                                         clusterMembershipConfiguration,
                                                                                         logger),
                                                                      new NullClusterMonitor())
                                 .GetService();
            var clusterServices = new ClusterServices(clusterMonitor,
                                                      scaleOutListener,
                                                      heartBeatSender,
                                                      clusterHealthMonitor);
            var nodeRoutesRegistrar = new NodeRoutesRegistrar(clusterServices,
                                                              internalRoutingTable,
                                                              securityProvider);
            var internalMessageRouteRegistrationHandler = new InternalMessageRouteRegistrationHandler(clusterMonitor,
                                                                                                      internalRoutingTable,
                                                                                                      securityProvider);
            var serviceMessageHandlers = new IServiceMessageHandler[]
            {
                new ClusterMessageRoutesRequestHandler(securityProvider,
                                                       nodeRoutesRegistrar),
                new PingHandler(),
                new ExternalMessageRouteRegistrationHandler(externalRoutingTable,
                                                            securityProvider,
                                                            clusterHealthMonitor,
                                                            logger),
                new MessageRouteDiscoveryHandler(clusterMonitor,
                                                 internalRoutingTable,
                                                 securityProvider,
                                                 logger),
                new MessageRouteUnregistrationHandler(clusterHealthMonitor,
                                                      externalRoutingTable,
                                                      securityProvider,
                                                      logger),
                new NodeMessageRoutesRequestHandler(securityProvider,
                                                    nodeRoutesRegistrar),
                new NodeUnregistrationHandler(clusterHealthMonitor,
                                              externalRoutingTable,
                                              securityProvider),
                new UnreachableNodeUnregistrationHandler(clusterHealthMonitor,
                                                         externalRoutingTable)
            };
            var serviceMessageHandlerRegistry = new ServiceMessageHandlerRegistry(serviceMessageHandlers);
            messageRouter = new MessageRouter(socketFactory,
                                              internalRoutingTable,
                                              externalRoutingTable,
                                              scaleoutConfigurationProvider,
                                              clusterServices,
                                              serviceMessageHandlerRegistry,
                                              performanceCounterManager,
                                              securityProvider,
                                              routerLocalSocket,
                                              internalRegistrationSocket,
                                              internalMessageRouteRegistrationHandler,
                                              roundRobinDestinationList,
                                              logger);
            var actorHostFactory = new ActorHostFactory(securityProvider,
                                                        routerLocalSocket,
                                                        internalRegistrationSocket,
                                                        localSocketFactory,
                                                        logger);
            var callbackHandlerStack = new CallbackHandlerStack();
            createMessageHub = (keepLocal) => new MessageHub(callbackHandlerStack,
                                                             routerLocalSocket,
                                                             internalRegistrationSocket,
                                                             localSocketFactory,
                                                             scaleoutConfigurationProvider,
                                                             securityProvider,
                                                             logger,
                                                             keepLocal);
            var messageHub = createMessageHub(false);
            getMessageHub    = () => messageHub;
            actorHostManager = new ActorHostManager(actorHostFactory, logger);

            internalActorHostManager = new ActorHostManager(actorHostFactory, logger);
            var internalActor = new MessageRoutesActor(externalRoutingTable, internalRoutingTable);
            internalActorHostManager.AssignActor(internalActor);
            //
            isBuilt = true;
        }
Example #24
0
        private void CounterList_Load(object sender, System.EventArgs e)
        {
            PerformanceCounterManager m;

            m = new PerformanceCounterManager();
        }
Example #25
0
        private static void CreateUserContext(HttpContext httpContext, UserContextKey userContextKey, AuthZClientInfo effectiveCaller, out IMailboxContext userContext, out UserContextStatistics userContextStats)
        {
            Stopwatch stopwatch = Stopwatch.StartNew();

            userContextStats = new UserContextStatistics();
            userContext      = null;
            OwaIdentity owaIdentity  = null;
            OwaIdentity owaIdentity2 = null;
            OwaIdentity owaIdentity3 = null;

            try
            {
                try
                {
                    OwaIdentity owaIdentity4 = OwaIdentity.ResolveLogonIdentity(httpContext, effectiveCaller);
                    owaIdentity2 = owaIdentity4;
                    string explicitLogonUser = UserContextUtilities.GetExplicitLogonUser(httpContext);
                    if (!string.IsNullOrEmpty(explicitLogonUser))
                    {
                        ExTraceGlobals.UserContextTracer.TraceDebug <string>(0L, "Created partial mailbox identity from SMTP address={0}", explicitLogonUser);
                        owaIdentity  = OwaIdentity.CreateOwaIdentityFromExplicitLogonAddress(explicitLogonUser);
                        owaIdentity3 = owaIdentity;
                    }
                    if (userContextKey == null)
                    {
                        userContextKey = UserContextKey.CreateNew(owaIdentity4, owaIdentity, httpContext);
                        ExTraceGlobals.UserContextTracer.TraceDebug <UserContextKey>(0L, "Creating new user context key: {0}", userContextKey);
                    }
                    else
                    {
                        ExTraceGlobals.UserContextTracer.TraceDebug <UserContextKey>(0L, "Reusing user context key: {0}", userContextKey);
                    }
                    OwaRWLockWrapper userContextKeyLock = UserContextManager.GetUserContextKeyLock(userContextKey.ToString());
                    if (userContextKeyLock == null)
                    {
                        userContextStats.Error = UserContextCreationError.UnableToAcquireOwaRWLock;
                        throw new OwaLockException("UserContextManger::CreateUserContext was not able to create a lock");
                    }
                    if (userContextKeyLock.LockWriterElastic(6000))
                    {
                        try
                        {
                            userContext = UserContextManager.GetMailboxContextFromCache(userContextKey, false);
                            if (userContext != null && userContext.TerminationStatus == UserContextTerminationStatus.TerminatePending)
                            {
                                UserContextManager.TerminateSession(userContext, userContext.AbandonedReason);
                                userContext = null;
                            }
                            if (userContext == null)
                            {
                                userContextStats.Created = true;
                                ExTraceGlobals.UserContextTracer.TraceDebug <UserContextKey>(0L, "User context was not found in the cache, creating one. UserContextKey: {0}", userContextKey);
                                bool flag = false;
                                try
                                {
                                    if (UserContextManager.IsSharedContextKey(userContextKey))
                                    {
                                        userContext = new SharedContext(userContextKey, httpContext.Request.UserAgent);
                                    }
                                    else
                                    {
                                        userContext = new UserContext(userContextKey, httpContext.Request.UserAgent);
                                    }
                                    Stopwatch stopwatch2 = Stopwatch.StartNew();
                                    userContext.Load(owaIdentity4, owaIdentity, userContextStats);
                                    userContextStats.LoadTime = (int)stopwatch2.ElapsedMilliseconds;
                                    UserContextManager.InsertIntoCache(httpContext, userContext);
                                    owaIdentity2 = null;
                                    owaIdentity3 = null;
                                    string userName = userContext.LogonIdentity.UserSid.ToString();
                                    PerformanceCounterManager.UpdatePerfCounteronUserContextCreation(userName, false, false, Globals.ArePerfCountersEnabled);
                                    flag = true;
                                }
                                finally
                                {
                                    if (!flag)
                                    {
                                        ExTraceGlobals.UserContextTracer.TraceDebug <UserContextKey>(0L, "User context creation failed. UserContextKey: {0}", userContextKey);
                                        if (userContext != null)
                                        {
                                            ExTraceGlobals.UserContextTracer.TraceDebug <UserContextKey>(0L, "Disposing user context. UserContextKey: {0}", userContextKey);
                                            userContext.Dispose();
                                            userContext.State = UserContextState.Abandoned;
                                        }
                                    }
                                }
                            }
                            goto IL_1EA;
                        }
                        finally
                        {
                            userContextKeyLock.ReleaseWriterLock();
                        }
                        goto IL_1D4;
IL_1EA:
                        goto IL_237;
                    }
IL_1D4:
                    userContextStats.Error = UserContextCreationError.UnableToAcquireOwaRWLock;
                    throw new OwaLockTimeoutException("UserContextManger::CreateUserContext was not able to acquire a rw lock", null, null);
                }
                catch (OwaIdentityException ex)
                {
                    userContextStats.Error = UserContextCreationError.UnableToResolveLogonIdentity;
                    OwaServerTraceLogger.AppendToLog(new TraceLogEvent("UserContext", userContext, "UserContextManager.CreateUserContext", ex.ToString()));
                    throw;
                }
                catch (Exception ex2)
                {
                    OwaServerTraceLogger.AppendToLog(new TraceLogEvent("UserContext", userContext, "UserContextManager.CreateUserContext", ex2.ToString()));
                    throw;
                }
                IL_237 :;
            }
            finally
            {
                if (owaIdentity2 != null)
                {
                    owaIdentity2.Dispose();
                }
                if (owaIdentity3 != null)
                {
                    owaIdentity3.Dispose();
                }
                stopwatch.Stop();
                userContextStats.AcquireLatency            = (int)stopwatch.ElapsedMilliseconds;
                httpContext.Items["UserContextStatistics"] = userContextStats;
            }
        }
Example #26
0
        public PerformanceMonitorForm(PerformanceCounterManager performanceCounterManager)
        {
            InitializeComponent();

            m_PerformanceCounterManager = performanceCounterManager;
        }
        // Token: 0x06002BE9 RID: 11241 RVA: 0x000F53B0 File Offset: 0x000F35B0
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            this.navigationBar = new NavigationBar(base.UserContext);
            InstantMessageManager instantMessageManager = base.UserContext.InstantMessageManager;

            if (!this.IsReInitializationRequest)
            {
                base.UserContext.PendingRequestManager.HandleFinishRequestFromClient(true);
            }
            if (instantMessageManager != null && !this.IsReInitializationRequest)
            {
                instantMessageManager.StartProvider();
            }
            if (base.UserContext.IsFeatureEnabled(Feature.Notifications))
            {
                if (base.UserContext.IsPushNotificationsEnabled)
                {
                    base.UserContext.MapiNotificationManager.SubscribeForFolderCounts(null, base.UserContext.MailboxSession);
                    if (base.UserContext.UserOptions.EnableReminders)
                    {
                        base.UserContext.MapiNotificationManager.SubscribeForReminders();
                    }
                    if (base.UserContext.UserOptions.NewItemNotify != NewNotification.None)
                    {
                        base.UserContext.MapiNotificationManager.SubscribeForNewMail();
                    }
                    base.UserContext.MapiNotificationManager.SubscribeForSubscriptionChanges();
                }
                if (base.UserContext.IsPullNotificationsEnabled)
                {
                    if (base.UserContext.NotificationManager.FolderCountAdvisor == null)
                    {
                        base.UserContext.NotificationManager.CreateOwaFolderCountAdvisor(base.UserContext.MailboxSession);
                    }
                    Dictionary <OwaStoreObjectId, OwaConditionAdvisor> conditionAdvisorTable = base.UserContext.NotificationManager.ConditionAdvisorTable;
                    if (base.UserContext.UserOptions.EnableReminders && (conditionAdvisorTable == null || !conditionAdvisorTable.ContainsKey(base.UserContext.RemindersSearchFolderOwaId)))
                    {
                        base.UserContext.NotificationManager.CreateOwaConditionAdvisor(base.UserContext, base.UserContext.MailboxSession, base.UserContext.RemindersSearchFolderOwaId, EventObjectType.None, EventType.None);
                    }
                    if (base.UserContext.UserOptions.NewItemNotify != NewNotification.None && base.UserContext.NotificationManager.LastEventAdvisor == null)
                    {
                        base.UserContext.NotificationManager.CreateOwaLastEventAdvisor(base.UserContext, base.UserContext.InboxFolderId, EventObjectType.Item, EventType.NewMail);
                    }
                }
            }
            StringBuilder stringBuilder = new StringBuilder();

            using (StringWriter stringWriter = new StringWriter(stringBuilder))
            {
                Utilities.RenderSizeWithUnits(stringWriter, base.UserContext.QuotaSend, false);
            }
            this.quotaWarningMessage  = string.Format(LocalizedStrings.GetHtmlEncoded(406437542), stringBuilder.ToString());
            this.quotaExceededMessage = string.Format(LocalizedStrings.GetHtmlEncoded(611216529), stringBuilder.ToString());
            if (this.IsReInitializationRequest)
            {
                PerformanceCounterManager.ProcessUserContextReInitializationRequest();
            }
            if (base.UserContext.IsClientSideDataCollectingEnabled)
            {
                this.UpdateClientCookie("owacsdc", "1");
                return;
            }
            Utilities.DeleteCookie(base.OwaContext.HttpContext.Response, "owacsdc");
        }