コード例 #1
0
        private void OnHandlerUnfocused(object sender, FocusEventArgs e)
        {
            decimal value = 0;

            if (decimal.TryParse(Text, out value))
            {
                if (MaximumAmount.IsNotNull() && value > MaximumAmount)
                {
                    Amount = MaximumAmount;
                    Text   = NumberType == EnumNumberType.Amount ? FormatterHelper.Format(Amount.Value) : FormatterHelper.FormatPercentage(Amount.Value);
                }
                else if (MinimumAmount.IsNotNull() && value < MinimumAmount)
                {
                    Amount = MinimumAmount;
                    Text   = NumberType == EnumNumberType.Amount ? FormatterHelper.Format(Amount.Value) : FormatterHelper.FormatPercentage(Amount.Value);
                }
                else
                {
                    Amount = value;
                    Text   = NumberType == EnumNumberType.Amount ? FormatterHelper.Format(Amount.Value) : FormatterHelper.FormatPercentage(Amount.Value);
                }
            }
            else
            {
                Text   = string.Empty;
                Amount = 0;
            }
        }
コード例 #2
0
ファイル: RoleClass.cs プロジェクト: yijutseng/cdaapi_core
        internal void writeXML(XmlWriter writer)
        {
            FormatterHelper.SerialiseDataType(recipientRoleCode, writer, "recipientRoleCode", "NPFIT:HL7:Localisation");

            // The FormatterHelper should really deal with the SET<II>, but doesn't.
            // So insted we loop around and deal with each II in turn.
            if (id != null)
            {
                foreach (II item in id)
                {
                    FormatterHelper.SerialiseDataType(item, writer, "id");
                }
            }

            FormatterHelper.SerialiseDataType(code, writer, "code");

            if (addr != null)
            {
                foreach (AD item in addr)
                {
                    FormatterHelper.SerialiseDataType(item, writer, "addr");
                }
            }

            if (telecom != null)
            {
                foreach (TEL item in telecom)
                {
                    FormatterHelper.SerialiseDataType(item, writer, "telecom");
                }
            }
        }
コード例 #3
0
        public void ConstructorMustSerializeExceptionWhenExceptionIsBeingSerialized()
        {
            NotFoundException exception = new NotFoundException("Test");

            using MemoryStream stream = new MemoryStream();
            Assert.Equal("Test", FormatterHelper.Deserialize <NotFoundException>(new BinaryFormatter(), FormatterHelper.Serialize(new BinaryFormatter(), stream, exception)).Message);
        }
コード例 #4
0
 public NumberEntry()
 {
     Text            = FormatterHelper.Format(0);
     Keyboard        = Keyboard.Numeric;
     this.Focused   += OnHandlerFocused;
     this.Unfocused += OnHandlerUnfocused;
 }
コード例 #5
0
        public new void WriteXml(XmlWriter writer)
        {
            writer.WriteStartElement("patient");

            writer.WriteAttributeString("classCode", base.ClassCode);
            writer.WriteAttributeString("determinerCode", base.DeterminerCode);

            its.TemplateSignpost(templateid + "#patientPatient", writer);

            FormatterHelper.SerialiseDataType(Name, writer, "name");
            FormatterHelper.SerialiseDataType(AdministrativeGenderCode, writer, "administrativeGenderCode");
            FormatterHelper.SerialiseDataType(birthTime, writer, "birthTime");


            if (LanguageCommunication != null)
            {
                LanguageCommunication.TemplateId = this.templateid;

                writer.WriteStartElement("languageCommunication");
                LanguageCommunication.WriteXml(writer);
                writer.WriteEndElement();
            }

            writer.WriteEndElement();
        }
