Ejemplo n.º 1
0
        /// <summary>
        /// Change the format of the current node.
        /// </summary>
        /// <remarks>
        /// <para>If the previous format was a container, this method will
        /// remove the children of the node.
        /// If the new format is a container, this method will add the format
        /// children to the node.</para>
        /// </remarks>
        /// <param name="newFormat">The new format to assign.</param>
        /// <param name="disposePreviousFormat">
        /// If <see langword="true" /> the method will dispose the previous
        /// format.
        /// </param>
        public void ChangeFormat(IFormat newFormat, bool disposePreviousFormat = true)
        {
            if (Disposed)
            {
                throw new ObjectDisposedException(nameof(Node));
            }

            // If it was a container, clean children
            if (IsContainer)
            {
                RemoveChildren();
            }

            if (disposePreviousFormat)
            {
                (Format as IDisposable)?.Dispose();
            }

            Format = newFormat;

            // If now it's a container, add its children
            if (IsContainer)
            {
                AddContainerChildren();
            }
        }
Ejemplo n.º 2
0
        /// <inheritdoc />
        public SpanContext Extract <TCarrier>(IFormat <TCarrier> format, TCarrier carrier)
        {
            if (carrier is ITextMap text)
            {
                ulong? traceId         = null;
                string OriginalTraceId = null;
                ulong? spanId          = null;

                foreach (var entry in text)
                {
                    if (TraceIdName.Equals(entry.Key, StringComparison.OrdinalIgnoreCase))
                    {
                        traceId         = ParseTraceId(entry.Value);
                        OriginalTraceId = entry.Value;
                    }
                    else if (SpanIdName.Equals(entry.Key, StringComparison.OrdinalIgnoreCase))
                    {
                        spanId = Convert.ToUInt64(entry.Value, 16);
                    }
                }

                if (traceId.HasValue && spanId.HasValue)
                {
                    return(new SpanContext(traceId.Value, spanId.Value, originalTraceId: OriginalTraceId));
                }
            }

            return(null);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Sets the dst complex field from the src complex field by knowing it's type.
        /// </summary>
        /// <param name="complexObj">The complex object.</param>
        /// <param name="name">The name of the field.</param>
        /// <param name="src">The source format.</param>
        /// <param name="dst">The destination format.</param>
        /// <returns>True if the type was setted up, otherwise false.</returns>
        private static bool SetComplexType(ListObjectDefine complexObj, string name, IFormat src, IFormat dst, int k, int c)
        {
            foreach (var obj in complexObj.list)
            {
                string newName = GetNewName(name + obj.name, k, c);

                if (obj.type == "string")
                {
                    SetStringType(obj.count, newName, src, dst);
                    continue;
                }

                for (int i = 0; i < obj.count; i++)
                {
                    if (obj.count > 1)
                    {
                        newName += "_" + i.ToString();
                    }

                    if (!SetBaseType(obj.type, newName, src, dst))
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
Ejemplo n.º 4
0
        public void AddCodec <TCarrier>(IFormat <TCarrier> format, IInjector injector, IExtractor extractor)
        {
            var formatString = format.ToString();

            _injectors[formatString]  = injector;
            _extractors[formatString] = extractor;
        }
Ejemplo n.º 5
0
 public minicostformatitem(IList <IFormat> formats, IFormat format, int cost)
 {
     Formats = new List <IFormat>();
     Formats.AddRange(formats);
     Formats.Add(format);
     Cost = cost;
 }
        public XmlDocument parseToInputFromMathModel(IExpressionType model)
        {
            XmlParser xp = new XmlParser();
            IFormat   nf = xp.UnitImportFromModelToFormat((IUnit)model, 0);

            return(xp.ParseFormatToInput(nf));
        }
Ejemplo n.º 7
0
        public void RemoveFormat(IFormat format)
        {
            List <IFormat> formats = new List <IFormat>(Formats);

            if (!formats.Contains(format))
            {
                return;
            }

            formats.Remove(format);

            string[] streams = GetStreamNames();
            foreach (string name in streams)
            {
                string[] parts = name.Split('.');
                int      id;
                if (int.TryParse(parts[0], out id))
                {
                    if (id == format.ID)
                    {
                        DeleteStream(name);
                    }
                }
            }

            // Song.Data.SetArray<int>("FormatIDs", formats.Select(f => f.ID).ToArray());
        }
Ejemplo n.º 8
0
        public bool WriteBlockFromBuffer(byte[] buffer, int offset, IFormat format)
        {
            double amp         = Math.Pow(2, (format.BytesPerSample * 8) - 1) - 1;
            int    blockLength = format.Channels * format.BytesPerSample;

            if (buffer.Length - offset < blockLength)
            {
                return(false);
            }

            for (int c = 0; c < format.Channels; c++)
            {
                //byte[] bytes = new byte[format.BytesPerSample];
                //for (int b = 0; b < bytes.Length; b++)
                //{
                //    bytes[b] = buffer[offset + (c * format.BytesPerSample) + b];
                //}

                if (format.BytesPerSample == 4)
                {
                    Int32 value = BitConverter.ToInt32(buffer, offset + (c * format.BytesPerSample));
                    Block[c] = Convert.ToDouble(value) / amp;
                }
                else if (format.BytesPerSample == 2)
                {
                    Int16 value = BitConverter.ToInt16(buffer, offset + (c * format.BytesPerSample));
                    Block[c] = Convert.ToDouble(value) / amp;
                }
            }

            return(true);
        }
Ejemplo n.º 9
0
        public override void Remux(IFormat format, FormatData data, FormatData destination, ProgressIndicator progress)
        {
            if (!(format is AudioFormatOgg))
            {
                throw new FormatException();
            }

            bool musttranscode = AudioFormatOgg.Instance.GetAudioStreams(data).Count > 1;

            if (musttranscode)               // Remuxing isn't possible with more than one audio stream
            {
                Platform.TranscodeOnly(format, data, AudioFormatMogg.Instance, destination, progress);
                return;
            }

            Util.StreamCopy(destination.AddStream(this, FormatName), AudioFormatOgg.Instance.GetFormatStream(data));

            CryptedMoggStream audio = new CryptedMoggStream(destination.AddStream(this, AudioName));

            audio.WriteHeader();
            Util.StreamCopy(audio, AudioFormatOgg.Instance.GetAudioStream(data));

            destination.CloseStream(this, AudioName);
            destination.CloseStream(this, FormatName);
        }
Ejemplo n.º 10
0
 public void ApplyFormatToCell(IXLWorkbook wb, IXLCell cell, IFormat format)
 {
     if (format is ClosedXmlFormat closedXmlFormat)
     {
         closedXmlFormat.Stylize.Invoke(cell.Style);
     }
 }
Ejemplo n.º 11
0
        /// <summary>
        /// Get the default (automatically discovered) configuration for a certain format.
        /// </summary>
        /// <param name="format">The format.</param>
        /// <returns>The default (auto discovered) configuration.</returns>
        public Configuration GetDefaultConfig(IFormat format)
        {
            Dictionary <Type, IPrimitiveSerializer> primitiveConfig = new Dictionary <Type, IPrimitiveSerializer>();

            if (PrimitiveSerializers.ContainsKey(format.SerialDataType))
            {
                foreach (IPrimitiveSerializer f in PrimitiveSerializers[format.SerialDataType])
                {
                    if (!primitiveConfig.ContainsKey(f.SourceType))
                    {
                        primitiveConfig.Add(f.SourceType, (IPrimitiveSerializer)Activator.CreateInstance(f.GetType()));
                    }
                }
            }
            else
            {
                Logger.Warn(String.Format(
                                "No primitive serializers found for format {0} with serial data type {1}",
                                format.GetType().AssemblyQualifiedName,
                                format.SerialDataType.AssemblyQualifiedName));
            }
            return(new Configuration(
                       format,
                       primitiveConfig.Values,
                       CompositeSerializers.Where((d) => d.Priority > 0).Select(d => (ICompositeSerializer)Activator.CreateInstance(d.GetType()))));
        }
Ejemplo n.º 12
0
        public LocatorValidationResult Fetch(ParameterizedDatumLocator datumLocator)
        {
            Navigation navigation = null;
            IDocument  doc        = null;
            IFormat    format     = null;

            try
            {
                var fetchPolicy = new EvaluatorPolicy(datumLocator.Parameters);
                navigation = fetchPolicy.GetNavigation(datumLocator.Site);

                doc = myWebScrapSC.GetDocument(navigation);
                if (doc == null)
                {
                    return(new LocatorValidationResult(null, datumLocator, navigation, null, null));
                }

                format = fetchPolicy.GetFormat(datumLocator.Site);
                var result = fetchPolicy.ApplyPreprocessing(doc.ExtractTable(format));

                var resultPolicy = new FirstNonNullPolicy();
                resultPolicy.Validate(datumLocator.Site, result);

                return(new LocatorValidationResult(resultPolicy.ResultTable, datumLocator, navigation, doc.Location, format));
            }
            catch (Exception ex)
            {
                var result = new LocatorValidationResult(null, datumLocator, navigation, doc != null ? doc.Location : null, format);
                result.ErrorMessage = ex.Message;
                return(result);
            }
        }
Ejemplo n.º 13
0
        public static IFormat getType(string type_)
        {
            IFormat type = null;

            try
            {
                switch (type_.ToLower())
                {
                case "csv":
                    type = new CSV();
                    break;

                case "xls":
                    type = new Xls();
                    break;

                case "xlsx":
                    type = new Xlsx();
                    break;
                    // Expand list here
                }
            }
            catch (Exception)
            {
                throw new Exception("Incorrect file type");
            }

            return(type);
        }
Ejemplo n.º 14
0
        /// <inheritdoc />
        public SpanContext Extract <TCarrier>(IFormat <TCarrier> format, TCarrier carrier)
        {
            string traceId = null;
            string spanId  = null;
            var    baggage = new Baggage();

            if (carrier is ITextMap text)
            {
                foreach (var entry in text)
                {
                    if (Keys.TraceId.Equals(entry.Key))
                    {
                        traceId = entry.Value;
                    }
                    else if (Keys.SpanId.Equals(entry.Key))
                    {
                        spanId = entry.Value;
                    }
                    else if (entry.Key.StartsWith(Keys.BaggagePrefix))
                    {
                        var key = entry.Key.Substring(Keys.BaggagePrefix.Length);
                        baggage.Set(key, entry.Value);
                    }
                }
            }

            if (!string.IsNullOrEmpty(traceId) && !string.IsNullOrEmpty(spanId))
            {
                return(new SpanContext(traceId, spanId, baggage));
            }

            return(null);
        }
Ejemplo n.º 15
0
Archivo: Site.cs Proyecto: bg0jr/Maui
 public Site( string name, Navigation navi, IFormat format, DataContent content )
 {
     Name = name;
     Navigation = navi;
     Format = format;
     Content = content;
 }
Ejemplo n.º 16
0
        public void Inject <TCarrier>(ISpanContext spanContext, IFormat <TCarrier> format, TCarrier carrier)
        {
            // TODO only ITextMap is supported currently
            var injector = new TextMapInjector(_spanContextKey);

            injector.Inject(spanContext, (ITextMap)carrier);
        }
Ejemplo n.º 17
0
        /// <inheritdoc />
        public SpanContext Extract <TCarrier>(IFormat <TCarrier> format, TCarrier carrier)
        {
            _logger.Trace($"Extracting {format.GetType()} from {carrier.GetType()}");
            string traceId = null;
            string spanId  = null;
            var    baggage = new Baggage();

            if (carrier is ITextMap text)
            {
                foreach (var entry in text)
                {
                    if (Keys.TraceId.Equals(entry.Key))
                    {
                        traceId = Convert.ToUInt64(entry.Value, 16).ToString();
                    }
                    else if (Keys.SpanId.Equals(entry.Key))
                    {
                        spanId = Convert.ToUInt64(entry.Value, 16).ToString();
                    }
                    else if (entry.Key.StartsWith(Keys.BaggagePrefix))
                    {
                        var key = entry.Key.Substring(Keys.BaggagePrefix.Length);
                        baggage.Set(key, entry.Value);
                    }
                }
            }

            if (!string.IsNullOrEmpty(traceId) && !string.IsNullOrEmpty(spanId))
            {
                _logger.Trace($"Existing trace/spanID found, returning SpanContext.");
                return(new SpanContext(traceId, spanId, baggage));
            }

            return(null);
        }
Ejemplo n.º 18
0
        /// <inheritdoc />
        public void Inject <TCarrier>(SpanContext context, IFormat <TCarrier> format, TCarrier carrier)
        {
            ulong traceId;
            ulong spanId;

            try
            {
                traceId = Convert.ToUInt64(context.TraceId);
            }
            catch (FormatException)
            {
                traceId = Convert.ToUInt64(context.TraceId, 16);
            }

            try
            {
                spanId = Convert.ToUInt64(context.SpanId);
            }
            catch (FormatException)
            {
                spanId = Convert.ToUInt64(context.SpanId, 16);
            }

            if (carrier is ITextMap text)
            {
                text.Set(TraceIdName, traceId.ToString("X"));
                text.Set(SpanIdName, spanId.ToString("X"));
                text.Set(SampledName, "true");
            }
        }
Ejemplo n.º 19
0
 private static void VerifySupportedFormat <TCarrier>(IFormat <TCarrier> format)
 {
     if (format != BuiltinFormats.HttpHeaders && format != BuiltinFormats.TextMap)
     {
         throw new InvalidOperationException("Format " + format.ToString() + " not supported");
     }
 }
Ejemplo n.º 20
0
        /// <inheritdoc />
        public SpanContext Extract <TCarrier>(IFormat <TCarrier> format, TCarrier carrier)
        {
            string traceId = null;
            string spanId  = null;

            if (carrier is ITextMap text)
            {
                foreach (var entry in text)
                {
                    if (TraceIdName.Equals(entry.Key))
                    {
                        traceId = entry.Value;
                    }
                    else if (SpanIdName.Equals(entry.Key))
                    {
                        spanId = entry.Value;
                    }
                }
            }

            if (!string.IsNullOrEmpty(traceId) && !string.IsNullOrEmpty(spanId))
            {
                return(new SpanContext(traceId, spanId));
            }

            return(null);
        }
Ejemplo n.º 21
0
        public static string Format(this IFormat obj, string delimeter = ",")
        {
            var result     = string.Empty;
            var objType    = obj.GetType();
            var properties = objType.GetProperties();
            var props      = new SortedDictionary <int, PropertyInfo>();

            foreach (var property in properties)
            {
                var formatAttributes = property.GetCustomAttributes(typeof(FormatAttribute), false);
                if (formatAttributes.Length > 0)
                {
                    var formatAttribute = (FormatAttribute)formatAttributes[0];
                    if (formatAttribute.IsVisible)
                    {
                        props.Add(formatAttribute.Order, property);
                    }
                }
                else
                {
                    props.Add(props.Count, property);
                }
            }

            foreach (var prop in props)
            {
                result += prop.Value.GetValue(obj, null) + delimeter;
            }
            return(result);
        }
Ejemplo n.º 22
0
 /// <summary>
 /// Discovers serializers from an assembly.
 /// </summary>
 /// <param name="a">An Assembly.</param>
 protected void DiscoverFrom(Assembly a)
 {
     try {
         foreach (Type t in a.GetTypes())
         {
             if (t.GetInterface(typeof(IPrimitiveSerializer).FullName) != null &&
                 !t.IsAbstract && t.GetConstructor(Type.EmptyTypes) != null && !t.ContainsGenericParameters)
             {
                 IPrimitiveSerializer primitiveSerializer =
                     (IPrimitiveSerializer)Activator.CreateInstance(t, true);
                 if (!PrimitiveSerializers.ContainsKey(primitiveSerializer.SerialDataType))
                 {
                     PrimitiveSerializers.Add(primitiveSerializer.SerialDataType, new List <IPrimitiveSerializer>());
                 }
                 PrimitiveSerializers[primitiveSerializer.SerialDataType].Add(primitiveSerializer);
             }
             if (t.GetInterface(typeof(ICompositeSerializer).FullName) != null &&
                 !t.IsAbstract && t.GetConstructor(Type.EmptyTypes) != null && !t.ContainsGenericParameters)
             {
                 CompositeSerializers.Add((ICompositeSerializer)Activator.CreateInstance(t, true));
             }
             if (t.GetInterface(typeof(IFormat).FullName) != null &&
                 !t.IsAbstract && t.GetConstructor(Type.EmptyTypes) != null && !t.ContainsGenericParameters)
             {
                 IFormat format = (IFormat)Activator.CreateInstance(t, true);
                 Formats.Add(format);
             }
         }
     } catch (ReflectionTypeLoadException e) {
         Logger.Warn("could not analyse assembly: " + a.FullName, e);
     }
 }
Ejemplo n.º 23
0
 public RestResponse(string body, IFormat format, HttpResponseMessage message)
 {
     Body    = body;
     Content = message.IsSuccessStatusCode ? format.Deserialize <TModel>(body) : default;
     Format  = format;
     Message = message;
 }
Ejemplo n.º 24
0
 public ProcessData(IEnumerable <IDataAccess> acesses, IEnumerable <IFormat> formats)
 {
     this.fileDataAccess  = acesses.First(o => o.GetType() == typeof(FileSystem));
     this.cloudDataAccess = acesses.First(o => o.GetType() == typeof(Cloud));
     this.xmlFormat       = formats.First(o => o.GetType() == typeof(XmlFormat));
     this.jsonFormat      = formats.First(o => o.GetType() == typeof(JsonFormat));
 }
Ejemplo n.º 25
0
        public override string ToString()
        {
            string assembly         = "DL.Protocol";
            string formatsNamespace = "DL.Protocol.Formats";

            if (FieldFormat == null)
            {
                Type   type            = typeof(T);
                string formatClassName = type.Name + "Format";
                //IFormat<T> format = Tools.CreateInstance<IFormat<T>>(assembly, formatsNamespace, formatClassName);
                Type        formatType = Type.GetType(formatsNamespace + "." + formatClassName);
                IFormat <T> format     = Tools.InvokeStaticMethod <IFormat <T> >(formatType, "GetInstance", null);
                if (format == null)
                {
                    return(base.ToString());
                }
                else
                {
                    return(format.GetString(this, this.GetData()));
                }
            }
            else
            {
                return(FieldFormat.GetString(this, this.GetData()));
            }
        }
Ejemplo n.º 26
0
        public IFormat Open(FileItem f)
        {
            // check extensions
            if (f.Extension != null)
            {
                if (ExtensionToType.ContainsKey(f.Extension))
                {
                    foreach (var type in ExtensionToType[f.Extension])
                    {
                        IFormat format = Activator.CreateInstance(type) as IFormat;
                        if (format.Verify(f) && format.CanOpen)
                        {
                            format.Open(f);
                            return(format);
                        }
                    }
                }
            }

            // check verify
            foreach (var type in AllTypes)
            {
                IFormat format = Activator.CreateInstance(type) as IFormat;

                if (format.Verify(f) && format.CanOpen)
                {
                    format.Open(f);
                    return(format);
                }
            }

            // not supported
            return(null);
        }
Ejemplo n.º 27
0
        // FORMAT TO MATH MODEL PARSER
        public IExpressionType UnitImportFromFormatToModel(IFormat input, int listPosition)
        {
            Context ctx = Context.getInstance();

            ctx.getIn(input.getType().ToString() + listPosition); //спускаемся в контекст блока

            List <IExpressionType> unitExpressions = new List <IExpressionType>();

            for (int o = 0; o < input.getOperands().Count; o++) // преобразуем все выражения внутри блока
            {
                switch (input.getOperands()[o].getType())
                {
                case Types.FuncDefinition:
                case Types.WhileU:
                case Types.ConditionU:
                    unitExpressions.Add(UnitImportFromFormatToModel(input.getOperands()[o], o));
                    break;

                default:
                    unitExpressions.Add(ExpressionImportFromFormatToModel(input.getOperands()[o]));
                    break;
                }
            }

            // преобразуем выражение - условие
            IExpressionType options = null;

            if (input.getType() != Types.FuncDefinition)
            {
                options = input.getOptions() == null ? null : ExpressionImportFromFormatToModel(input.getOptions());
            }

            ctx.getOut();

            // построение самого блока
            switch (input.getType())
            {
            case Types.GlobalU:
                return(new GlobalUnit(unitExpressions, listPosition));

            case Types.WhileU:
                return(new WhileUnit(unitExpressions, options, listPosition));

            case Types.FuncDefinition:
                string name = input.getOptions().getOptions().getValue();

                List <Variable> lst = new List <Variable>();
                foreach (var v in input.getOptions().getOperands())
                {
                    lst.Add(new Variable(v.getValue()));
                }

                FunctionDefenition fd = new FunctionDefenition(unitExpressions, name, lst, listPosition);
                ctx.addFunction(name, ctx.getCurrPath(), fd);
                return(fd);

            default:
                throw new Exception("Error in importing" + input.getType());
            }
        }
Ejemplo n.º 28
0
        public SpanContext Extract <TCarrier>(IFormat <TCarrier> format, TCarrier carrier, StringComparison comparison)
        {
            _logger.Trace($"Extracting {format.GetType()} from {carrier.GetType()}");
            if (carrier is ITextMap text)
            {
                ulong?traceId = null;
                ulong?spanId  = null;
                var   baggage = new Baggage();

                foreach (var entry in text)
                {
                    if (Keys.TraceId.Equals(entry.Key, comparison))
                    {
                        traceId = Convert.ToUInt64(entry.Value, 16);
                    }
                    else if (Keys.SpanId.Equals(entry.Key, comparison))
                    {
                        spanId = Convert.ToUInt64(entry.Value, 16);
                    }
                    else if (entry.Key.StartsWith(Keys.BaggagePrefix, comparison))
                    {
                        var key = entry.Key.Substring(Keys.BaggagePrefix.Length);
                        baggage.Set(key, entry.Value);
                    }
                }

                if (traceId.HasValue && spanId.HasValue)
                {
                    _logger.Trace($"Existing trace/spanID found, returning SpanContext.");
                    return(new SpanContext(traceId.Value, spanId.Value));
                }
            }

            return(null);
        }
Ejemplo n.º 29
0
 public Site(string name, Navigation navi, IFormat format, DataContent content)
 {
     Name       = name;
     Navigation = navi;
     Format     = format;
     Content    = content;
 }
Ejemplo n.º 30
0
 public BaseRestService(IRestHandler restHandler, IFormat formator, IRestRequest restRequest)
 {
     _restHandler = restHandler;
     _formator = formator;
     _restRequest = restRequest;
     Initialize();
 }
Ejemplo n.º 31
0
        /// <summary>
        /// Process a proto entry from format A to format B by using the dynamic definition.
        ///
        /// NOTE: Both src and dst MUST BE initialized before this function should be called.
        /// NOTE: Both src and dst finalize MUST BE called after this function, this function
        /// will not call them.
        /// </summary>
        /// <param name="def">A JSONParser class that stores the definition.</param>
        /// <param name="src">The source format.</param>
        /// <param name="dst">The destination format.</param>
        /// <param name="list">The list to get the defines from.</param>
        private static void ProcessEntry(JSONParser def, IFormat src, IFormat dst, List <BasicObjectDefine> list)
        {
            foreach (var objdef in list)
            {
                if (objdef.type == "string")
                {
                    SetStringType(objdef.count, objdef.name, src, dst);
                    continue;
                }

                for (int i = 0; i < objdef.count; i++)
                {
                    if (SetBaseType(objdef.type, GetNewName(objdef.name, i, objdef.count), src, dst))
                    {
                        continue;
                    }

                    var complexType = def.GetTypedefObjectFromName(objdef.type);

                    if (complexType == null)
                    {
                        throw new Exception($"Complex type not defined {objdef.type}");
                    }

                    if (!SetComplexType(complexType, objdef.name, src, dst, i, objdef.count))
                    {
                        throw new Exception($"Invalid type {objdef.type} for {objdef.name}");
                    }
                }
            }
        }
Ejemplo n.º 32
0
        public FormSummary(IFormat scanFormat)
        {
            ScanFormat = scanFormat;

            InitializeComponent();
            InitializeControl();
        }
Ejemplo n.º 33
0
 public LocatorValidationResult( DataTable result, ParameterizedDatumLocator datumLocator, Navigation modifiedNavigation, string documentLocation, IFormat modifiedFormat )
 {
     Result = result;
     DatumLocator = datumLocator;
     Navigation = modifiedNavigation ?? Navigation.Empty;
     DocumentLocation = documentLocation;
     Format = modifiedFormat;
 }
Ejemplo n.º 34
0
 public AbstractECU(VehicleDB db, ICommbox box)
 {
     troubleCode = null;
     dataStream = null;
     freezeFrame = null;
     activeTest = null;
     this.db = db;
     this.box = box;
     param = new Parameter();
     format = null;
     chn = null;
 }
Ejemplo n.º 35
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Configuration"/> class.
 /// </summary>
 /// <param name="format">The format.</param>
 /// <param name="primitiveSerializers">The primitive serializers.</param>
 /// <param name="compositeSerializers">The composite serializers.</param>
 public Configuration(IFormat format,
     IEnumerable<IPrimitiveSerializer> primitiveSerializers,
     IEnumerable<ICompositeSerializer> compositeSerializers)
   : this(false) {
   this.Format = format;
   this.compositeSerializers.AddRange(compositeSerializers);
   foreach (var primitiveSerializer in primitiveSerializers) {
     if (primitiveSerializer.SerialDataType != format.SerialDataType)
       throw new ArgumentException(string.Format(
         "primitive serializer's ({0}) serialized data type ({1}) " + Environment.NewLine +
         "is not compatible with selected format's ({2}) seriali data type ({3})",
         primitiveSerializers.GetType().FullName, primitiveSerializer.SerialDataType.FullName,
         format.Name, format.SerialDataType.FullName));
     this.primitiveSerializers.Add(primitiveSerializer.SourceType, primitiveSerializer);
   }
 }
Ejemplo n.º 36
0
        public DataTable ExtractTable( IFormat format )
        {
            PathSeriesFormat pathSeriesFormat = format as PathSeriesFormat;
            PathTableFormat pathTableFormat = format as PathTableFormat;

            if ( pathSeriesFormat != null )
            {
                var htmlSettings = new HtmlExtractionSettings();
                htmlSettings.ExtractLinkUrl = pathSeriesFormat.ExtractLinkUrl;

                var result = Content.ExtractTable( HtmlPath.Parse( pathSeriesFormat.Path ), pathSeriesFormat.ToExtractionSettings(), htmlSettings );
                if ( !result.Success )
                {
                    throw new Exception( "Failed to extract table from document: " + result.FailureReason );
                }

                return pathSeriesFormat.ToFormattedTable( result.Value );
            }
            else if ( pathTableFormat != null )
            {
                var result = Content.ExtractTable( HtmlPath.Parse( pathTableFormat.Path ), true );
                if ( !result.Success )
                {
                    throw new Exception( "Failed to extract table from document: " + result.FailureReason );
                }

                return pathTableFormat.ToFormattedTable( result.Value );
            }
            else if ( format is PathSingleValueFormat )
            {
                var f = (PathSingleValueFormat)format;
                var str = Content.GetTextByPath( HtmlPath.Parse( f.Path ) );
                var value = f.ValueFormat.Convert( str );

                // XXX: this is really ugly - i have to create a table just to satisfy the interface :(
                return CreateTableForScalar( f.ValueFormat.Type, value );
            }
            else
            {
                throw new NotSupportedException( "Format not supported for Html documents: " + format.GetType() );
            }
        }
Ejemplo n.º 37
0
 public DataStreamFunction(VehicleDB db, IChannel chn, IFormat format)
     : base(db, chn, format)
 {
     stopRead = true;
     stopCalc = true;
     readExp = false;
     lds = null;
     readInterval = Timer.FromMilliseconds(10);
     calcInterval = Timer.FromMilliseconds(1);
     readMutex = new Mutex();
     calcMutex = new Mutex();
     taskFactory = new TaskFactory();
     tasks = null;
     readBuff = new byte[128];
     historyBuff = new Dictionary<string, byte[]>();
     BeginRead = null;
     EndRead = null;
     BeginCalc = null;
     EndCalc = null;
 }
Ejemplo n.º 38
0
        public DataTable ExtractTable( IFormat format )
        {
            SeparatorSeriesFormat separatorSeriesFormat = format as SeparatorSeriesFormat;
            CsvFormat csvFormat = format as CsvFormat;

            if ( csvFormat != null )
            {
                DataTable result = CsvReader.Read( Location, csvFormat.Separator );
                return csvFormat.ToFormattedTable( result );
            }
            else if ( separatorSeriesFormat != null )
            {
                DataTable result = CsvReader.Read( Location, separatorSeriesFormat.Separator );
                return separatorSeriesFormat.ToFormattedTable( result );
            }
            else
            {
                throw new NotSupportedException( "Format not supported for text files: " + format.GetType() );
            }
        }
Ejemplo n.º 39
0
 public void Format(string format)
 {
     switch (format)
     {
         case "XML":
             f = new XML();
             break;
         case "JSON":
             f = new JSON();
             break;
         case "CSV":
             f = new CSV();
             break;
         case "YAML":
             f = new YAML();
             break;
         default:
             f = new XML();
             break;
     }
 }
Ejemplo n.º 40
0
 public TroubleCodeFunction(VehicleDB db, IChannel chn, IFormat format)
     : base(db, chn, format)
 {
 }
Ejemplo n.º 41
0
 public ActiveTestFunction(VehicleDB db, IChannel chn, IFormat format)
     : base(db, chn, format)
 {
     actMap = new Dictionary<int, Action<ActiveState>>();
     state = ActiveState.Stop;
 }
Ejemplo n.º 42
0
        public void WriteOutputContent(MediaType mediaType, IFormat format)
        {
            if (mediaType == null)
            {
                throw new ArgumentNullException("mediaType", "mediaType cannot be null.");
            }

            if (format == null)
            {
                throw new ArgumentNullException("format", "format cannot be null.");
            }

            string contentType = format.ContentType(mediaType);

            if (contentType.Contains("*"))
            {
                throw new InvalidOperationException(
                    string.Format(
                        CultureInfo.InvariantCulture,
                        "Format {0} returned a Content-Type of {1} for the chosen media type of {2}. Writing a wildcard Content-Type to the response is not supported.",
                        format.GetType(),
                        contentType,
                        mediaType));
            }

            object resp = this.ResponseObject;
            this.httpResponse.ContentType = contentType;

            if (resp != null)
            {
                format.Serialize(mediaType, resp, this.httpResponse.OutputStream);
            }
        }
Ejemplo n.º 43
0
        public static void ShowDialog(DevExpress.XtraEditors.XtraForm mainForm, DevExpress.XtraEditors.XtraForm form, bool isWaitForm, IFormat isFormat, IPermission isPermision,
            bool isMultiLang, bool isModal, bool ignoreCheckShowForm)
        {
            //if (FrameworkParams.wait != null) FrameworkParams.wait.Finish();
            //if (isWaitForm) FrameworkParams.wait = new WaitingMsg();

            if (ignoreCheckShowForm == false)
            {
                if (HelpPermission.CanShowForm(form) == false)
                {
                    ApplyPermissionAction.getPermissionFormFail().ShowDialog();
                    form.Dispose();
                    return;
                }
            }

            try
            {
                if (form.IsDisposed) return;
                //form.TopMost = true;

                HelpUserLog.logOpenForm(form);
                PLPlugin.HookShowAllPlugin(form);

                form.FormClosed += new FormClosedEventHandler(form_FormClosed);
                ProtocolForm.pl_wrapper(ref form, isFormat, isPermision);
                EventHandler showEvent = new EventHandler(wait);
                form.Shown += showEvent;
                //DEVEXPRESS
                if (FrameworkParams.UsingRightClickForm) HelpXtraForm.PopupRightClickForm(form);

                if (FrameworkParams.wait != null) FrameworkParams.wait.Finish();

                HelpXtraForm.SetModal(mainForm, form, isModal);
            }
            catch (Exception ex)
            {
                PLException.AddException(ex);
                PLMessageBox.ShowSystemErrorMessage(ex.ToString());
            }
        }
Ejemplo n.º 44
0
 public static void ShowDialog(DevExpress.XtraEditors.XtraForm mainForm, DevExpress.XtraEditors.XtraForm form, bool isWaitForm, IFormat isFormat, IPermission isPermision, bool isMultiLang)
 {
     ShowDialog(mainForm, form, isWaitForm, isFormat, isPermision, isMultiLang, false);
 }
Ejemplo n.º 45
0
        public static void ShowWindow(DevExpress.XtraEditors.XtraForm mainForm,
            DevExpress.XtraEditors.XtraForm form, bool isWait, IFormat isFormat,
            IPermission isPermision, bool ignoreCheckShowForm)
        {
            //if (FrameworkParams.wait != null) FrameworkParams.wait.Finish();
            //if (isWait) FrameworkParams.wait = new WaitingMsg();
            ////Kích hoạt menu đang mở nếu đã mở
            //foreach (Form f in mainForm.MdiChildren)
            //{
            //    if (f.Text.Equals(form.Text) && f.Controls.Count == form.Controls.Count)
            //    {
            //        f.Activate();
            //        return;
            //    }
            //}
            if (ignoreCheckShowForm == false)
            {
                if (HelpPermission.CanShowForm(form) == false)
                {
                    ApplyPermissionAction.getPermissionFormFail().ShowDialog();
                    form.Dispose();
                    return;
                }
            }

            try
            {
                if (form.IsDisposed) return;

                HelpUserLog.logOpenForm(form);
                PLPlugin.HookShowAllPlugin(form);

                form.FormClosed += new FormClosedEventHandler(form_FormClosed);
                //form.Disposed += new EventHandler(form_Disposed);

                form.MdiParent = mainForm;
                form.MinimizeBox = false;
                form.WindowState = FormWindowState.Maximized;
                form.ShowInTaskbar = false;
                form.Icon = FrameworkParams.ApplicationIcon;

                ProtocolForm.pl_wrapper(ref form, isFormat, isPermision);

                form.Shown += new EventHandler(wait);
                //DEVEXPRESS
                if (FrameworkParams.UsingRightClickForm) HelpXtraForm.PopupRightClickForm(form);

                if (form is frmPermissionFail)
                    form.ShowDialog(FrameworkParams.MainForm);
                else
                    form.Show();
            }
            catch (Exception ex)
            {
                PLException.AddException(ex);
                PLMessageBox.ShowSystemErrorMessage(ex.ToString());
            }
        }
Ejemplo n.º 46
0
 public static void ShowWindow(DevExpress.XtraEditors.XtraForm mainForm, DevExpress.XtraEditors.XtraForm form, bool isWait, IFormat isFormat, IPermission isPermision)
 {
     ShowWindow(mainForm, form, isWait, isFormat, isPermision, false);
 }
Ejemplo n.º 47
0
 public AbstractFunction(VehicleDB db, IChannel chn, IFormat format)
 {
     this.db = db;
     this.chn = chn;
     this.format = format;
 }
Ejemplo n.º 48
0
        /// <summary>
        /// Indicates whether the current object is equal to another object of the same type.
        /// </summary>
        /// <param name="other">An object to compare with this object.</param>
        /// <returns>True if the current object is equal to the other parameter, otherwise false.</returns>
        public bool Equals(IFormat other)
        {
            if ((object)other != null)
            {
                return this.GetType().Equals(other.GetType());
            }

            return false;
        }
Ejemplo n.º 49
0
        public static void pl_wrapper(ref XtraForm form, IFormat isFormat, IPermission isPermision)
        {
            ProtocolForm standard = new ProtocolForm(form);
            if (isPermision != null)
                standard.applyActions.Add(new ProtocolVN.Framework.Win.ApplyPermissionAction(form.GetType().ToString()));
            if (isFormat != null)
                standard.applyActions.Add(new ProtocolVN.Framework.Win.ApplyFormatAction());

            //PHUOCNC : Thất bại có thể rơi vào chức năng khác
            //          Nhưng hiện tại chắc chắn thất bại chỉ do phân quyền
            if (standard.wrapperForm() == false)
            {
                form.Close();
                form = ApplyPermissionAction.getPermissionFormFail();
            }
            else
            {

            }
        }
Ejemplo n.º 50
0
 public ActionCommand(string command, IFormat format)
 {
     this.command = command;
     this.format = format;
 }
Ejemplo n.º 51
0
        public void WriteOutputContent(MediaType mediaType, IFormat format)
        {
            if (mediaType == null)
            {
                throw new ArgumentNullException("mediaType", "mediaType cannot be null.");
            }

            if (format == null)
            {
                throw new ArgumentNullException("format", "format cannot be null.");
            }

            object resp = this.ResponseObject;
            this.Headers["Content-Type"] = format.ContentType(mediaType);

            if (resp != null)
            {
                format.Serialize(mediaType, resp, this.OutputStream);
            }
        }