public override AsyncExecutionResult HandleAsyncResult(AsyncOperationResult asyncResult)
 {
     if (asyncResult.Errno == 0)
     {
         BytesTransferred = asyncResult.IntValue;
         SocketError      = SocketError.Success;
         return(AsyncExecutionResult.Finished);
     }
     else if (asyncResult.Errno == EINTR)
     {
         return(AsyncExecutionResult.Executing);
     }
     else if (asyncResult.Errno == ECANCELED)
     {
         return(AsyncExecutionResult.Cancelled);
     }
     else if (asyncResult.Errno == EAGAIN)
     {
         return(AsyncExecutionResult.WaitForPoll);
     }
     else
     {
         SocketError = SocketPal.GetSocketErrorForErrno(asyncResult.Errno);
         return(AsyncExecutionResult.Finished);
     }
 }
        void InitPivotLayoutSampleOlapDB(AsyncOperationResult result)
        {
            PivotGrid.RetrieveFields(FieldArea.FilterArea, false);
            if (PivotGrid.Fields.Count == 0)
            {
                InitializationCompletedCallback.Invoke(null);
                return;
            }
            PivotGrid.BeginUpdate();
            PivotGridField fieldProduct       = PivotGrid.Fields[CategoryFieldName],
                           fieldYear          = PivotGrid.Fields[YearFieldName],
                           fieldTotalCost     = PivotGrid.Fields[TotalCostFieldName],
                           fieldFreightCost   = PivotGrid.Fields[FreightFieldName],
                           fieldOrderQuantity = PivotGrid.Fields[QuantityOrderFieldName];

            PivotGrid.Groups[1].Caption = "Calendar";
            PivotGrid.Groups[2].Caption = "Products";

            fieldProduct.Area           = FieldArea.RowArea;
            fieldYear.Area              = FieldArea.ColumnArea;
            fieldYear.SortOrder         = FieldSortOrder.Descending;
            fieldTotalCost.Width        = DefaultFieldWidth;
            fieldTotalCost.CellFormat   = "c2";
            fieldFreightCost.Width      = DefaultFieldWidth;
            fieldFreightCost.CellFormat = "c2";
            fieldOrderQuantity.Width    = DefaultFieldWidth;

            fieldProduct.Visible       = true;
            fieldYear.Visible          = true;
            fieldTotalCost.Visible     = true;
            fieldFreightCost.Visible   = true;
            fieldOrderQuantity.Visible = true;

            PivotGrid.EndUpdateAsync(ExpandAll);
        }
Beispiel #3
0
        // Token: 0x0600004D RID: 77 RVA: 0x00003538 File Offset: 0x00001738
        public void LogOff()
        {
            base.CheckDisposed();
            this.ThrowIfNotConnected();
            AsyncOperationResult <DBNull> asyncOperationResult = ImapConnectionCore.LogOff(this.ConnectionContext, null, null);

            this.ThrowIfExceptionNotNull(asyncOperationResult.Exception);
        }
Beispiel #4
0
        // Token: 0x06000048 RID: 72 RVA: 0x00003424 File Offset: 0x00001624
        public void StoreMessageFlags(string uid, ImapMailFlags flagsToStore, ImapMailFlags previousFlags)
        {
            base.CheckDisposed();
            this.ThrowIfNotConnected();
            AsyncOperationResult <DBNull> asyncOperationResult = ImapConnectionCore.StoreMessageFlags(this.ConnectionContext, uid, flagsToStore, previousFlags, null, null);

            this.ThrowIfExceptionNotNull(asyncOperationResult.Exception);
        }
Beispiel #5
0
        public Pop3ResultData VerifyAccount()
        {
            base.CheckDisposed();
            AsyncOperationResult <Pop3ResultData> asyncOperationResult = Pop3ConnectionCore.VerifyAccount(this.ConnectionContext, null, null);

            this.ThrowIfExceptionNotNull(asyncOperationResult.Exception);
            return(asyncOperationResult.Data);
        }