コード例 #6
0
ファイル: CDAModel.cs プロジェクト: yijutseng/cdaapi_core
        public void writeXmlParentElements(XmlWriter writer)
        {
            // Add the Namespace declaration

            writer.WriteAttributeString("xmlns", "npfitlc", null, "NPFIT:HL7:Localisation");
            writer.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");

            if (Config.SchemaLocation != null)
            {
                writer.WriteAttributeString("xsi", "schemaLocation", null, "urn:hl7-org:v3 " + Config.SchemaLocation);
            }
            else
            {
                writer.WriteAttributeString("xsi", "schemaLocation", null, "urn:hl7-org:v3 ../Schemas/POCD_MT000002UK01.xsd");
            }

            // Add the root CDA attributes
            writer.WriteAttributeString("moodCode", moodCode);
            writer.WriteAttributeString("classCode", classCode);
            FormatterHelper.SerialiseDataType(typeId, writer, "typeId");
            FormatterHelper.SerialiseDataType(messageType, writer, "messageType", "NPFIT:HL7:Localisation");
            FormatterHelper.SerialiseDataType(id, writer, "id");
            FormatterHelper.SerialiseDataType(code, writer, "code");
            FormatterHelper.SerialiseDataType(title, writer, "title");
            FormatterHelper.SerialiseDataType(effectiveTime, writer, "effectiveTime");
            FormatterHelper.SerialiseDataType(confidentialityCode, writer, "confidentialityCode");
            FormatterHelper.SerialiseDataType(setId, writer, "setId");
            FormatterHelper.SerialiseDataType(versionNumber, writer, "versionNumber");
        }
コード例 #7
0
 /// <summary>
 /// Creates the public properties for each Mvvm library.
 /// </summary>
 /// <returns>The public properties.</returns>
 /// <param name="property">The property to generate.</param>
 public static PropertyDeclarationSyntax GeneratePropertiesSyntax(Property property)
 {
     return(SyntaxFactory.PropertyDeclaration(SyntaxFactory.ParseTypeName(property.Type.FindType()), property.Name)
            .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
            .AddAccessorListAccessors(
                SyntaxFactory.AccessorDeclaration(
                    SyntaxKind.GetAccessorDeclaration)
                .WithExpressionBody(
                    SyntaxFactory.ArrowExpressionClause(
                        SyntaxFactory.MemberAccessExpression(
                            SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.ThisExpression(), SyntaxFactory.IdentifierName(property.Name.ToCamelCase()))))
                .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)),
                SyntaxFactory.AccessorDeclaration(
                    SyntaxKind.SetAccessorDeclaration)
                .WithExpressionBody(
                    SyntaxFactory.ArrowExpressionClause(
                        SyntaxFactory.InvocationExpression(
                            SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.ThisExpression(), SyntaxFactory.IdentifierName("SetProperty")))
                        .WithArgumentList(SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList <ArgumentSyntax>(
                                                                         new SyntaxNodeOrToken[]
     {
         SyntaxFactory.Argument(SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.ThisExpression(), SyntaxFactory.IdentifierName(property.Name.ToCamelCase())))
         .WithRefKindKeyword(SyntaxFactory.Token(SyntaxKind.RefKeyword)), SyntaxFactory.Token(SyntaxKind.CommaToken), SyntaxFactory.Argument(SyntaxFactory.IdentifierName("value"))
     })))))
                .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)))
            .WithModifiers(FormatterHelper.GenerateComment(property.Comment)));
 }
コード例 #8
0
        /// <summary>
        ///     Escreve um texto formatado.
        /// </summary>
        /// <param name="format">Formato</param>
        /// <param name="args">Argumentos.</param>
        /// <returns>Auto referência.</returns>
        public IOutput Write(string format, params object[] args)
        {
            var text = string.Format(format, args);

            FormatterHelper.Output(text, WriteNow);

            return(this);
        }
コード例 #9
0
 public ObjectReader(Stream serializationStream, ISurrogateSelector surrogateSelector, StreamingContext context, FormatterHelper fh, SerializationBinder binder)
     : this()
 {
     this.stream     = serializationStream ?? throw new ArgumentNullException(nameof(serializationStream));
     this.surrogates = surrogateSelector;
     this.context    = context;
     this.fh         = fh;
     this.binder     = binder;
 }
