public AnalyzerResult(
                SemanticDocument document,
                IEnumerable<ITypeParameterSymbol> typeParametersInDeclaration,
                IEnumerable<ITypeParameterSymbol> typeParametersInConstraintList,
                IList<VariableInfo> variables,
                VariableInfo variableToUseAsReturnValue,
                ITypeSymbol returnType,
                bool awaitTaskReturn,
                bool instanceMemberIsUsed,
                bool endOfSelectionReachable,
                OperationStatus status)
            {
                var semanticModel = document.SemanticModel;

                this.UseInstanceMember = instanceMemberIsUsed;
                this.EndOfSelectionReachable = endOfSelectionReachable;
                this.AwaitTaskReturn = awaitTaskReturn;
                this.SemanticDocument = document;
                _typeParametersInDeclaration = typeParametersInDeclaration.Select(s => semanticModel.ResolveType(s)).ToList();
                _typeParametersInConstraintList = typeParametersInConstraintList.Select(s => semanticModel.ResolveType(s)).ToList();
                _variables = variables;
                this.ReturnType = semanticModel.ResolveType(returnType);
                _variableToUseAsReturnValue = variableToUseAsReturnValue;
                this.Status = status;
            }
 public SimpleExtractMethodResult(
     OperationStatus status,
     Document document,
     SyntaxToken invocationNameToken,
     SyntaxNode methodDefinition)
     : base(status.Flag, status.Reasons, document, invocationNameToken, methodDefinition)
 {
 }
Exemplo n.º 3
0
        internal GettingEventArgs(Workspace workspace, GetOperation operation)
        {
            this.workspace = workspace;
                this.operation = operation;

                if (operation.ChangeType == ChangeType.Delete)
                    status = OperationStatus.Deleting;
                else status = OperationStatus.Getting;
        }
 internal ComputeTypeCreateOrUpdateResponse(
     CoreRegistrationModel.ComputeTypeCreateOrUpdateResponse internalResponse,
     DataFactoryManagementClient client)
     : this()
 {
     DataFactoryOperationUtilities.CopyRuntimeProperties(internalResponse, this);
     this.ComputeType = ((ComputeTypeOperations)client.ComputeTypes).Converter.ToWrapperType(internalResponse.ComputeType);
     this.Status = internalResponse.Status;
 }
Exemplo n.º 5
0
 public OperationReport(string name, string description, OperationStatus status, string exceptionDetail, int cycles, double duration)
 {
     Name = name;
     Description = description;
     Status = status;
     ExceptionDetail = exceptionDetail;
     Cycles = cycles;
     TotalDuration = duration;
 }
Exemplo n.º 6
0
        public virtual void Cancel()
        {
            if (this.Status == OperationStatus.Cancelled || this.Status == OperationStatus.Completed)
            {
                // no-op
                return;
            }

            this.Status = OperationStatus.Cancelled;
        }
Exemplo n.º 7
0
        private ExtractMethodResult CreateExtractMethodResult(
            OperationStatus status, SemanticDocument semanticDocument,
            SyntaxAnnotation invocationAnnotation, SyntaxAnnotation methodAnnotation)
        {
            var newRoot = semanticDocument.Root;
            var annotatedTokens = newRoot.GetAnnotatedNodesAndTokens(invocationAnnotation);
            var methodDefinition = newRoot.GetAnnotatedNodesAndTokens(methodAnnotation).FirstOrDefault().AsNode();

            return new SimpleExtractMethodResult(status, semanticDocument.Document, GetMethodNameAtInvocation(annotatedTokens), methodDefinition);
        }
Exemplo n.º 8
0
        //新增
        internal void cmdBtnAdd_Click(object sender, EventArgs e)
        {
            ClearMessage();

            if (!Add())
                return;

            CurrentOperationStatus = OperationStatus.New;
            ResetButtonStatus();
        }
 public StatementResult(
     OperationStatus status,
     TextSpan originalSpan,
     TextSpan finalSpan,
     OptionSet options,
     bool selectionInExpression,
     SemanticDocument document,
     SyntaxAnnotation firstTokenAnnotation,
     SyntaxAnnotation lastTokenAnnotation) :
     base(status, originalSpan, finalSpan, options, selectionInExpression, document, firstTokenAnnotation, lastTokenAnnotation)
 {
 }
Exemplo n.º 10
0
 public static string GetMessage(OperationStatus status)
 {
     if (_operationStatus.ContainsKey(status))
     {
         var statusKey = _operationStatus[status];
         if (_defaultLocaleResources.ContainsKey(statusKey))
         {
             return _defaultLocaleResources[_operationStatus[status]];
         }
         return statusKey;
     }
     return status.ToString();
 }
        internal PipelineCreateOrUpdateResponse(
            Core.Models.PipelineCreateOrUpdateResponse internalResponse,
            DataFactoryManagementClient client)
            : this() 
        {
            Ensure.IsNotNull(internalResponse, "internalResponse");
            Ensure.IsNotNull(internalResponse.Pipeline, "internalResponse.Pipeline");

            DataFactoryUtilities.CopyRuntimeProperties(internalResponse, this);
            this.Pipeline = ((PipelineOperations)client.Pipelines).Converter.ToWrapperType(internalResponse.Pipeline);
            this.Location = internalResponse.Location;
            this.Status = internalResponse.Status;
        }
Exemplo n.º 12
0
        public void Execute()
        {
            Debug.Assert(this.Status != OperationStatus.Started, "Cannot re-execute a started operation.");
            Debug.Assert(this.Status != OperationStatus.Completed, "Cannot re-execute a completed operation.");

            if (this.IsCancelled)
            {
                // This operation already has been cancelled and its OnCancel method should of already been called.
                return;
            }

            this.Status = OperationStatus.Started;

            this.InternalExecute();
        }
            public GeneratedCode(
                OperationStatus status,
                SemanticDocument document,
                SyntaxAnnotation methodNameAnnotation,
                SyntaxAnnotation callsiteAnnotation,
                SyntaxAnnotation methodDefinitionAnnotation)
            {
                Contract.ThrowIfNull(document);
                Contract.ThrowIfNull(methodNameAnnotation);
                Contract.ThrowIfNull(callsiteAnnotation);
                Contract.ThrowIfNull(methodDefinitionAnnotation);

                this.Status = status;
                this.SemanticDocument = document;
                this.MethodNameAnnotation = methodNameAnnotation;
                this.CallSiteAnnotation = callsiteAnnotation;
                this.MethodDefinitionAnnotation = methodDefinitionAnnotation;
            }
 /// <summary>
 /// Converts the type of the automatic error action.
 /// </summary>
 /// <param name="status">The status.</param>
 /// <returns></returns>
 internal static ErrorActionType ConvertToErrorActionType(OperationStatus status)
 {
     switch (status)
     {
         case OperationStatus.Failed:
             return ErrorActionType.Fail;
         case OperationStatus.Canceled:
             return ErrorActionType.Cancel;
         case OperationStatus.Retry:
             return ErrorActionType.Retry;
         case OperationStatus.Suspended:
             return ErrorActionType.Suspend;
         case OperationStatus.Succeeded:
             return ErrorActionType.Succeed;
         default:
             AsyncServiceException.Assert(false, "错误的作业状态。");
             return ErrorActionType.Fail;
     }
 }
        public static OperationStatus<Category> ShowWindow(Category obj)
        {
            OperationStatus<Category> status = new OperationStatus<Category>();
            status.Data = obj;
            CategoryDetails window = new CategoryDetails();
            window.DataContext = obj;
            window.uxCategoryComboBox.ItemsSource = BooksManager.BooksManager.GetCategoryList(Constants.ROOT_CATEGORY).Where(c => c.Id != obj.Id);

            var retStatus = window.ShowDialog();

            if (retStatus.HasValue && retStatus.Value)
            {
                status.Result = OperationResult.Passed;
            }
            else
                status.Result = OperationResult.Failed;

            return status;
        }