Beispiel #6
0
        // Token: 0x0600004B RID: 75 RVA: 0x000034C4 File Offset: 0x000016C4
        public void RenameImapMailbox(string oldMailboxName, string newMailboxName)
        {
            base.CheckDisposed();
            this.ThrowIfNotConnected();
            AsyncOperationResult <DBNull> asyncOperationResult = ImapConnectionCore.RenameImapMailbox(this.ConnectionContext, oldMailboxName, newMailboxName, null, null);

            this.ThrowIfExceptionNotNull(asyncOperationResult.Exception);
        }
Beispiel #7
0
        public Pop3ResultData GetEmail(int messageId)
        {
            base.CheckDisposed();
            AsyncOperationResult <Pop3ResultData> email = Pop3ConnectionCore.GetEmail(this.ConnectionContext, messageId, null, null);

            this.ThrowIfExceptionNotNull(email.Exception);
            return(email.Data);
        }
Beispiel #8
0
        public Pop3ResultData DeleteEmails(List <int> messageIds)
        {
            base.CheckDisposed();
            AsyncOperationResult <Pop3ResultData> asyncOperationResult = Pop3ConnectionCore.DeleteEmails(this.ConnectionContext, messageIds, null, null);

            this.ThrowIfExceptionNotNull(asyncOperationResult.Exception);
            return(asyncOperationResult.Data);
        }
Beispiel #9
0
        public Pop3ResultData GetUniqueIds()
        {
            base.CheckDisposed();
            AsyncOperationResult <Pop3ResultData> uniqueIds = Pop3ConnectionCore.GetUniqueIds(this.ConnectionContext, null, null);

            this.ThrowIfExceptionNotNull(uniqueIds.Exception);
            return(uniqueIds.Data);
        }
Beispiel #10
0
        // Token: 0x06000047 RID: 71 RVA: 0x000033E8 File Offset: 0x000015E8
        public IList <string> SearchForMessageByMessageId(string messageId)
        {
            base.CheckDisposed();
            this.ThrowIfNotConnected();
            AsyncOperationResult <IList <string> > asyncOperationResult = ImapConnectionCore.SearchForMessageByMessageId(this.ConnectionContext, messageId, null, null);

            this.ThrowIfExceptionNotNull(asyncOperationResult.Exception);
            return(asyncOperationResult.Data);
        }
Beispiel #11
0
        // Token: 0x06000043 RID: 67 RVA: 0x000032F4 File Offset: 0x000014F4
        public ImapMailbox SelectImapMailbox(ImapMailbox imapMailbox)
        {
            base.CheckDisposed();
            this.ThrowIfNotConnected();
            AsyncOperationResult <ImapMailbox> asyncOperationResult = ImapConnectionCore.SelectImapMailbox(this.ConnectionContext, imapMailbox, null, null);

            this.ThrowIfExceptionNotNull(asyncOperationResult.Exception);
            return(asyncOperationResult.Data);
        }
Beispiel #12
0
        // Token: 0x0600004C RID: 76 RVA: 0x000034FC File Offset: 0x000016FC
        public IList <ImapMailbox> ListImapMailboxesByLevel(int level, char separator)
        {
            base.CheckDisposed();
            this.ThrowIfNotConnected();
            AsyncOperationResult <IList <ImapMailbox> > asyncOperationResult = ImapConnectionCore.ListImapMailboxesByLevel(this.ConnectionContext, level, separator, null, null);

            this.ThrowIfExceptionNotNull(asyncOperationResult.Exception);
            return(asyncOperationResult.Data);
        }
Beispiel #13
0
        // Token: 0x06000046 RID: 70 RVA: 0x000033AC File Offset: 0x000015AC
        public string AppendMessageToImapMailbox(string mailboxName, ImapMailFlags messageFlags, Stream messageMimeStream)
        {
            base.CheckDisposed();
            this.ThrowIfNotConnected();
            AsyncOperationResult <string> asyncOperationResult = ImapConnectionCore.AppendMessageToImapMailbox(this.ConnectionContext, mailboxName, messageFlags, messageMimeStream, null, null);

            this.ThrowIfExceptionNotNull(asyncOperationResult.Exception);
            return(asyncOperationResult.Data);
        }