コード例 #10
0
        public int Serialize(ref byte[] bytes, int offset, global::MagicSpritz.IAction value, global::MessagePack.IFormatterResolver formatterResolver)
        {
            if (value == null)
            {
                return(global::MessagePack.MessagePackBinary.WriteNil(ref bytes, offset));
            }

            return(FormatterHelper.Serialize(ref bytes, offset, value, formatterResolver));;
        }
コード例 #11
0
ファイル: ActClass.cs プロジェクト: benbunCoder/cdaapi_core
        internal void WriteXML(XmlWriter writer)
        {
            writer.WriteAttributeString("classCode", classCode);
            writer.WriteAttributeString("moodCode", moodCode);

            // Format the template Id if it is present
            FormatterHelper.SerialiseDataType(templateId, writer, "templateId");

            // The FormatterHelper should really deal with the SET<II>, but doesn't.
            // So instead we loop around and deal with each II in turn.
            if (id != null)
            {
                foreach (II item in id)
                {
                    FormatterHelper.SerialiseDataType(item, writer, "id");
                }
            }

            FormatterHelper.SerialiseDataType(code, writer, "code");
            FormatterHelper.SerialiseDataType(effectiveTime, writer, "effectiveTime");
            FormatterHelper.SerialiseDataType(dischargeDispositionCode, writer, "dischargeDispositionCode");
            FormatterHelper.SerialiseDataType(setId, writer, "setId");
            FormatterHelper.SerialiseDataType(versionNumber, writer, "versionNumber");
            FormatterHelper.SerialiseDataType(statusCode, writer, "statusCode");

            if ((valueType != null) && (valueType != string.Empty))
            {
                if (valueType == "ANY.NHS.URL")
                {
                    writer.WriteStartElement("value");
                    writer.WriteAttributeString("type", "http://www.w3.org/2001/XMLSchema-instance", valueType);
                    writer.WriteAttributeString("value", valueString);
                    writer.WriteEndElement();
                }

                if (valueType == "ED.NHS.ObservationMedia")
                {
                    writer.WriteStartElement("value");
                    writer.WriteAttributeString("type", "http://www.w3.org/2001/XMLSchema-instance", valueType);
                    writer.WriteAttributeString("representation", valueEDRepresentation);
                    writer.WriteAttributeString("mediaType", valueEDMediaType);
                    writer.WriteString(valueED);
                    writer.WriteEndElement();
                }

                if (valueType == "ED.NHS.NHS111Attachment")
                {
                    writer.WriteStartElement("value");
                    writer.WriteAttributeString("type", "http://www.w3.org/2001/XMLSchema-instance", valueType);
                    writer.WriteAttributeString("representation", valueEDRepresentation);
                    writer.WriteAttributeString("mediaType", valueEDMediaType);
                    writer.WriteString(valueED);
                    writer.WriteEndElement();
                }
            }
        }
コード例 #12
0
        public global::MagicSpritz.IAction Deserialize(byte[] bytes, int offset, global::MessagePack.IFormatterResolver formatterResolver, out int readSize)
        {
            if (global::MessagePack.MessagePackBinary.IsNil(bytes, offset))
            {
                readSize = 1;
                return(null);
            }

            return(FormatterHelper.Deserialize(bytes, offset, formatterResolver, out readSize));
        }
コード例 #13
0
        public string[] Busca(string filter)
        {
            var query     = _uow.MedicoRepository.GetAll();
            var resultDto = query.Select(x => new SuggestionDto
            {
                View = x.Id + "-" + x.Nome.Trim() + " " + x.Sobrenome.Trim()
            })
                            .Where(x => x.View.Contains(filter))
                            .Take(10).ToList();

            return(FormatterHelper.Suggestion(resultDto));
        }