Exemplo n.º 16
0
        public static OperationStatus<Book> ShowWindow(Window owner, Book obj)
        {
            OperationStatus<Book> status = new OperationStatus<Book>();
            status.Data = obj;
            BookDetails window = new BookDetails();
            window.Owner = owner;
            window.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            window.DataContext = obj;
            window.book = obj;
            window.uxCategoryComboBox.ItemsSource = BooksManager.BooksManager.GetCategoryList(Constants.ROOT_CATEGORY, true);
            var retStatus = window.ShowDialog();

            if (retStatus.HasValue && retStatus.Value)
            {
                status.Result = OperationResult.Passed;
            }
            else
                status.Result = OperationResult.Failed;

            return status;
        }
Exemplo n.º 17
0
        public static OperationStatus<bool> CraeteDatabase(string filename)
        {
            OperationStatus<bool> status = new OperationStatus<bool>
                                               {
                                                   OperationMessage = "Database " + filename + " was created.",
                                                   Result = OperationResult.Passed
                                               };
            try
            {
                SQLiteConnection.CreateFile(filename);

                #region create tables
                SQLiteConnection connection = new SQLiteConnection(String.Format(connectionString, filename));
                connection.Open();
                using (SQLiteTransaction mytransaction = connection.BeginTransaction())
                {
                    using (SQLiteCommand mycommand = new SQLiteCommand(connection))
                    {
                        mycommand.CommandText = createCategoryTable;
                        mycommand.ExecuteNonQuery();

                        mycommand.CommandText = createBooksTable;
                        mycommand.ExecuteNonQuery();
                    }

                    mytransaction.Commit();
                }

                connection.Close();
                #endregion
            }
            catch (Exception exc)
            {
                status.Result = OperationResult.Failed;
                status.OperationMessage = exc.Message;
            }

            return status;
        }
            public async Task<OperationStatus<SemanticDocument>> ApplyAsync(GeneratedCode generatedCode, CancellationToken cancellationToken)
            {
                var document = generatedCode.SemanticDocument;
                var root = document.Root;

                var callsiteAnnotation = generatedCode.CallSiteAnnotation;
                var methodDefinitionAnnotation = generatedCode.MethodDefinitionAnnotation;

                var callsite = root.GetAnnotatedNodesAndTokens(callsiteAnnotation).SingleOrDefault().AsNode();
                var method = root.GetAnnotatedNodesAndTokens(methodDefinitionAnnotation).SingleOrDefault().AsNode();

                var annotationResolver = GetAnnotationResolver(callsite, method);
                var triviaResolver = GetTriviaResolver(method);
                if (annotationResolver == null || triviaResolver == null)
                {
                    // bug # 6644
                    // this could happen in malformed code. return as it was.
                    var status = new OperationStatus(OperationStatusFlag.None, FeaturesResources.CantNotConstructFinalTree);
                    return status.With(document);
                }

                return OperationStatus.Succeeded.With(
                    await document.WithSyntaxRootAsync(_result.RestoreTrivia(root, annotationResolver, triviaResolver), cancellationToken).ConfigureAwait(false));
            }
Exemplo n.º 19
0
 /// <summary>
 /// create operation status with the given data
 /// </summary>
 public static OperationStatus <T> Create <T>(OperationStatus status, T data)
 {
     return(new OperationStatus <T>(status, data));
 }
Exemplo n.º 20
0
 public UpdateStatus(OperationStatus status)
 {
     this.status = status;
 }
        /// <summary>
        /// Cancels the given operation.
        /// </summary>
        public void Cancel()
        {
            // If we are already cancelled or completed we can just leave.
            if (this.status == OperationStatus.Cancelled || this.status == OperationStatus.Completed)
            {
                return;
            }

            // if we have started we must remove the request from the service to cancel.
            if (this.status == OperationStatus.Started)
            {
                this.backgroundTransferService.Remove(this.request);
            }

            // if we have not started, or started we must switch the state to cancelled and
            // notify the TaskCompletionSource to cancel.
            this.status = OperationStatus.Cancelled;
            this.tcs.TrySetCanceled();
        }
Exemplo n.º 22
0
 public static void SetFaild(this OperationStatus operation)
 {
     operation.State = OperationState.Failed;
 }
Exemplo n.º 23
0
 private void AddErrors(OperationStatus result)
 {
     ModelState.AddModelError("", result.ToString());
 }