Beispiel #14
0
        // Token: 0x06000044 RID: 68 RVA: 0x00003330 File Offset: 0x00001530
        public ImapResultData GetMessageInfoByRange(string start, string end, bool uidFetch, IList <string> messageDataItems)
        {
            base.CheckDisposed();
            this.ThrowIfNotConnected();
            AsyncOperationResult <ImapResultData> messageInfoByRange = ImapConnectionCore.GetMessageInfoByRange(this.ConnectionContext, start, end, uidFetch, messageDataItems, null, null);

            this.ThrowIfExceptionNotNull(messageInfoByRange.Exception);
            return(messageInfoByRange.Data);
        }
Beispiel #15
0
        // Token: 0x06000041 RID: 65 RVA: 0x00003284 File Offset: 0x00001484
        public ImapServerCapabilities GetServerCapabilities()
        {
            base.CheckDisposed();
            this.ThrowIfNotConnected();
            AsyncOperationResult <ImapServerCapabilities> asyncOperationResult = ImapConnectionCore.Capabilities(this.ConnectionContext, null, null);

            this.ThrowIfExceptionNotNull(asyncOperationResult.Exception);
            return(asyncOperationResult.Data);
        }
Beispiel #16
0
        // Token: 0x06000045 RID: 69 RVA: 0x00003370 File Offset: 0x00001570
        public ImapResultData GetMessageItemByUid(string uid, IList <string> messageBodyDataItems)
        {
            base.CheckDisposed();
            this.ThrowIfNotConnected();
            AsyncOperationResult <ImapResultData> messageItemByUid = ImapConnectionCore.GetMessageItemByUid(this.ConnectionContext, uid, messageBodyDataItems, null, null);

            this.ThrowIfExceptionNotNull(messageItemByUid.Exception);
            return(messageItemByUid.Data);
        }
        public override AsyncExecutionResult HandleAsyncResult(AsyncOperationResult asyncResult)
        {
            if (asyncResult.Errno == ECANCELED)
            {
                return(AsyncExecutionResult.Cancelled);
            }

            // poll says we're ready
            // TODO: read SOL_SOCKET, SO_ERROR to get errorcode...
            SocketError = SocketError.Success;
            return(AsyncExecutionResult.Finished);
        }
        public override AsyncExecutionResult HandleAsyncResult(AsyncOperationResult asyncResult)
        {
            if (asyncResult.Errno == ECANCELED)
            {
                return(AsyncExecutionResult.Cancelled);
            }

            // poll says we're ready
            bool finished = TryExecuteSync();

            return(finished ? AsyncExecutionResult.Finished : AsyncExecutionResult.WaitForPoll);
        }
Beispiel #19
0
        // Token: 0x0600003F RID: 63 RVA: 0x0000317C File Offset: 0x0000137C
        public void ConnectAndAuthenticate(ImapServerParameters serverParameters, ImapAuthenticationParameters authenticationParameters, IServerCapabilities capabilities = null)
        {
            base.CheckDisposed();
            this.ThrowIfConnected();
            ImapConnectionContext imapConnectionContext = this.ConnectionContext;

            imapConnectionContext.AuthenticationParameters = authenticationParameters;
            imapConnectionContext.ServerParameters         = serverParameters;
            imapConnectionContext.NetworkFacade            = this.CreateNetworkFacade.Value(this.ConnectionContext, serverParameters);
            AsyncOperationResult <DBNull> asyncOperationResult = ImapConnectionCore.ConnectAndAuthenticate(this.ConnectionContext, capabilities, null, null);

            this.ThrowIfExceptionNotNull(asyncOperationResult.Exception);
        }
        public override AsyncExecutionResult HandleAsyncResult(AsyncOperationResult asyncResult)
        {
            if (asyncResult.Errno == 0)
            {
                BytesTransferred += asyncResult.IntValue;

                IList <ArraySegment <byte> >?bufferList = BufferList;
                if (bufferList == null)
                {
                    if (BytesTransferred == MemoryBuffer.Length)
                    {
                        SocketError = SocketError.Success;
                        return(AsyncExecutionResult.Finished);
                    }
                }
                else
                {
                    _bufferOffset += asyncResult.IntValue;
                    if (_bufferOffset == bufferList[_bufferIndex].Count)
                    {
                        _bufferOffset = 0;
                        _bufferIndex++;
                        if (_bufferIndex == bufferList.Count)
                        {
                            SocketError = SocketError.Success;
                            return(AsyncExecutionResult.Finished);
                        }
                    }
                }

                return(AsyncExecutionResult.Executing);
            }
            else if (asyncResult.Errno == EINTR)
            {
                return(AsyncExecutionResult.Executing);
            }
            else if (asyncResult.Errno == ECANCELED)
            {
                return(AsyncExecutionResult.Cancelled);
            }
            else if (asyncResult.Errno == EAGAIN)
            {
                return(AsyncExecutionResult.WaitForPoll);
            }
            else
            {
                SocketError = SocketPal.GetSocketErrorForErrno(asyncResult.Errno);
                return(AsyncExecutionResult.Finished);
            }
        }