コード例 #14
0
 internal ObjectWriter(ISurrogateSelector selector, StreamingContext context, FormatterHelper formatterEnums, SerializationBinder binder)
 {
     this._surrogates         = selector;
     this._context            = context;
     this._binder             = binder;
     this._formatterEnums     = formatterEnums;
     this.ObjectManager       = new SerializationObjectManager(context);
     this._idGenerator        = new ObjectIDGenerator();
     this._objectQueue        = new Queue <object>();
     this._formatterConverter = new FormatterConverter();
     this._serObjectInfoInit  = new SerializationObjectInfo();
 }
コード例 #15
0
        public void WriteXml(XmlWriter writer)
        {
            string templateId   = "COCD_TP146246GB01";
            string templateText = "Section1";

            writer.WriteStartElement("section");
            writer.WriteAttributeString("classCode", "DOCSECT");
            writer.WriteAttributeString("moodCode", "EVN");

            its.TemplateSignpost(templateId + "#" + templateText, writer);

            if (this.Id != null)
            {
                writer.WriteStartElement("id");
                writer.WriteAttributeString("root", this.Id);
                writer.WriteEndElement();  // section/id
            }
            if (this.code != null)
            {
                FormatterHelper.SerialiseDataType(this.code, writer, "code");
            }


            if (this.Title != null)
            {
                writer.WriteStartElement("title");
                writer.WriteValue(this.Title);
                writer.WriteEndElement();  // section/title
            }

            if (this.Text != null)
            {
                writer.WriteStartElement("text");
                writer.WriteRaw(this.Text);
                writer.WriteEndElement();  // section/text
            }

            WriteXMLAuthor(writer);

            int level = 1;

            foreach (TextSubSection subitem in this.section)
            {
                templateText = "component" + level.ToString();
                writer.WriteStartElement("component");
                writer.WriteAttributeString("typeCode", "COMP");
                writer.WriteAttributeString("contextConductionInd", "true");
                its.TemplateSignpost(templateId + "#" + templateText, writer);
                WriteXmlTextTemplate(subitem, level + 1, writer);
                writer.WriteEndElement();
            }
            writer.WriteEndElement();  // section
        }
コード例 #16
0
        internal void WriteXml(XmlWriter writer)
        {
            writer.WriteStartAttribute("classCode");
            writer.WriteValue(classCode);
            writer.WriteEndAttribute();

            writer.WriteStartAttribute("determinerCode");
            writer.WriteValue(determinerCode);
            writer.WriteEndAttribute();

            its.TemplateSignpost(templateId + "#" + templateText, writer);

            // The FormatterHelper should really deal with the SET<II>, but doesn't.
            // So insted we loop around and deal with each II in turn.
            if (id != null)
            {
                foreach (II item in id)
                {
                    FormatterHelper.SerialiseDataType(item, writer, "id");
                }
            }

            if (name != null)
            {
                foreach (PN item in name)
                {
                    FormatterHelper.SerialiseDataType(item, writer, "name");
                }
            }

            if (telecom != null)
            {
                foreach (TEL item in telecom)
                {
                    FormatterHelper.SerialiseDataType(item, writer, "telecom");
                }
            }

            if (addr != null)
            {
                foreach (AD item in addr)
                {
                    FormatterHelper.SerialiseDataType(item, writer, "addr");
                }
            }

            FormatterHelper.SerialiseDataType(AdministrativeGenderCode, writer, "administrativeGenderCode");
            FormatterHelper.SerialiseDataType(birthTime, writer, "birthTime");

            FormatterHelper.SerialiseDataType(standardIndustryClassCode, writer, "standardIndustryClassCode");
            FormatterHelper.SerialiseDataType(manufacturerModelName, writer, "manufacturerModelName");
            FormatterHelper.SerialiseDataType(softwareName, writer, "softwareName");
        }