Exemplo n.º 24
0
        private void WriteStartUtf8Pretty(ReadOnlySpan <byte> nameSpanByte, byte token)
        {
            // quote {name} quote colon open-brace, hence 4
            int bytesNeeded = 4;

            if (_indent < 0)
            {
                bytesNeeded++;
            }

            if (Encodings.Utf16.ToUtf8Length(nameSpanByte, out int bytesNeededValue) != OperationStatus.Done)
            {
                JsonThrowHelper.ThrowArgumentExceptionInvalidUtf8String();
            }
            bytesNeeded += bytesNeededValue;

            int indent = _indent & RemoveFlagsBitMask;

            // For the new line, \r\n or \n, and the space after the colon
            bytesNeeded += JsonWriterHelper.NewLineUtf8.Length + 1 + indent * 2;

            Span <byte> byteBuffer = EnsureBuffer(bytesNeeded);
            int         idx        = 0;

            if (_indent < 0)
            {
                byteBuffer[idx++] = JsonConstants.ListSeperator;
            }

            // \r\n versus \n, depending on OS
            if (JsonWriterHelper.NewLineUtf8.Length == 2)
            {
                byteBuffer[idx++] = JsonConstants.CarriageReturn;
            }

            byteBuffer[idx++] = JsonConstants.LineFeed;

            while (indent-- > 0)
            {
                byteBuffer[idx++] = JsonConstants.Space;
                byteBuffer[idx++] = JsonConstants.Space;
            }

            byteBuffer[idx++] = JsonConstants.Quote;

            OperationStatus status = Encodings.Utf16.ToUtf8(nameSpanByte, byteBuffer.Slice(idx), out int consumed, out int written);

            Debug.Assert(consumed == nameSpanByte.Length);
            if (status != OperationStatus.Done)
            {
                JsonThrowHelper.ThrowFormatException();
            }

            idx += written;

            byteBuffer[idx++] = JsonConstants.Quote;

            byteBuffer[idx++] = JsonConstants.KeyValueSeperator;

            byteBuffer[idx++] = JsonConstants.Space;

            byteBuffer[idx++] = token;

            _bufferWriter.Advance(idx);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Transcodes the UTF-8 <paramref name="source"/> buffer to <paramref name="destination"/> as UTF-16.
        /// </summary>
        /// <remarks>
        /// If <paramref name="replaceInvalidSequences"/> is <see langword="true"/>, invalid UTF-8 sequences
        /// in <paramref name="source"/> will be replaced with U+FFFD in <paramref name="destination"/>, and
        /// this method will not return <see cref="OperationStatus.InvalidData"/>.
        /// </remarks>
        public static unsafe OperationStatus ToUtf16(ReadOnlySpan <byte> source, Span <char> destination, out int numBytesRead, out int numCharsWritten, bool replaceInvalidSequences = true, bool isFinalBlock = true)
        {
            // Throwaway span accesses - workaround for https://github.com/dotnet/coreclr/issues/23437

            _ = source.Length;
            _ = destination.Length;

            // We'll be mutating these values throughout our loop.

            fixed(byte *pOriginalSource = &MemoryMarshal.GetReference(source))
            fixed(char *pOriginalDestination = &MemoryMarshal.GetReference(destination))
            {
                // We're going to bulk transcode as much as we can in a loop, iterating
                // every time we see bad data that requires replacement.

                OperationStatus operationStatus        = OperationStatus.Done;
                byte *          pInputBufferRemaining  = pOriginalSource;
                char *          pOutputBufferRemaining = pOriginalDestination;

                while (!source.IsEmpty)
                {
                    // We've pinned the spans at the entry point to this method.
                    // It's safe for us to use Unsafe.AsPointer on them during this loop.

                    operationStatus = Utf8Utility.TranscodeToUtf16(
                        pInputBuffer: (byte *)Unsafe.AsPointer(ref MemoryMarshal.GetReference(source)),
                        inputLength: source.Length,
                        pOutputBuffer: (char *)Unsafe.AsPointer(ref MemoryMarshal.GetReference(destination)),
                        outputCharsRemaining: destination.Length,
                        pInputBufferRemaining: out pInputBufferRemaining,
                        pOutputBufferRemaining: out pOutputBufferRemaining);

                    // If we finished the operation entirely or we ran out of space in the destination buffer,
                    // or if we need more input data and the caller told us that there's possibly more data
                    // coming, return immediately.

                    if (operationStatus <= OperationStatus.DestinationTooSmall ||
                        (operationStatus == OperationStatus.NeedMoreData && !isFinalBlock))
                    {
                        break;
                    }

                    // We encountered invalid data, or we need more data but the caller told us we're
                    // at the end of the stream. In either case treat this as truly invalid.
                    // If the caller didn't tell us to replace invalid sequences, return immediately.

                    if (!replaceInvalidSequences)
                    {
                        operationStatus = OperationStatus.InvalidData; // status code may have been NeedMoreData - force to be error
                        break;
                    }

                    // We're going to attempt to write U+FFFD to the destination buffer.
                    // Do we even have enough space to do so?

                    destination = destination.Slice((int)(pOutputBufferRemaining - (char *)Unsafe.AsPointer(ref MemoryMarshal.GetReference(destination))));

                    if (destination.IsEmpty)
                    {
                        operationStatus = OperationStatus.DestinationTooSmall;
                        break;
                    }

                    destination[0] = (char)UnicodeUtility.ReplacementChar;
                    destination    = destination.Slice(1);

                    // Now figure out how many bytes of the source we must skip over before we should retry
                    // the operation. This might be more than 1 byte.

                    source = source.Slice((int)(pInputBufferRemaining - (byte *)Unsafe.AsPointer(ref MemoryMarshal.GetReference(source))));
                    Debug.Assert(!source.IsEmpty, "Expected 'Done' if source is fully consumed.");

                    Rune.DecodeFromUtf8(source, out _, out int bytesConsumedJustNow);
                    source = source.Slice(bytesConsumedJustNow);

                    operationStatus        = OperationStatus.Done; // we patched the error - if we're about to break out of the loop this is a success case
                    pInputBufferRemaining  = (byte *)Unsafe.AsPointer(ref MemoryMarshal.GetReference(source));
                    pOutputBufferRemaining = (char *)Unsafe.AsPointer(ref MemoryMarshal.GetReference(destination));
                }

                // Not possible to make any further progress - report to our caller how far we got.

                numBytesRead    = (int)(pInputBufferRemaining - pOriginalSource);
                numCharsWritten = (int)(pOutputBufferRemaining - pOriginalDestination);
                return(operationStatus);
            }
        }
Exemplo n.º 26
0
		internal static void RegisterOperation(this IHasTrackingContext context, OperationStatus operation, string language)
		{
			var trackingContext = context.TrackingContext;
			trackingContext.RegisterOperation(operation, language);
		}
Exemplo n.º 27
0
        public static void UpdateStatus(SavedOpData operation, OperationStatus opStatus)
        {
            var id = operation.filedata_app_id;
            var fullpath = Path.Combine(OpDirectory, id + ".data");

            if (!File.Exists(fullpath))
            {
                Logger.Log("Attempting to update operation: {0} but it was not found.", LogLevel.Info, operation.filedata_app_name);
                return;
            }

            try
            {
                var deserialized = JsonConvert.DeserializeObject<SavedOpData>((File.ReadAllText(fullpath)));
                deserialized.operation_status = opStatus;

                var serialized = JsonConvert.SerializeObject(deserialized);
                File.WriteAllText(fullpath, serialized);
            }
            catch
            {
                Logger.Log("Error when attempting to Update operation status.");
            }
        }
Exemplo n.º 28
0
        public void TryDecodeToUnicodeMultipleCodePoints(bool useUtf8Encoder, uint[] expectedCodePointsArray, byte[] inputBytesArray, OperationStatus expectedReturnVal)
        {
            ReadOnlySpan <byte> expectedBytes = expectedCodePointsArray.AsSpan().AsBytes();
            ReadOnlySpan <byte> inputBytes    = inputBytesArray;
            Span <byte>         codePoints    = new byte[expectedBytes.Length];
            int             written;
            int             consumed;
            OperationStatus result;

            if (useUtf8Encoder)
            {
                result = Encodings.Utf8.ToUtf32(inputBytes, codePoints, out consumed, out written);
            }
            else
            {
                result = Encodings.Utf16.ToUtf32(inputBytes, codePoints, out consumed, out written);
            }

            Assert.Equal(expectedReturnVal, result);
            Assert.Equal(inputBytes.Length, consumed);
            Assert.Equal(codePoints.Length, written);
            Assert.True(expectedBytes.SequenceEqual(codePoints), "Bad output sequence");
        }
Exemplo n.º 29
0
 public static void SetRunning(this OperationStatus operation)
 {
     operation.State = OperationState.Running;
 }
Exemplo n.º 30
0
        public void UTF16ToUTF8EncodingTestForReadOnlySpanOfChar(byte[] expectedBytes, char[] chars, OperationStatus expectedReturnVal)
        {
            ReadOnlySpan <byte> utf16  = MemoryMarshal.Cast <char, byte>(new ReadOnlySpan <char>(chars));
            Span <byte>         buffer = new byte[expectedBytes.Length];

            Assert.Equal(expectedReturnVal, Encodings.Utf16.ToUtf8(utf16, buffer, out int consumed, out int written));
            Assert.Equal(expectedBytes.Length, written);

            if (expectedBytes.Length > 0)
            {
                Assert.Equal(utf16.Length, consumed);
                Assert.True(buffer.Slice(0, written).SequenceEqual(expectedBytes));
            }
        }
        protected override void GenerateInternal(OperationStatus op, BuildType buildType)
        {
            if (OrmPackages.Length == 0)
            {
                return;
            }

            EnsureLibraries();

            IFileInfo   projectInfoPath = FileSystem.GetFileInfo(Path.Combine(FullProjectDirectory, "project.info.xml"));
            ProjectInfo local           = ProjectInfo.Load(projectInfoPath);

            if (local == null || local.InstanceId != Project.InstanceId)
            {
                if (buildType == BuildType.Build)
                {
                    Logging.BuildLog.Info("Full build required");
                }

                buildType = BuildType.BuildAll;
                local     = new ProjectInfo {
                    InstanceId = Project.InstanceId
                };

                if (projectInfoPath.Directory.Exists)
                {
                    foreach (var file in projectInfoPath.Directory.GetFiles())
                    {
                        file.Delete();
                    }
                }
            }

            CopyEntityInterfacesAssembly();

            string path = FullProjectDirectory;

            var generatorList = new List <BaseEntityGenerator>();

            // generate entities
            BaseEntityGenerator baseGen = new SDataClientEntityCodeGenerator();

            baseGen.Initialize(WorkingDirectoryPath);
            generatorList.Add(baseGen);

            // Ensure all paths are created
            foreach (var gen in generatorList)
            {
                string relPath = Path.Combine(path, gen.RelativePath);
                if (!Directory.Exists(relPath))
                {
                    Directory.CreateDirectory(relPath);
                }
            }

            var model = (OrmModel)OrmPackages[0].Model;

            var engine = new Engine {
                DefaultToolsVersion = "3.5"
            };
            bool atLeastOneFileWasGenerated = false;
            var  buildItemFiles             = new List <BuildItemFileInfo>();

            foreach (var entity in OrmEntity.GetAll(model.Project).Where(item => item.Generate && item.GenerateSDataFeed))
            {
                if (!op.CanContinue)
                {
                    return;
                }

                foreach (var generator in generatorList)
                {
                    string fullPath = Path.Combine(Path.Combine(path, generator.RelativePath), generator.FormatFileName(entity.Name));
                    var    fi       = new FileInfo(fullPath);

                    if (BuildHelper.IsEntityNewer(buildType, fi.LastWriteTimeUtc, entity))
                    {
                        using (var writer = new StreamWriter(fullPath))
                        {
                            generator.Generate(entity, writer);
                        }
                        atLeastOneFileWasGenerated = true;
                    }

                    buildItemFiles.Add(new BuildItemFileInfo(generator, fullPath));
                }
            }

            if (atLeastOneFileWasGenerated)
            {
                BuildProject(buildItemFiles, engine);
            }

            if (op.CanContinue)
            {
                local.Save(projectInfoPath);
            }
        }
Exemplo n.º 32
0
 public static void SetAborted(this OperationStatus operation)
 {
     operation.State = OperationState.Aborted;
 }
Exemplo n.º 33
0
        public static void UpdateOperation(SavedOpData operation, bool installSuccess, bool rebootNeeded, OperationStatus opStatus, string path = "")
        {
            var    id = operation.filedata_app_id;
            string fullpath;

            if (path != "")
            {
                fullpath = path;
            }
            else
            {
                fullpath = Path.Combine(Tools.GetOpDirectory(), id + ".data");
            }

            if (!File.Exists(fullpath))
            {
                return;
            }

            try
            {
                var deserialized = JsonConvert.DeserializeObject <SavedOpData>(Security.Decrypt(File.ReadAllText(fullpath)));
                deserialized.success          = installSuccess.ToString();
                deserialized.reboot_required  = rebootNeeded.ToString().ToLower();
                deserialized.operation_status = opStatus;
                deserialized.error            = operation.error;

                var serialized = JsonConvert.SerializeObject(deserialized);
                serialized = Security.Encrypt(serialized);

                File.WriteAllText(fullpath, serialized);
            }
            catch
            {
            }
        }
Exemplo n.º 34
0
 [InlineData(new char[] { '\ud800', '\u1234' }, OperationStatus.InvalidData, 0xFFFD, 1)] // standalone high surrogate
 public static void DecodeFromUtf16(char[] data, OperationStatus expectedOperationStatus, int expectedRuneValue, int expectedCharsConsumed)
 {
     Assert.Equal(expectedOperationStatus, Rune.DecodeFromUtf16(data, out Rune actualRune, out int actualCharsConsumed));
     Assert.Equal(expectedRuneValue, actualRune.Value);
     Assert.Equal(expectedCharsConsumed, actualCharsConsumed);
 }
Exemplo n.º 35
0
        private void WriteAttributeUtf8Pretty(ReadOnlySpan <byte> nameSpan, long value)
        {
            // quote {name} quote colon, hence 3
            int bytesNeeded = 3;

            if (_indent < 0)
            {
                bytesNeeded++;
            }

            if (Encodings.Utf16.ToUtf8Length(nameSpan, out int bytesNeededName) != OperationStatus.Done)
            {
                JsonThrowHelper.ThrowArgumentExceptionInvalidUtf8String();
            }
            bytesNeeded += bytesNeededName;

            // For the new line, \r\n or \n, and the space after the colon
            bytesNeeded += JsonWriterHelper.NewLineUtf8.Length + 1 + (_indent & RemoveFlagsBitMask) * 2;

            bool insertNegationSign = false;

            if (value < 0)
            {
                insertNegationSign = true;
                value        = -value;
                bytesNeeded += 1;
            }

            int digitCount = JsonWriterHelper.CountDigits((ulong)value);

            bytesNeeded += digitCount;
            Span <byte> byteBuffer = EnsureBuffer(bytesNeeded);

            int idx = 0;

            if (_indent < 0)
            {
                byteBuffer[idx++] = JsonConstants.ListSeperator;
            }

            idx += AddNewLineAndIndentation(byteBuffer.Slice(idx));

            byteBuffer[idx++] = JsonConstants.Quote;

            OperationStatus status = Encodings.Utf16.ToUtf8(nameSpan, byteBuffer.Slice(idx), out int consumed, out int written);

            if (status != OperationStatus.Done)
            {
                JsonThrowHelper.ThrowFormatException();
            }
            Debug.Assert(consumed == nameSpan.Length);
            idx += written;

            byteBuffer[idx++] = JsonConstants.Quote;

            byteBuffer[idx++] = JsonConstants.KeyValueSeperator;

            byteBuffer[idx++] = JsonConstants.Space;

            _indent |= 1 << 31;

            if (insertNegationSign)
            {
                byteBuffer[idx++] = (byte)'-';
            }

            JsonWriterHelper.WriteDigitsUInt64D((ulong)value, byteBuffer.Slice(idx, digitCount));

            _bufferWriter.Advance(bytesNeeded);
        }
Exemplo n.º 36
0
        private void SpeechPopup_NetworkOperationInProgressCallBack(bool operationInProgress, OperationStatus status)
        {
            // call the MainViewModel's routine to make sure global network status is reset
            App.ViewModel.NetworkOperationInProgressCallback(operationInProgress, status);

            // signal whether the net operation is in progress or not
            SpeechNetworkOperationInProgress = (operationInProgress == true ? Visibility.Visible : Visibility.Collapsed);

            // if the operationSuccessful flag is null, no new data; otherwise, it signals the status of the last operation
            if (status != OperationStatus.Started)
            {
                if (status != OperationStatus.Success)
                {   // the server wasn't reachable
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show("Unable to access the speech service at this time.");
                        SpeechPopup_Close();
                    });
                }
            }
        }