Beispiel #21
0
 void ProcessAsyncResult(AsyncOperationResult result)
 {
     if (result == null)
     {
         if (currentDataSource == InitializerDataSource.OlapCube || isDataBaseGeneratorRunned)
         {
             ShowErrorInfo();
         }
         else
         {
             RunDBGenerator("Start Demo");
         }
     }
     EnableControls();
 }
        void InitPivotLayoutSampleOlapDB(AsyncOperationResult result)
        {
            if (pivotGrid.Fields.Count == 0 || !IsSampleCube())
            {
                return;
            }
            pivotGrid.BeginUpdate();
            PivotGridField fieldProduct       = pivotGrid.Fields[CategoryFieldName],
                           fieldYear          = pivotGrid.Fields[YearFieldName],
                           fieldTotalCost     = pivotGrid.Fields[TotalCostFieldName],
                           fieldFreightCost   = pivotGrid.Fields[FreightFieldName],
                           fieldOrderQuantity = pivotGrid.Fields[QuantityOrderFieldName];

            if (fieldProduct == null ||
                fieldYear == null ||
                fieldTotalCost == null ||
                fieldFreightCost == null ||
                fieldOrderQuantity == null)
            {
                pivotGrid.EndUpdateAsync();
                return;
            }
            fieldProduct.Area           = FieldArea.RowArea;
            fieldYear.Area              = FieldArea.ColumnArea;
            fieldYear.SortOrder         = FieldSortOrder.Descending;
            fieldTotalCost.Width        = DefaultFieldWidth + 20;
            fieldTotalCost.CellFormat   = "c2";
            fieldFreightCost.Width      = DefaultFieldWidth;
            fieldFreightCost.CellFormat = "c2";
            fieldOrderQuantity.Width    = DefaultFieldWidth + 5;
            fieldProduct.Visible        = true;
            fieldYear.Visible           = true;
            fieldTotalCost.Visible      = true;
            fieldFreightCost.Visible    = true;
            fieldOrderQuantity.Visible  = true;
            pivotGrid.EndUpdateAsync();
        }
        void InitPivotLayoutGeneratedDB(AsyncOperationResult result)
        {
            PivotGrid.BeginUpdate();
            PivotGridField fieldSalesPerson = CreatePivotGridField("SalesPersonName", "Sales Person", FieldArea.RowArea);
            PivotGridField fieldCustomer    = CreatePivotGridField("CustomerName", "Customer", FieldArea.FilterArea);
            PivotGridField fieldQuantity    = CreatePivotGridField("Quantity", "Quantity", FieldArea.DataArea);
            PivotGridField fieldUnitPrice   = CreatePivotGridField("UnitPrice", "Unit Price", FieldArea.DataArea);

            fieldUnitPrice.SummaryType         = FieldSummaryType.Average;
            fieldUnitPrice.ShowSummaryTypeName = true;
            PivotGridField fieldOrderID       = CreatePivotGridField("OrderID", "Order ID", FieldArea.FilterArea);
            PivotGridField fieldCategory      = CreatePivotGridField("CategoryName", "Category", FieldArea.RowArea);
            PivotGridField fieldProduct       = CreatePivotGridField("ProductName", "Product", FieldArea.RowArea);
            PivotGridField fieldOrderDateYear = CreatePivotGridField("OrderDate", "Year", FieldArea.ColumnArea);

            fieldOrderDateYear.GroupInterval = FieldGroupInterval.DateYear;
            PivotGridField fieldOrderDateMonth = CreatePivotGridField("OrderDate", "Month", FieldArea.ColumnArea);

            fieldOrderDateMonth.GroupInterval = FieldGroupInterval.DateMonth;
            PivotGridField fieldPrice = new PivotGridField();

            fieldPrice.Area        = FieldArea.DataArea;
            fieldPrice.Caption     = "Price";
            fieldPrice.UnboundType = FieldUnboundColumnType.Decimal;

            fieldQuantity.Width  = DefaultFieldWidth;
            fieldUnitPrice.Width = DefaultFieldWidth;
            fieldPrice.Width     = DefaultFieldWidth;

            PivotGrid.Fields.AddRange(new PivotGridField[] { fieldSalesPerson, fieldCustomer, fieldQuantity, fieldUnitPrice,
                                                             fieldOrderID, fieldCategory, fieldProduct, fieldOrderDateYear, fieldOrderDateMonth, fieldPrice });
            PivotGrid.Groups.Add(fieldOrderDateYear, fieldOrderDateMonth);

            fieldPrice.UnboundExpression = "[" + fieldQuantity.ExpressionFieldName + "] * [" + fieldUnitPrice.ExpressionFieldName + "]";
            PivotGrid.EndUpdateAsync(InitializationCompletedCallback);
        }
        public async Task <T> ExecuteWithReplicationAsync <T>(string method, string primaryUrl, OperationCredentials primaryCredentials, int currentRequest, int currentReadStripingBase, Func <OperationMetadata, Task <T> > operation)
        {
            var localReplicationDestinations = ReplicationDestinationsUrls; // thread safe copy
            var primaryOperation             = new OperationMetadata(primaryUrl, primaryCredentials);

            var shouldReadFromAllServers = conventions.FailoverBehavior.HasFlag(FailoverBehavior.ReadFromAllServers);
            var operationResult          = new AsyncOperationResult <T>();

            if (shouldReadFromAllServers && method == "GET")
            {
                var replicationIndex = currentReadStripingBase % (localReplicationDestinations.Count + 1);
                // if replicationIndex == destinations count, then we want to use the master
                // if replicationIndex < 0, then we were explicitly instructed to use the master
                if (replicationIndex < localReplicationDestinations.Count && replicationIndex >= 0)
                {
                    // if it is failing, ignore that, and move to the master or any of the replicas
                    if (ShouldExecuteUsing(localReplicationDestinations[replicationIndex], primaryOperation, currentRequest, method, false))
                    {
                        operationResult = await TryOperationAsync(operation, localReplicationDestinations[replicationIndex], primaryOperation, true).ConfigureAwait(false);

                        if (operationResult.Success)
                        {
                            return(operationResult.Result);
                        }
                    }
                }
            }

            if (ShouldExecuteUsing(primaryOperation, primaryOperation, currentRequest, method, true))
            {
                operationResult = await TryOperationAsync(operation, primaryOperation, null, !operationResult.WasTimeout && localReplicationDestinations.Count > 0).ConfigureAwait(false);

                if (operationResult.Success)
                {
                    return(operationResult.Result);
                }

                IncrementFailureCount(primaryOperation.Url);
                if (!operationResult.WasTimeout && IsFirstFailure(primaryOperation.Url))
                {
                    operationResult = await TryOperationAsync(operation, primaryOperation, null, localReplicationDestinations.Count > 0).ConfigureAwait(false);

                    if (operationResult.Success)
                    {
                        return(operationResult.Result);
                    }
                    IncrementFailureCount(primaryOperation.Url);
                }
            }

            for (var i = 0; i < localReplicationDestinations.Count; i++)
            {
                var replicationDestination = localReplicationDestinations[i];
                if (ShouldExecuteUsing(replicationDestination, primaryOperation, currentRequest, method, false) == false)
                {
                    continue;
                }

                var hasMoreReplicationDestinations = localReplicationDestinations.Count > i + 1;
                operationResult = await TryOperationAsync(operation, replicationDestination, primaryOperation, !operationResult.WasTimeout && hasMoreReplicationDestinations).ConfigureAwait(false);

                if (operationResult.Success)
                {
                    return(operationResult.Result);
                }

                IncrementFailureCount(replicationDestination.Url);
                if (!operationResult.WasTimeout && IsFirstFailure(replicationDestination.Url))
                {
                    operationResult = await TryOperationAsync(operation, replicationDestination, primaryOperation, hasMoreReplicationDestinations).ConfigureAwait(false);

                    // tuple = await TryOperationAsync(operation, replicationDestination, primaryOperation, localReplicationDestinations.Count > i + 1).ConfigureAwait(false);
                    if (operationResult.Success)
                    {
                        return(operationResult.Result);
                    }
                    IncrementFailureCount(replicationDestination.Url);
                }
            }

            // this should not be thrown, but since I know the value of should...
            throw new InvalidOperationException(@"Attempted to connect to master and all replicas have failed, giving up.
There is a high probability of a network problem preventing access to all the replicas.
Failed to get in touch with any of the " + (1 + localReplicationDestinations.Count) + " Raven instances.");
        }
        public override AsyncExecutionResult TryExecute(bool triggeredByPoll, bool isCancellationRequested, bool asyncOnly, AsyncExecutionQueue?executionQueue, AsyncExecutionCallback?callback, object?state, int data, AsyncOperationResult asyncResult)
        {
            Socket socket = Socket !;

            // When there is a pollable executionQueue, use it to poll, and then try the operation.
            bool hasPollableExecutionQueue = executionQueue?.SupportsPolling == true;
            bool trySync = !hasPollableExecutionQueue && !asyncOnly;

            if (trySync || asyncResult.HasResult)
            {
                (SocketError socketError, Socket? acceptedSocket) = SocketPal.Accept(socket.SafeHandle);
                if (socketError != SocketError.WouldBlock)
                {
                    SocketError    = socketError;
                    AcceptedSocket = acceptedSocket;
                    return(AsyncExecutionResult.Finished);
                }
            }

            if (isCancellationRequested)
            {
                SocketError = SocketError.OperationAborted;
                return(AsyncExecutionResult.Cancelled);
            }

            // poll
            if (hasPollableExecutionQueue)
            {
                executionQueue !.AddPollIn(socket.SafeHandle, callback !, state, data);;
                return(AsyncExecutionResult.Executing);
            }
            else
            {
                return(AsyncExecutionResult.WaitForPoll);
            }
        }
Beispiel #26
0
        public override AsyncExecutionResult TryExecute(bool triggeredByPoll, bool isCancellationRequested, bool asyncOnly, AsyncExecutionQueue?executionQueue, AsyncExecutionCallback?callback, object?state, int data, AsyncOperationResult asyncResult)
        {
            IList <ArraySegment <byte> >?bufferList = BufferList;

            if (bufferList == null)
            {
                return(SendSingleBuffer(MemoryBuffer, isCancellationRequested, asyncOnly, executionQueue, callback, state, data, asyncResult));
            }
            else
            {
                return(SendMultipleBuffers(bufferList, isCancellationRequested, asyncOnly, executionQueue, callback, state, data, asyncResult));
            }
        }
Beispiel #27
0
 private unsafe AsyncExecutionResult SendMultipleBuffers(IList <ArraySegment <byte> > buffers, bool isCancellationRequested, bool asyncOnly, AsyncExecutionQueue?executionQueue, AsyncExecutionCallback?callback, object?state, int data, AsyncOperationResult asyncResult)
 {
     // TODO: really support multi-buffer sends...
     for (; _bufferIndex < buffers.Count; _bufferIndex++)
     {
         AsyncExecutionResult bufferSendResult = SendSingleBuffer(buffers[_bufferIndex], isCancellationRequested, asyncOnly, executionQueue, callback, state, data, asyncResult);
         if (bufferSendResult == AsyncExecutionResult.WaitForPoll || bufferSendResult == AsyncExecutionResult.Executing)
         {
             return(bufferSendResult);
         }
         if (SocketError != SocketError.Success)
         {
             break;
         }
         BytesTransferred = 0; // TODO... not really correct
     }
     return(AsyncExecutionResult.Finished);
 }
Beispiel #28
0
        private AsyncExecutionResult SendSingleBuffer(Memory <byte> memory, bool isCancellationRequested, bool asyncOnly, AsyncExecutionQueue?executionQueue, AsyncExecutionCallback?callback, object?state, int data, AsyncOperationResult asyncResult)
        {
            SocketError          socketError = SocketError.SocketError;
            AsyncExecutionResult result      = AsyncExecutionResult.Executing;

            if (asyncResult.HasResult)
            {
                if (asyncResult.IsError)
                {
                    if (asyncResult.Errno == EINTR)
                    {
                        result = AsyncExecutionResult.Executing;
                    }
                    else if (asyncResult.Errno == EAGAIN)
                    {
                        result = AsyncExecutionResult.WaitForPoll;
                    }
                    else
                    {
                        socketError = SocketPal.GetSocketErrorForErrno(asyncResult.Errno);
                        result      = AsyncExecutionResult.Finished;
                    }
                }
                else
                {
                    BytesTransferred += asyncResult.IntValue;
                    if (BytesTransferred == memory.Length)
                    {
                        socketError = SocketError.Success;
                        result      = AsyncExecutionResult.Finished;
                    }
                }
            }

            if (isCancellationRequested && result != AsyncExecutionResult.Finished)
            {
                SocketError = SocketError.OperationAborted;
                return(AsyncExecutionResult.Cancelled);
            }

            // When there is a pollable executionQueue, use it to poll, and then try the operation.
            if (result == AsyncExecutionResult.Executing ||
                (result == AsyncExecutionResult.WaitForPoll && executionQueue?.SupportsPolling == true))
            {
                Socket socket = Socket !;
                if (socket == null)
                {
                    ThrowHelper.ThrowInvalidOperationException();
                }

                if (executionQueue != null)
                {
                    Memory <byte> remaining = memory.Slice(BytesTransferred);
                    executionQueue.AddWrite(socket.SafeHandle, remaining, callback !, state, data);
                    result = AsyncExecutionResult.Executing;
                }
                else if (result == AsyncExecutionResult.Executing)
                {
                    if (asyncOnly)
                    {
                        result = AsyncExecutionResult.WaitForPoll;
                    }
                    else
                    {
                        while (true)
                        {
                            Memory <byte> remaining = memory.Slice(BytesTransferred);
                            int           bytesTransferred;
                            (socketError, bytesTransferred) = SocketPal.Send(socket.SafeHandle, remaining);
                            if (socketError == SocketError.Success)
                            {
                                BytesTransferred += bytesTransferred;
                                if (BytesTransferred == memory.Length || bytesTransferred == 0)
                                {
                                    break;
                                }
                            }
                            else
                            {
                                break;
                            }
                        }
                        result = socketError == SocketError.WouldBlock ? AsyncExecutionResult.WaitForPoll : AsyncExecutionResult.Finished;
                    }
                }
            }

            if (result == AsyncExecutionResult.Finished)
            {
                SocketError = socketError;
            }

            return(result);
        }
Beispiel #29
0
        public async Task <T> ExecuteWithReplicationAsync <T>(HttpMethod method,
                                                              string primaryUrl,
                                                              OperationCredentials primaryCredentials,
                                                              RequestTimeMetric primaryRequestTimeMetric,
                                                              int currentRequest,
                                                              int currentReadStripingBase,
                                                              Func <OperationMetadata, Task <T> > operation,
                                                              CancellationToken token = default(CancellationToken))
        {
            Debug.Assert(typeof(T).FullName.Contains("Task") == false);

            var localReplicationDestinations = ReplicationDestinationsUrls; // thread safe copy
            var primaryOperation             = new OperationMetadata(primaryUrl, primaryCredentials, null);

            var operationResult          = new AsyncOperationResult <T>();
            var shouldReadFromAllServers = Conventions.FailoverBehavior.HasFlag(FailoverBehavior.ReadFromAllServers);

            var allowReadFromSecondariesWhenRequestTimeThresholdIsPassed = Conventions.FailoverBehavior.HasFlag(FailoverBehavior.AllowReadFromSecondariesWhenRequestTimeThresholdIsSurpassed);

            if (method == HttpMethods.Get && (shouldReadFromAllServers || allowReadFromSecondariesWhenRequestTimeThresholdIsPassed))
            {
                var replicationIndex = -1;
                if (allowReadFromSecondariesWhenRequestTimeThresholdIsPassed && primaryRequestTimeMetric != null && primaryRequestTimeMetric.RateSurpassed(Conventions))
                {
                    replicationIndex = currentReadStripingBase % (localReplicationDestinations.Count);
                }
                else if (shouldReadFromAllServers)
                {
                    replicationIndex = currentReadStripingBase % (localReplicationDestinations.Count + 1);
                }

                // if replicationIndex == destinations count, then we want to use the master
                // if replicationIndex < 0, then we were explicitly instructed to use the master
                if (replicationIndex < localReplicationDestinations.Count && replicationIndex >= 0)
                {
                    // if it is failing, ignore that, and move to the master or any of the replicas
                    if (ShouldExecuteUsing(localReplicationDestinations[replicationIndex], primaryOperation, method, false, null, token))
                    {
                        operationResult = await TryOperationAsync(operation, localReplicationDestinations[replicationIndex], primaryOperation, true, token).ConfigureAwait(false);

                        if (operationResult.Success)
                        {
                            return(operationResult.Result);
                        }
                    }
                }
            }

            if (ShouldExecuteUsing(primaryOperation, primaryOperation, method, true, null, token))
            {
                operationResult = await TryOperationAsync(operation, primaryOperation, null, !operationResult.WasTimeout && localReplicationDestinations.Count > 0, token)
                                  .ConfigureAwait(false);

                if (operationResult.Success)
                {
                    return(operationResult.Result);
                }

                FailureCounters.IncrementFailureCount(primaryOperation.Url);
                if (!operationResult.WasTimeout && FailureCounters.IsFirstFailure(primaryOperation.Url))
                {
                    operationResult = await TryOperationAsync(operation, primaryOperation, null, localReplicationDestinations.Count > 0, token).ConfigureAwait(false);

                    if (operationResult.Success)
                    {
                        return(operationResult.Result);
                    }
                    FailureCounters.IncrementFailureCount(primaryOperation.Url);
                }
            }

            for (var i = 0; i < localReplicationDestinations.Count; i++)
            {
                token.ThrowCancellationIfNotDefault();

                var replicationDestination = localReplicationDestinations[i];
                if (ShouldExecuteUsing(replicationDestination, primaryOperation, method, false, operationResult.Error, token) == false)
                {
                    continue;
                }

                var hasMoreReplicationDestinations = localReplicationDestinations.Count > i + 1;
                operationResult = await TryOperationAsync(operation, replicationDestination, primaryOperation, !operationResult.WasTimeout && hasMoreReplicationDestinations, token).ConfigureAwait(false);

                if (operationResult.Success)
                {
                    return(operationResult.Result);
                }

                FailureCounters.IncrementFailureCount(replicationDestination.Url);
                if (!operationResult.WasTimeout && FailureCounters.IsFirstFailure(replicationDestination.Url))
                {
                    operationResult = await TryOperationAsync(operation, replicationDestination, primaryOperation, hasMoreReplicationDestinations, token).ConfigureAwait(false);

                    if (operationResult.Success)
                    {
                        return(operationResult.Result);
                    }

                    FailureCounters.IncrementFailureCount(replicationDestination.Url);
                }
            }

            // this should not be thrown, but since I know the value of should...
            throw new InvalidOperationException(@"Attempted to connect to master and all replicas have failed, giving up.
There is a high probability of a network problem preventing access to all the replicas.
Failed to get in touch with any of the " + (1 + localReplicationDestinations.Count) + " Raven instances.");
        }
 void ExpandAll(AsyncOperationResult result)
 {
     PivotGrid.ExpandAllAsync(InitializationCompletedCallback);
 }