コード例 #17
0
    private void ReceiveAudio(byte[] bytes)
    {
        //反序列化
        M_AudioClip mac = (M_AudioClip)FormatterHelper.Deserialize(bytes);
        //生成新的声音片段
        AudioClip ac = AudioClip.Create("s", mac.length, 1, mac.frequency, false);

        //float数组转audioclip
        ac.SetData(mac.audioData, 0);
        //播放
        audioSource.clip = ac;
        audioSource.Play();
    }
コード例 #18
0
        public void WriteXml(XmlWriter writer)
        {
            writer.WriteAttributeString("typeCode", typeCode);
            writer.WriteAttributeString("contextControlCode", contextControlCode);

            its.TemplateLookAhead(Role.getTemplateID() + "#" + Role.getTemplateText(), writer);

            FormatterHelper.SerialiseDataType(functionCode, writer, "functionCode");
            FormatterHelper.SerialiseDataType(time, writer, "time");

            writer.WriteStartElement("assignedEntity");
            Role.WriteXml(writer);
            writer.WriteEndElement();
        }
コード例 #19
0
 public void Limit(DataTable dataTable, Action <DataRow[]> Callback)
 {
     Monitor.Enter(FlowControl.syncLock);
     try
     {
         if (dataTable != null && Callback != null)
         {
             decimal        _mSize       = this._setSize;
             DataTable      newDataTable = dataTable.Clone();
             List <DataRow> rows         = new List <DataRow>();
             Stopwatch      stopwatch    = new Stopwatch();
             stopwatch.Start();
             Array.ForEach <DataRow>(dataTable.Select(), delegate(DataRow dr)
             {
                 newDataTable.Clear();
                 newDataTable.ImportRow(dr);
                 rows.Add(dr);
                 try
                 {
                     byte[] array    = FormatterHelper.Serialize(newDataTable);
                     decimal d       = array.Length / this._Kbyte;
                     _mSize         -= d;
                     this._netBytes += d;
                 }
                 catch
                 {
                 }
                 if (_mSize < 0m)
                 {
                     if (stopwatch.Elapsed.Milliseconds < 1000)
                     {
                         Thread.Sleep(1000 - stopwatch.Elapsed.Milliseconds);
                     }
                     Callback(rows.ToArray());
                     rows.Clear();
                     stopwatch.Reset();
                     stopwatch.Start();
                     _mSize         = this._setSize;
                     this._netBytes = 0m;
                 }
             });
             Callback(rows.ToArray());
             this._netBytes = 0m;
         }
     }
     finally
     {
         Monitor.Exit(FlowControl.syncLock);
     }
 }
コード例 #20
0
        private static void CreateSerializeMethod(TypeDefinition wrapper, ModuleDefinition module, PropertyDefinition valuesField, IReadOnlyList <IExposedProperty> properties)
        {
            MethodDefinition m = wrapper.AddMethod("Serialize",
                                                   MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual);

            ParameterDefinition paraId      = m.AddParameter <int>("id");
            ParameterDefinition paraWriter  = m.AddParameter(module.GetTypeReference(typeof(MessagePackWriter).MakeByRefType()), "writer");
            ParameterDefinition paraOptions = m.AddParameter <MessagePackSerializerOptions>("options");

            ILProcessor il = m.BeginEdit();

            MethodReference getItem = module.GetMethod <Dictionary <int, object> >("get_Item").MakeHostInstanceGeneric(module.GetTypeReference(typeof(Dictionary <,>)).MakeGenericInstanceType(module.GetTypeReference <int>(), module.GetTypeReference <object>()));

            il.EmitIfElse(properties, (property, index, next, body, fill) =>
            {
                // if (id == <id>)
                fill.Add(ILHelper.Ldarg(il, paraId));
                if (property.Id == 0)
                {
                    fill.Add(Instruction.Create(OpCodes.Brtrue, next));
                }
                else
                {
                    fill.Add(ILHelper.Int(property.Id));
                    fill.Add(Instruction.Create(OpCodes.Bne_Un, next));
                }
            }, (property, index, next, fill) =>
            {
                // writer.Write((Type) values[id])
                // options.Resolver.GetFormatterWithVerify<Type>().Serialize(ref writer, (Type) values[id], options)
                fill.AddRange(FormatterHelper.GetWriteValue(property.FieldTypeComponentAware, module, il, paraWriter, paraOptions, list =>
                {
                    list.Add(Instruction.Create(OpCodes.Call, valuesField.GetMethod));
                    list.Add(ILHelper.Int(property.Id));
                    list.Add(Instruction.Create(OpCodes.Callvirt, getItem));
                    if (property.IsValueType)
                    {
                        list.Add(Instruction.Create(OpCodes.Unbox_Any, property.FieldTypeComponentAware));
                    }
                }));

                if (index <= properties.Count - 1)
                {
                    fill.Add(Instruction.Create(OpCodes.Ret));
                }
            }, fill => { fill.Add(Instruction.Create(OpCodes.Ret)); });

            m.EndEdit();
        }