Exemplo n.º 37
0
        /*
         * OperationStatus-based APIs for transcoding of chunked data.
         * This method is similar to Encoding.UTF8.GetBytes / GetChars but has a
         * different calling convention, different error handling mechanisms, and
         * different performance characteristics.
         *
         * If 'replaceInvalidSequences' is true, the method will replace any ill-formed
         * subsequence in the source with U+FFFD when transcoding to the destination,
         * then it will continue processing the remainder of the buffers. Otherwise
         * the method will return OperationStatus.InvalidData.
         *
         * If the method does return an error code, the out parameters will represent
         * how much of the data was successfully transcoded, and the location of the
         * ill-formed subsequence can be deduced from these values.
         *
         * If 'replaceInvalidSequences' is true, the method is guaranteed never to return
         * OperationStatus.InvalidData. If 'isFinalBlock' is true, the method is
         * guaranteed never to return OperationStatus.NeedMoreData.
         */

        /// <summary>
        /// Transcodes the UTF-16 <paramref name="source"/> buffer to <paramref name="destination"/> as UTF-8.
        /// </summary>
        /// <remarks>
        /// If <paramref name="replaceInvalidSequences"/> is <see langword="true"/>, invalid UTF-16 sequences
        /// in <paramref name="source"/> will be replaced with U+FFFD in <paramref name="destination"/>, and
        /// this method will not return <see cref="OperationStatus.InvalidData"/>.
        /// </remarks>
        public static unsafe OperationStatus FromUtf16(ReadOnlySpan <char> source, Span <byte> destination, out int charsRead, out int bytesWritten, bool replaceInvalidSequences = true, bool isFinalBlock = true)
        {
            // Throwaway span accesses - workaround for https://github.com/dotnet/coreclr/issues/23437

            _ = source.Length;
            _ = destination.Length;

            fixed(char *pOriginalSource = &MemoryMarshal.GetReference(source))
            fixed(byte *pOriginalDestination = &MemoryMarshal.GetReference(destination))
            {
                // We're going to bulk transcode as much as we can in a loop, iterating
                // every time we see bad data that requires replacement.

                OperationStatus operationStatus        = OperationStatus.Done;
                char *          pInputBufferRemaining  = pOriginalSource;
                byte *          pOutputBufferRemaining = pOriginalDestination;

                while (!source.IsEmpty)
                {
                    // We've pinned the spans at the entry point to this method.
                    // It's safe for us to use Unsafe.AsPointer on them during this loop.

                    operationStatus = Utf8Utility.TranscodeToUtf8(
                        pInputBuffer: (char *)Unsafe.AsPointer(ref MemoryMarshal.GetReference(source)),
                        inputLength: source.Length,
                        pOutputBuffer: (byte *)Unsafe.AsPointer(ref MemoryMarshal.GetReference(destination)),
                        outputBytesRemaining: destination.Length,
                        pInputBufferRemaining: out pInputBufferRemaining,
                        pOutputBufferRemaining: out pOutputBufferRemaining);

                    // If we finished the operation entirely or we ran out of space in the destination buffer,
                    // or if we need more input data and the caller told us that there's possibly more data
                    // coming, return immediately.

                    if (operationStatus <= OperationStatus.DestinationTooSmall ||
                        (operationStatus == OperationStatus.NeedMoreData && !isFinalBlock))
                    {
                        break;
                    }

                    // We encountered invalid data, or we need more data but the caller told us we're
                    // at the end of the stream. In either case treat this as truly invalid.
                    // If the caller didn't tell us to replace invalid sequences, return immediately.

                    if (!replaceInvalidSequences)
                    {
                        operationStatus = OperationStatus.InvalidData; // status code may have been NeedMoreData - force to be error
                        break;
                    }

                    // We're going to attempt to write U+FFFD to the destination buffer.
                    // Do we even have enough space to do so?

                    destination = destination.Slice((int)(pOutputBufferRemaining - (byte *)Unsafe.AsPointer(ref MemoryMarshal.GetReference(destination))));

                    if (2 >= (uint)destination.Length)
                    {
                        operationStatus = OperationStatus.DestinationTooSmall;
                        break;
                    }

                    destination[0] = 0xEF; // U+FFFD = [ EF BF BD ] in UTF-8
                    destination[1] = 0xBF;
                    destination[2] = 0xBD;
                    destination    = destination.Slice(3);

                    // Invalid UTF-16 sequences are always of length 1. Just skip the next character.

                    source = source.Slice((int)(pInputBufferRemaining - (char *)Unsafe.AsPointer(ref MemoryMarshal.GetReference(source))) + 1);

                    operationStatus        = OperationStatus.Done; // we patched the error - if we're about to break out of the loop this is a success case
                    pInputBufferRemaining  = (char *)Unsafe.AsPointer(ref MemoryMarshal.GetReference(source));
                    pOutputBufferRemaining = (byte *)Unsafe.AsPointer(ref MemoryMarshal.GetReference(destination));
                }

                // Not possible to make any further progress - report to our caller how far we got.

                charsRead    = (int)(pInputBufferRemaining - pOriginalSource);
                bytesWritten = (int)(pOutputBufferRemaining - pOriginalDestination);
                return(operationStatus);
            }
        }
Exemplo n.º 38
0
 private UnCheckoutInfo(string path, OperationStatus status)
 {
     Path = path;
     Status = status;
 }
Exemplo n.º 39
0
        /// <summary>
        /// 注册命令
        /// </summary>
        public void RegisterMessage()
        {
            Messenger.Default.Register <object>(this, EnumMessageKey.ChangeDateRegister, msg =>
            {
                if (null != msg && !string.IsNullOrEmpty(msg.ToString()) && this.CheckData())
                {
                    this.SaveData();
                    ViewFlag = msg.ToString();

                    // 执行的手术时间必须是按顺序
                    // 当前手术状态
                    OperationStatus curOperStatus  = (OperationStatus)_masterRow.OPER_STATUS_CODE;
                    OperationStatus nextOperStatus = OperationStatus.None;

                    // 目标状态
                    OperationStatus targetOperStatus = OperationStatusHelper.OperationStatusFromString(ViewFlag);

                    if (curOperStatus >= targetOperStatus)
                    {
                    }
                    else
                    {
                        switch (curOperStatus)
                        {
                        case OperationStatus.InOperationRoom:
                            nextOperStatus = OperationStatus.AnesthesiaStart;
                            break;

                        case OperationStatus.AnesthesiaStart:
                            nextOperStatus = OperationStatus.OperationStart;
                            break;

                        case OperationStatus.OperationStart:
                            nextOperStatus = OperationStatus.OperationEnd;
                            break;

                        case OperationStatus.OperationEnd:
                            nextOperStatus = OperationStatus.AnesthesiaEnd;
                            break;

                        case OperationStatus.AnesthesiaEnd:
                            nextOperStatus = OperationStatus.OutOperationRoom;
                            break;
                        }

                        if (nextOperStatus == OperationStatus.None || nextOperStatus != targetOperStatus)
                        {
                            this.ShowMessageBox("请按流程顺序操作!", MessageBoxButton.OK, MessageBoxImage.Warning);
                            return;
                        }
                        else if (nextOperStatus == targetOperStatus &&
                                 nextOperStatus == OperationStatus.OutOperationRoom)
                        {
                            this.Result = true;
                            this.CloseContentWindow();
                        }
                    }

                    this.InRoomVisible     = Visibility.Collapsed;
                    this.InRoomBackVisible = Visibility.Collapsed;
                    this.InRoomEnable      = false;
                    this.InRoomFinish      = false;

                    this.AnesStartVisible     = Visibility.Collapsed;
                    this.AnesStartBackVisible = Visibility.Collapsed;
                    this.AnesStartEnable      = false;
                    this.AnesStartFinish      = false;

                    this.OperStartVisible     = Visibility.Collapsed;
                    this.OperStartBackVisible = Visibility.Collapsed;
                    this.OperStartEnable      = false;
                    this.OperStartFinish      = false;

                    this.OperEndVisible     = Visibility.Collapsed;
                    this.OperEndBackVisible = Visibility.Collapsed;
                    this.OperEndEnable      = false;
                    this.OperEndFinish      = false;

                    this.AnesEndVisible     = Visibility.Collapsed;
                    this.AnesEndBackVisible = Visibility.Collapsed;
                    this.AnesEndEnable      = false;
                    this.AnesEndFinish      = false;

                    this.OutRoomVisible     = Visibility.Collapsed;
                    this.OutRoomBackVisible = Visibility.Collapsed;
                    this.OutRoomEnable      = false;
                    this.OutRoomFinish      = false;
                    this.LoadData();
                    Messenger.Default.Send <object>(true, EnumMessageKey.RefreshDateRegisterFocus);
                }
            });
        }
Exemplo n.º 40
0
 public static void SetCompleted(this OperationStatus operation)
 {
     operation.State = OperationState.Completed;
 }
Exemplo n.º 41
0
		/// <summary>
		/// Registers a specified operation.
		/// </summary>
		/// <param name="operation">The operation.</param>
		public void RegisterOperation(OperationStatus operation, string language)
		{
			if (!string.IsNullOrEmpty(language))
			{
			}
		}