コード例 #21
0
        protected override async Task FixAllAsync(
            Document document, ImmutableArray <Diagnostic> diagnostics, SyntaxEditor editor,
            CancellationToken cancellationToken)
        {
            var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            // Defer to our callback to actually make the edits for each diagnostic. In turn, it
            // will return 'true' if it made a multi-line conditional expression. In that case,
            // we'll need to explicitly format this node so we can get our special multi-line
            // formatting in VB and C#.
            var nestedEditor = new SyntaxEditor(root, document.Project.Solution.Workspace);

            foreach (var diagnostic in diagnostics)
            {
                await FixOneAsync(
                    document, diagnostic, nestedEditor, cancellationToken).ConfigureAwait(false);
            }

            var changedRoot = nestedEditor.GetChangedRoot();

            // Get the language specific rule for formatting this construct and call into the
            // formatted to explicitly format things.  Note: all we will format is the new
            // conditional expression as that's the only node that has the appropriate
            // annotation on it.
            var rules = new List <AbstractFormattingRule> {
                GetMultiLineFormattingRule()
            };

            var options = document.Project.AnalyzerOptions.GetAnalyzerOptionSet(root.SyntaxTree, cancellationToken);

#if CODE_STYLE
            var formattedRoot = FormatterHelper.Format(changedRoot,
                                                       GetSyntaxFormattingService(),
                                                       SpecializedFormattingAnnotation,
                                                       options,
                                                       rules, cancellationToken);
#else
            var formattedRoot = Formatter.Format(changedRoot,
                                                 SpecializedFormattingAnnotation,
                                                 document.Project.Solution.Workspace,
                                                 options,
                                                 rules, cancellationToken);
#endif
            changedRoot = formattedRoot;

            editor.ReplaceNode(root, changedRoot);
        }
コード例 #22
0
 public void Limit <TEntity>(List <TEntity> entities, Action <TEntity[]> Callback) where TEntity : class, new()
 {
     Monitor.Enter(FlowControl.syncLock);
     try
     {
         if (entities != null && Callback != null && entities.Count != 0)
         {
             decimal        _mSize      = this._setSize;
             List <TEntity> newEntities = new List <TEntity>();
             Stopwatch      stopwatch   = new Stopwatch();
             stopwatch.Start();
             Array.ForEach <TEntity>(entities.ToArray(), delegate(TEntity entity)
             {
                 newEntities.Add(entity);
                 try
                 {
                     byte[] array    = FormatterHelper.Serialize(entity);
                     decimal d       = array.Length / this._Kbyte;
                     _mSize         -= d;
                     this._netBytes += d;
                 }
                 catch
                 {
                 }
                 if (_mSize < 0m)
                 {
                     if (stopwatch.Elapsed.Milliseconds < 1000)
                     {
                         Thread.Sleep(1000 - stopwatch.Elapsed.Milliseconds);
                     }
                     Callback(newEntities.ToArray());
                     newEntities.Clear();
                     stopwatch.Reset();
                     stopwatch.Start();
                     _mSize         = this._setSize;
                     this._netBytes = 0m;
                 }
             });
             Callback(newEntities.ToArray());
             this._netBytes = 0m;
         }
     }
     finally
     {
         Monitor.Exit(FlowControl.syncLock);
     }
 }