Exemplo n.º 42
0
        private void SetOperStatusEnable()
        {
            OperationStatus operSate       = OperationStatusHelper.OperationStatusFromString(ViewFlag);
            int             patStatuIndex  = OperationStatusHelper.GetOperStatusIndex(ExtendAppContext.Current.PatientInformationExtend.OPER_STATUS_CODE);
            int             curntEditIndex = OperationStatusHelper.GetOperStatusIndex((int)operSate);

            //当前编辑已填写的状态的时间
            if (patStatuIndex > curntEditIndex)
            {
                visibIndex = patStatuIndex;
            }
            //编辑新的状态时间
            else
            {
                visibIndex     = curntEditIndex;
                operStatusCode = (int)operSate;
            }
            StepIndex       = visibIndex - 1;
            curntStatusCode = (int)operSate;

            enableIndex = curntEditIndex;


            switch (visibIndex)
            {
            case 1:
                InRoomVisible = Visibility.Visible;
                InRoomFinish  = true;
                break;

            case 2:
                InRoomVisible    = Visibility.Visible;
                AnesStartVisible = Visibility.Visible;
                InRoomFinish     = true;
                AnesStartFinish  = true;
                break;

            case 3:
                InRoomVisible    = Visibility.Visible;
                AnesStartVisible = Visibility.Visible;
                OperStartVisible = Visibility.Visible;
                InRoomFinish     = true;
                AnesStartFinish  = true;
                OperStartFinish  = true;
                break;

            case 4:
                InRoomVisible    = Visibility.Visible;
                AnesStartVisible = Visibility.Visible;
                OperStartVisible = Visibility.Visible;
                OperEndVisible   = Visibility.Visible;
                InRoomFinish     = true;
                AnesStartFinish  = true;
                OperStartFinish  = true;
                OperEndFinish    = true;
                break;

            case 5:
                InRoomVisible    = Visibility.Visible;
                AnesStartVisible = Visibility.Visible;
                OperStartVisible = Visibility.Visible;
                OperEndVisible   = Visibility.Visible;
                AnesEndVisible   = Visibility.Visible;
                InRoomFinish     = true;
                AnesStartFinish  = true;
                OperStartFinish  = true;
                OperEndFinish    = true;
                AnesEndFinish    = true;
                break;

            case 6:
                InRoomVisible    = Visibility.Visible;
                AnesStartVisible = Visibility.Visible;
                OperStartVisible = Visibility.Visible;
                OperEndVisible   = Visibility.Visible;
                AnesEndVisible   = Visibility.Visible;
                OutRoomVisible   = Visibility.Visible;
                InRoomFinish     = true;
                AnesStartFinish  = true;
                OperStartFinish  = true;
                OperEndFinish    = true;
                AnesEndFinish    = true;
                OutRoomFinish    = true;
                break;
            }

            switch (enableIndex)
            {
            case 1:
                InRoomEnable      = true;
                InRoomBackVisible = Visibility.Visible;
                InRoomFinish      = false;
                break;

            case 2:
                AnesStartEnable      = true;
                AnesStartBackVisible = Visibility.Visible;
                AnesStartFinish      = false;
                break;

            case 3:
                OperStartEnable      = true;
                OperStartBackVisible = Visibility.Visible;
                OperStartFinish      = false;
                break;

            case 4:
                OperEndEnable      = true;
                OperEndBackVisible = Visibility.Visible;
                OperEndFinish      = false;
                break;

            case 5:
                AnesEndEnable      = true;
                AnesEndBackVisible = Visibility.Visible;
                AnesEndFinish      = false;
                break;

            case 6:
                OutRoomEnable      = true;
                OutRoomBackVisible = Visibility.Visible;
                OutRoomFinish      = false;
                break;
            }
        }
Exemplo n.º 43
0
        public static void UpdateOperation(SavedOpData operation, bool installSuccess, bool rebootNeeded, OperationStatus opStatus)
        {
            var id       = operation.filedata_app_id;
            var fullpath = Path.Combine(OpDirectory, id + ".data");

            if (!File.Exists(fullpath))
            {
                Logger.Log("Attempting to update operation: {0} but it was not found.", LogLevel.Info, operation.filedata_app_name);
                return;
            }

            try
            {
                var deserialized                = JsonConvert.DeserializeObject<SavedOpData>((File.ReadAllText(fullpath)));
                deserialized.success            = installSuccess.ToString().ToLower();
                deserialized.reboot_required    = rebootNeeded.ToString().ToLower();
                deserialized.operation_status   = opStatus;

                var serialized = JsonConvert.SerializeObject(deserialized);
                File.WriteAllText(fullpath, serialized);
            }
            catch (Exception)
            {
                Logger.Log("Error when attempting to Update operation: {0}, with install success of:{1}, reboot:{2}", LogLevel.Info, operation.filedata_app_name, operation.success, operation.restart);
            }
        }
        /// <summary>
        /// The Get Operation Status operation returns the status of
        /// thespecified operation. After calling an asynchronous operation,
        /// you can call Get Operation Status to determine whether the
        /// operation has succeeded, failed, or is still in progress.  (see
        /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx
        /// for more information)
        /// </summary>
        /// <param name='requestId'>
        /// Required. The request ID for the request you wish to track. The
        /// request ID is returned in the x-ms-request-id response header for
        /// every request.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response body contains the status of the specified asynchronous
        /// operation, indicating whether it has succeeded, is inprogress, or
        /// has failed. Note that this status is distinct from the HTTP status
        /// code returned for the Get Operation Status operation itself.  If
        /// the asynchronous operation succeeded, the response body includes
        /// the HTTP status code for the successful request.  If the
        /// asynchronous operation failed, the response body includes the HTTP
        /// status code for the failed request, and also includes error
        /// information regarding the failure.
        /// </returns>
        public async System.Threading.Tasks.Task <OperationStatusResponse> GetOperationStatusAsync(string requestId, CancellationToken cancellationToken)
        {
            // Validate
            if (requestId == null)
            {
                throw new ArgumentNullException("requestId");
            }

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = Tracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("requestId", requestId);
                Tracing.Enter(invocationId, this, "GetOperationStatusAsync", tracingParameters);
            }

            // Construct URL
            string url     = "/" + (this.Credentials.SubscriptionId != null ? this.Credentials.SubscriptionId.Trim() : "") + "/operations/" + requestId.Trim();
            string baseUrl = this.BaseUri.AbsoluteUri;

            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

            try
            {
                httpRequest            = new HttpRequestMessage();
                httpRequest.Method     = HttpMethod.Get;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers
                httpRequest.Headers.Add("x-ms-version", "2013-06-01");

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        Tracing.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        Tracing.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    OperationStatusResponse result = null;
                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    result = new OperationStatusResponse();
                    XDocument responseDoc = XDocument.Parse(responseContent);

                    XElement operationElement = responseDoc.Element(XName.Get("Operation", "http://schemas.microsoft.com/windowsazure"));
                    if (operationElement != null)
                    {
                        XElement idElement = operationElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
                        if (idElement != null)
                        {
                            string idInstance = idElement.Value;
                            result.Id = idInstance;
                        }

                        XElement statusElement = operationElement.Element(XName.Get("Status", "http://schemas.microsoft.com/windowsazure"));
                        if (statusElement != null)
                        {
                            OperationStatus statusInstance = ((OperationStatus)Enum.Parse(typeof(OperationStatus), statusElement.Value, true));
                            result.Status = statusInstance;
                        }

                        XElement httpStatusCodeElement = operationElement.Element(XName.Get("HttpStatusCode", "http://schemas.microsoft.com/windowsazure"));
                        if (httpStatusCodeElement != null)
                        {
                            HttpStatusCode httpStatusCodeInstance = ((HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), httpStatusCodeElement.Value, true));
                            result.HttpStatusCode = httpStatusCodeInstance;
                        }

                        XElement errorElement = operationElement.Element(XName.Get("Error", "http://schemas.microsoft.com/windowsazure"));
                        if (errorElement != null)
                        {
                            OperationStatusResponse.ErrorDetails errorInstance = new OperationStatusResponse.ErrorDetails();
                            result.Error = errorInstance;

                            XElement codeElement = errorElement.Element(XName.Get("Code", "http://schemas.microsoft.com/windowsazure"));
                            if (codeElement != null)
                            {
                                string codeInstance = codeElement.Value;
                                errorInstance.Code = codeInstance;
                            }

                            XElement messageElement = errorElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure"));
                            if (messageElement != null)
                            {
                                string messageInstance = messageElement.Value;
                                errorInstance.Message = messageInstance;
                            }
                        }
                    }

                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        Tracing.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
 private OperationStatusResponse CreateComputeOperationResponse(string requestId, OperationStatus status = OperationStatus.Succeeded)
 {
     return new OperationStatusResponse
     {
         Error = null,
         HttpStatusCode = HttpStatusCode.OK,
         Id = "id",
         RequestId = requestId,
         Status = status,
         StatusCode = HttpStatusCode.OK
     };
 }
 public static Models.Operation Operation(string operationId = default, OperationStatus status = default, UpdateId updateId = default, string resourceLocation = default, Error error = default, string traceId = default, DateTimeOffset lastActionDateTime = default, DateTimeOffset createdDateTime = default, string etag = default)
 {
     return(new Models.Operation(operationId, status, updateId, resourceLocation, error, traceId, lastActionDateTime, createdDateTime, etag));
 }
Exemplo n.º 47
0
 /// <summary>
 ///     设置处理状态
 /// </summary>
 /// <param name="status">处理状态</param>
 public void SetOperationStatus(OperationStatus status)
 {
     switch (status)
     {
         case OperationStatus.草稿:
             Status = OperationStatus.草稿;
             break;
         case OperationStatus.待审核:
             Status = OperationStatus.待审核;
             break;
         case OperationStatus.已审核:
             Status = OperationStatus.已审核;
             break;
         case OperationStatus.已提交:
             Status = OperationStatus.已提交;
             break;
         default:
             throw new ArgumentOutOfRangeException("status");
     }
 }
Exemplo n.º 48
0
 protected internal abstract void Hide([NotNull] OperationContext context, OperationStatus status);
Exemplo n.º 49
0
 public UpdateStatus()
 {
     status = OperationStatus.CONFIGURING;
 }
Exemplo n.º 50
0
        async Task ReadLoop()
        {
            using (_config.InputLogger?.InputLoopStarting())
            {
                try
                {
                    while (!StopToken.IsCancellationRequested)
                    {
                        ReadResult read = await _pipeReader.ReadAsync(StopToken);

                        IInputLogger?m = _config.InputLogger;
                        if (StopToken.IsCancellationRequested || read.IsCanceled)
                        {
                            m?.ReadLoopTokenCancelled();
                            break;//The client called the cancel, no need to notify it.
                        }
                        //The packet header require 2-5 bytes
                        OperationStatus res = TryParsePacketHeader(read.Buffer, out byte header, out int length, out SequencePosition position);
                        if (res == OperationStatus.InvalidData)
                        {
                            m?.InvalidIncomingData();
                            await DisconnectAsync(DisconnectedReason.ProtocolError);

                            break;
                        }
                        if (res == OperationStatus.Done)
                        {
                            _pipeReader.AdvanceTo(position);
                            using (m?.IncomingPacket(header, length))
                            {
                                // TODO: Can concurrently changing the ref to CurrentReflex could cause an issue here ? Lets hope not for now.
                                await CurrentReflex(m, this, header, length, _pipeReader, StopToken);
                            }
                            continue;
                        }
                        Debug.Assert(res == OperationStatus.NeedMoreData);
                        if (read.IsCompleted)
                        {
                            if (read.Buffer.Length == 0)
                            {
                                m?.EndOfStream();
                            }
                            else
                            {
                                m?.UnexpectedEndOfStream();
                            }
                            await DisconnectAsync(DisconnectedReason.RemoteDisconnected);

                            break;
                        }
                        _pipeReader.AdvanceTo(read.Buffer.Start, read.Buffer.End);  //Mark data observed, so we will wait new data.
                    }
                    _pipeReader.Complete();
                    _pipeReader.CancelPendingRead();
                }
                catch (OperationCanceledException e)
                {
                    _config.InputLogger?.LoopCanceledException(e);
                }
                catch (Exception e)
                {
                    _config.InputLogger?.ExceptionOnParsingIncomingData(e);
                    await DisconnectAsync(DisconnectedReason.UnspecifiedError);
                }
            }
        }
Exemplo n.º 51
0
 public AddedInfo(string path, OperationStatus status)
 {
     Path = path;
     Status = status;
 }
Exemplo n.º 52
0
 [InlineData(new byte[] { 0xF0, 0x9F, 0x98, }, OperationStatus.NeedMoreData, 0xFFFD, 3)]      // [ F0 9F 98 ] is valid 3-byte start of 4-byte sequence
 public static void DecodeLastFromUtf8(byte[] data, OperationStatus expectedOperationStatus, int expectedRuneValue, int expectedBytesConsumed)
 {
     Assert.Equal(expectedOperationStatus, Rune.DecodeLastFromUtf8(data, out Rune actualRune, out int actualBytesConsumed));
     Assert.Equal(expectedRuneValue, actualRune.Value);
     Assert.Equal(expectedBytesConsumed, actualBytesConsumed);
 }
Exemplo n.º 53
0
 internal PlayAudioResultEvent(ResultInfo resultInfo, string operationContext, OperationStatus status)
 {
     ResultInfo       = resultInfo;
     OperationContext = operationContext;
     Status           = status;
 }
 public BatchMatchingAssessorResponse()
 {
     Assessors       = new List <ASSESSOR.Assessor>();
     OperationStatus = new OperationStatus();
 }
 private BackgroundDownloadOperation(Builder builder)
 {
     this.requestUri = builder.RequestUri;
     this.accessToken = builder.AccessToken;
     this.downloadLocationOnDevice = builder.DownloadLocationOnDevice;
     this.backgroundTransferService = builder.BackgroundTransferService;
     this.progress = builder.Progress;
     this.tcs = new TaskCompletionSource<LiveOperationResult>();
     this.status = OperationStatus.NotStarted;
     this.transferPreferences =
         BackgroundTransferHelper.GetTransferPreferences(builder.BackgroundTransferPreferences);
 }
Exemplo n.º 56
0
 internal static bool IsActive(this OperationStatus operationStatus)
 => operationStatus == OperationStatus.NotSet || operationStatus == OperationStatus.Queued || operationStatus == OperationStatus.InProgress;
        /// <summary>
        /// Performs the BackgroundDownloadOperation.
        /// </summary>
        public async Task<LiveOperationResult> ExecuteAsync()
        {
            Debug.Assert(this.status != OperationStatus.Completed, "Cannot execute on a completed operation.");

            var builder = new BackgroundDownloadRequestBuilder
            {
                AccessToken = this.accessToken,
                DownloadLocationOnDevice = this.downloadLocationOnDevice,
                RequestUri = this.requestUri,
                TransferPreferences = this.transferPreferences
            };

            this.request = builder.Build();
            var eventAdapter = new BackgroundDownloadEventAdapter(this.backgroundTransferService, this.tcs);

            Task<LiveOperationResult> task = this.progress == null ?
                                             eventAdapter.ConvertTransferStatusChangedToTask(this.request) :
                                             eventAdapter.ConvertTransferStatusChangedToTask(this.request, this.progress);

            Debug.Assert(this.tcs.Task == task, "EventAdapter returned a different task. This could affect cancel.");

            // if the request has already been cancelled do not add it to the service.
            if (this.status != OperationStatus.Cancelled)
            {
                this.backgroundTransferService.Add(this.request);
                this.status = OperationStatus.Started;
            }

            LiveOperationResult result = await task;
            this.status = OperationStatus.Completed;
            return result;
        }
Exemplo n.º 58
0
 internal static bool IsFinal(this OperationStatus operationStatus)
 => !operationStatus.IsActive();