コード例 #23
0
        public void WriteXml(XmlWriter writer)
        {
            writer.WriteAttributeString("typeCode", typeCode);
            writer.WriteAttributeString("contextControlCode", contextControlCode);

            if (templateId != null)
            {
                its.TemplateSignpost(templateId.Extension + "#subject", writer);
            }
            its.TemplateLookAhead(Role.getTemplateID() + "#" + Role.getTemplateText(), writer);

            FormatterHelper.SerialiseDataType(targetAwarenessCode, writer, "awarenessCode");

            writer.WriteStartElement("relatedSubject");
            Role.WriteXml(writer);
            writer.WriteEndElement();
        }
コード例 #24
0
    public void OnPress(bool isPress)
    {
        if (isPress)//点击
        {
            messageLabel.text = "";
            Microphone.End(null);                                        //关闭录音.
            audioClip = Microphone.Start(null, false, 10, samplingRate); //开始录音
        }
        else//弹起按钮
        {
            int audioLength;//录音的长度,单位为秒,ui上可能需要显示
            int lastPos = Microphone.GetPosition(null);
            if (Microphone.IsRecording(null))
            {
                audioLength = lastPos / samplingRate;
            }
            else
            {
                audioLength = 10;
            }

            Microphone.End(null);//此时录音结束,audioClip可以播放

            if (audioLength < 1.0f)
            {
                messageLabel.text = "说话时间太短";
                return;
            } //录音小于1秒不处理

            //将声音转成float数组
            float[] samples = new float[audioLength * samplingRate];
            audioClip.GetData(samples, 0);
            int i = 0;
            while (i < samples.Length)
            {
                samples[i] = samples[i] * 0.5F;
                ++i;
            }

            //实例化M_AudioClip类 传入声音采样率 声道 音频 和float数组
            M_AudioClip mac = new M_AudioClip(audioLength * samplingRate, audioClip.frequency, samples);

            //向rpc发送M_AudioClip序列化后的byte数组
            nv.RPC("ReceiveAudio", RPCMode.Others, FormatterHelper.Serialize(mac));
        }
    }
コード例 #25
0
        private static void CreateDeserializeMethod(TypeDefinition wrapper, ModuleDefinition module, IReadOnlyList <IExposedProperty> properties)
        {
            MethodDefinition m = wrapper.AddMethod <object>("Deserialize",
                                                            MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual);

            ParameterDefinition paraId      = m.AddParameter <int>("id");
            ParameterDefinition paraReader  = m.AddParameter(module.GetTypeReference(typeof(MessagePackReader).MakeByRefType()), "reader");
            ParameterDefinition paraOptions = m.AddParameter <MessagePackSerializerOptions>("options");

            ILProcessor il = m.BeginEdit();

            il.EmitIfElse(properties, (property, index, next, body, fill) =>
            {
                // if (id == <id>)
                fill.Add(ILHelper.Ldarg(il, paraId));
                if (property.Id == 0)
                {
                    fill.Add(Instruction.Create(OpCodes.Brtrue, next));
                }
                else
                {
                    fill.Add(ILHelper.Int(property.Id));
                    fill.Add(Instruction.Create(OpCodes.Bne_Un, next));
                }
            }, (property, index, next, fill) =>
            {
                // return reader.Read()
                // return options.Resolver.GetFormatterWithVerify<Type>().Deserialize(ref reader, options)

                fill.AddRange(FormatterHelper.GetReadValue(property.FieldTypeComponentAware, module, il, paraReader, paraOptions));
                if (property.IsValueType)
                {
                    fill.Add(Instruction.Create(OpCodes.Box, property.FieldTypeComponentAware));
                }

                fill.Add(Instruction.Create(OpCodes.Ret));
            }, fill =>
            {
                // return null
                fill.Add(Instruction.Create(OpCodes.Ldnull));
                fill.Add(Instruction.Create(OpCodes.Ret));
            });

            m.EndEdit();
        }
コード例 #26
0
        public void WriteXml(XmlWriter writer)
        {
            writer.WriteStartElement("performer");
            writer.WriteAttributeString("typeCode", typeCode);

            if (role != null)
            {
                its.TemplateSignpost(templateId + "#" + templateText, writer);
                its.TemplateLookAhead(role.getTemplateID() + "#" + role.getTemplateText(), writer);
                FormatterHelper.SerialiseDataType(functionCode, writer, "functionCode");
                FormatterHelper.SerialiseDataType(time, writer, "time");

                writer.WriteStartElement("assignedEntity");
                role.WriteXml(writer);
                writer.WriteEndElement();
            }
            writer.WriteEndElement();
        }
コード例 #27
0
 private byte[] ToQueryMsg()
 {
     byte[] serverBuffer = null;
     try
     {
         DataTable      dt       = new MessageService().GetMessageToSend().Tables[0];;
         NewsCollection newsList = new NewsCollection();
         for (int i = 0; i < dt.Rows.Count; i++)
         {
             newsList.Add(new NewsMessage(dt.Rows[i]["Id"].ToString(), dt.Rows[i]["Theme"].ToString()));
         }
         P2P.WellKnown.S2C.GetMsgsResponseMessage msgListReponse = new P2P.WellKnown.S2C.GetMsgsResponseMessage(newsList);
         serverBuffer = FormatterHelper.Serialize(msgListReponse);
     }
     catch
     {
     }
     return(serverBuffer);
 }
コード例 #28
0
        public void WriteXml(XmlWriter writer)
        {
            writer.WriteAttributeString("typeCode", typeCode);
            writer.WriteAttributeString("contextControlCode", contextControlCode);

            if (templateId != null)
            {
                its.TemplateSignpost(base.templateId.Extension + "#author", writer);
            }

            its.TemplateLookAhead(Role.getTemplateID() + "#" + Role.getTemplateText(), writer);

            FormatterHelper.SerialiseDataType(functionCode, writer, "functionCode");
            FormatterHelper.SerialiseDataType(time, writer, "time");

            writer.WriteStartElement("assignedAuthor");
            Role.WriteXml(writer);
            writer.WriteEndElement();
        }
コード例 #29
0
        public void WriteXml(XmlWriter writer)
        {
            writer.WriteAttributeString("typeCode", base.typeCode);

            its.TemplateLookAhead(Role.getTemplateID() + "#" + Role.getTemplateText(), writer);

            FormatterHelper.SerialiseDataType(time, writer, "time");

            //
            // The follow attrbute is fixed, so this is hardcoded as below.
            //
            writer.WriteStartElement("signatureCode");
            writer.WriteAttributeString("nullFlavor", "NA");
            writer.WriteEndElement();

            writer.WriteStartElement("assignedEntity");
            Role.WriteXml(writer);
            writer.WriteEndElement();
        }
コード例 #30
0
 void m_WebSocketServer_NewDataReceived(WebSocketSession session, byte[] value)
 {
     try
     {
         var data = FormatterHelper.BytesToObject(value) as object[];
         if (data == null)
         {
             return;
         }
         if (data[0].ToString() == "Login")
         {
             var ResponseData = FormatterHelper.ObjectToBytes
                                    (new object[] { "LoginResult", "Sucess" });
             session.Send(ResponseData, 0, ResponseData.Length);
         }
     }
     catch (Exception ex)
     {
     }
 }