Exemplo n.º 59
0
 internal PlayAudioResultEvent(OperationStatus status)
 {
     Status = status;
 }
        /// <summary>
        /// Gets Info for the given recovery point of the given item protected
        /// by your Recovery Services Vault as specified by the recovery point
        /// ID passed in the arguments.This is an asynchronous operation. To
        /// determine whether the backend service has finished processing the
        /// request, call the Get Protected Item Operation Result API.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. Resource group name of your recovery services vault.
        /// </param>
        /// <param name='resourceName'>
        /// Required. Name of your recovery services vault.
        /// </param>
        /// <param name='customRequestHeaders'>
        /// Optional. Request header parameters.
        /// </param>
        /// <param name='fabricName'>
        /// Optional. Fabric name of the protected item.
        /// </param>
        /// <param name='containerName'>
        /// Optional. Name of the container where the protected item belongs to.
        /// </param>
        /// <param name='protectedItemName'>
        /// Optional. Name of the protected item whose recovery points are to
        /// be fetched.
        /// </param>
        /// <param name='recoveryPointId'>
        /// Optional. ID of the recovery point whose details are to be fetched.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// A single instance of a recovery point response as returned by the
        /// service in the list recovery points call.
        /// </returns>
        public async Task <RecoveryPointResponse> GetAsync(string resourceGroupName, string resourceName, CustomRequestHeaders customRequestHeaders, string fabricName, string containerName, string protectedItemName, string recoveryPointId, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }
            if (resourceName == null)
            {
                throw new ArgumentNullException("resourceName");
            }

            // Tracing
            bool   shouldTrace  = TracingAdapter.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("resourceName", resourceName);
                tracingParameters.Add("customRequestHeaders", customRequestHeaders);
                tracingParameters.Add("fabricName", fabricName);
                tracingParameters.Add("containerName", containerName);
                tracingParameters.Add("protectedItemName", protectedItemName);
                tracingParameters.Add("recoveryPointId", recoveryPointId);
                TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
            }

            // Construct URL
            string url = "";

            url = url + "/subscriptions/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/resourceGroups/";
            url = url + Uri.EscapeDataString(resourceGroupName);
            url = url + "/providers/";
            if (this.Client.ResourceNamespace != null)
            {
                url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
            }
            url = url + "/";
            url = url + "vaults";
            url = url + "/";
            url = url + Uri.EscapeDataString(resourceName);
            url = url + "/backupFabrics/";
            if (fabricName != null)
            {
                url = url + Uri.EscapeDataString(fabricName);
            }
            url = url + "/protectionContainers/";
            if (containerName != null)
            {
                url = url + Uri.EscapeDataString(containerName);
            }
            url = url + "/protectedItems/";
            if (protectedItemName != null)
            {
                url = url + Uri.EscapeDataString(protectedItemName);
            }
            url = url + "/recoveryPoints/";
            if (recoveryPointId != null)
            {
                url = url + Uri.EscapeDataString(recoveryPointId);
            }
            List <string> queryParameters = new List <string>();

            queryParameters.Add("api-version=2016-05-01");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;

            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

            try
            {
                httpRequest            = new HttpRequestMessage();
                httpRequest.Method     = HttpMethod.Get;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers
                httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Culture);
                httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    RecoveryPointResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                        result = new RecoveryPointResponse();
                        JToken responseDoc = null;
                        if (string.IsNullOrEmpty(responseContent) == false)
                        {
                            responseDoc = JToken.Parse(responseContent);
                        }

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            RecoveryPointResource recPointInstance = new RecoveryPointResource();
                            result.RecPoint = recPointInstance;

                            JToken propertiesValue = responseDoc["properties"];
                            if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
                            {
                                string typeName = ((string)propertiesValue["objectType"]);
                                if (typeName == "IaasVMRecoveryPoint")
                                {
                                    RecoveryPoint recoveryPointInstance = new RecoveryPoint();

                                    JToken recoveryPointTypeValue = propertiesValue["recoveryPointType"];
                                    if (recoveryPointTypeValue != null && recoveryPointTypeValue.Type != JTokenType.Null)
                                    {
                                        string recoveryPointTypeInstance = ((string)recoveryPointTypeValue);
                                        recoveryPointInstance.RecoveryPointType = recoveryPointTypeInstance;
                                    }

                                    JToken recoveryPointTimeValue = propertiesValue["recoveryPointTime"];
                                    if (recoveryPointTimeValue != null && recoveryPointTimeValue.Type != JTokenType.Null)
                                    {
                                        string recoveryPointTimeInstance = ((string)recoveryPointTimeValue);
                                        recoveryPointInstance.RecoveryPointTime = recoveryPointTimeInstance;
                                    }

                                    JToken recoveryPointAdditionalInfoValue = propertiesValue["recoveryPointAdditionalInfo"];
                                    if (recoveryPointAdditionalInfoValue != null && recoveryPointAdditionalInfoValue.Type != JTokenType.Null)
                                    {
                                        string recoveryPointAdditionalInfoInstance = ((string)recoveryPointAdditionalInfoValue);
                                        recoveryPointInstance.RecoveryPointAdditionalInfo = recoveryPointAdditionalInfoInstance;
                                    }

                                    JToken sourceVMStorageTypeValue = propertiesValue["sourceVMStorageType"];
                                    if (sourceVMStorageTypeValue != null && sourceVMStorageTypeValue.Type != JTokenType.Null)
                                    {
                                        string sourceVMStorageTypeInstance = ((string)sourceVMStorageTypeValue);
                                        recoveryPointInstance.SourceVMStorageType = sourceVMStorageTypeInstance;
                                    }
                                    recPointInstance.Properties = recoveryPointInstance;
                                }
                                if (typeName == "GenericRecoveryPoint")
                                {
                                    GenericRecoveryPoint genericRecoveryPointInstance = new GenericRecoveryPoint();

                                    JToken recoveryPointTypeValue2 = propertiesValue["recoveryPointType"];
                                    if (recoveryPointTypeValue2 != null && recoveryPointTypeValue2.Type != JTokenType.Null)
                                    {
                                        string recoveryPointTypeInstance2 = ((string)recoveryPointTypeValue2);
                                        genericRecoveryPointInstance.RecoveryPointType = recoveryPointTypeInstance2;
                                    }

                                    JToken recoveryPointTimeValue2 = propertiesValue["recoveryPointTime"];
                                    if (recoveryPointTimeValue2 != null && recoveryPointTimeValue2.Type != JTokenType.Null)
                                    {
                                        string recoveryPointTimeInstance2 = ((string)recoveryPointTimeValue2);
                                        genericRecoveryPointInstance.RecoveryPointTime = recoveryPointTimeInstance2;
                                    }

                                    JToken recoveryPointAdditionalInfoValue2 = propertiesValue["recoveryPointAdditionalInfo"];
                                    if (recoveryPointAdditionalInfoValue2 != null && recoveryPointAdditionalInfoValue2.Type != JTokenType.Null)
                                    {
                                        string recoveryPointAdditionalInfoInstance2 = ((string)recoveryPointAdditionalInfoValue2);
                                        genericRecoveryPointInstance.RecoveryPointAdditionalInfo = recoveryPointAdditionalInfoInstance2;
                                    }
                                    recPointInstance.Properties = genericRecoveryPointInstance;
                                }
                            }

                            JToken idValue = responseDoc["id"];
                            if (idValue != null && idValue.Type != JTokenType.Null)
                            {
                                string idInstance = ((string)idValue);
                                recPointInstance.Id = idInstance;
                            }

                            JToken nameValue = responseDoc["name"];
                            if (nameValue != null && nameValue.Type != JTokenType.Null)
                            {
                                string nameInstance = ((string)nameValue);
                                recPointInstance.Name = nameInstance;
                            }

                            JToken typeValue = responseDoc["type"];
                            if (typeValue != null && typeValue.Type != JTokenType.Null)
                            {
                                string typeInstance = ((string)typeValue);
                                recPointInstance.Type = typeInstance;
                            }

                            JToken locationValue = responseDoc["location"];
                            if (locationValue != null && locationValue.Type != JTokenType.Null)
                            {
                                string locationInstance = ((string)locationValue);
                                recPointInstance.Location = locationInstance;
                            }

                            JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
                            if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
                            {
                                foreach (JProperty property in tagsSequenceElement)
                                {
                                    string tagsKey   = ((string)property.Name);
                                    string tagsValue = ((string)property.Value);
                                    recPointInstance.Tags.Add(tagsKey, tagsValue);
                                }
                            }

                            JToken eTagValue = responseDoc["eTag"];
                            if (eTagValue != null && eTagValue.Type != JTokenType.Null)
                            {
                                string eTagInstance = ((string)eTagValue);
                                recPointInstance.ETag = eTagInstance;
                            }

                            JToken locationValue2 = responseDoc["location"];
                            if (locationValue2 != null && locationValue2.Type != JTokenType.Null)
                            {
                                string locationInstance2 = ((string)locationValue2);
                                result.Location = locationInstance2;
                            }

                            JToken azureAsyncOperationValue = responseDoc["azureAsyncOperation"];
                            if (azureAsyncOperationValue != null && azureAsyncOperationValue.Type != JTokenType.Null)
                            {
                                string azureAsyncOperationInstance = ((string)azureAsyncOperationValue);
                                result.AzureAsyncOperation = azureAsyncOperationInstance;
                            }

                            JToken retryAfterValue = responseDoc["retryAfter"];
                            if (retryAfterValue != null && retryAfterValue.Type != JTokenType.Null)
                            {
                                string retryAfterInstance = ((string)retryAfterValue);
                                result.RetryAfter = retryAfterInstance;
                            }

                            JToken statusValue = responseDoc["Status"];
                            if (statusValue != null && statusValue.Type != JTokenType.Null)
                            {
                                OperationStatus statusInstance = ((OperationStatus)Enum.Parse(typeof(OperationStatus), ((string)statusValue), true));
                                result.Status = statusInstance;
                            }
                        }
                    }
                    result.StatusCode = statusCode;

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }