Exemple #1
0
        /// <summary>
        /// <para>
        /// Decodes the input from Watson Representation to the specified format in <paramref name="options"/> and stores it in <paramref name="stream"/>
        /// </para>
        /// </summary>
        /// <param name="options">The decoing options</param>
        /// <param name="stream">The output stream</param>
        public static void Decode(DecodeOptions options, Stream output)
        {
            var vm = new VM(new Lexer(options.InitialMode));

            Converter converter = ConverterFactory.GetConverter(options.Type);

            string input;

            using (var writer = new StreamWriter(output))
            {
                if (options.Files.Count() == 0)
                {
                    input = Console.ReadLine();
                    writer.Write(converter.Decode(input, vm));
                }
                else
                {
                    var sb = new StringBuilder();
                    foreach (var file in options.Files)
                    {
                        using (var fileStream = new FileStream(file, FileMode.Open))
                        {
                            using (var reader = new StreamReader(fileStream))
                            {
                                converter.Decode(reader, writer, vm);
                            }
                        }
                    }
                }
            }
        }
        public object OutputValue()
        {
            var converter = ConverterFactory.GetConverter(Definition);
            var output    = converter.Output(Value);

            return(output);
        }
Exemple #3
0
        /// <summary>
        /// <para>
        /// Encodes the input to Watson Representation using <paramref name="options"/> and stores it in <paramref name="stream"/>
        /// </para>
        /// </summary>
        /// <param name="options">The encoding options</param>
        /// <param name="stream">The output stream</param>
        public static void Encode(EncodeOptions options, Stream stream)
        {
            var vm = new VM(options.InitialMode);

            Converter converter = ConverterFactory.GetConverter(options.Type);

            using (var writer = new StreamWriter(stream))
            {
                if (options.File == null)
                {
                    string input = Console.ReadLine();
                    writer.Write(converter.Encode(input, vm));
                }
                else
                {
                    using (var fileStream = new FileStream(options.File, FileMode.Open))
                    {
                        using (var reader = new StreamReader(fileStream))
                        {
                            converter.Encode(reader, writer, vm);
                        }
                    }
                }
            }
        }
Exemple #4
0
        public static object StringToField(this IFieldInfoDescriptor fieldDescriptor, string value)
        {
            if (value == null)
            {
                return(null);
            }

            value = fieldDescriptor.StringTrim(value);

            if (string.Empty.Equals(value) && fieldDescriptor.Converter == null)
            {
                return(value);
            }

            if (fieldDescriptor.Converter == null && fieldDescriptor.Type == null)
            {
                return(value);
            }

            ConverterBase converterInstance =
                fieldDescriptor.Converter == null
                ? ConverterFactory.GetDefaultConverter(fieldDescriptor.Type, fieldDescriptor.ConverterFormat)
                : ConverterFactory.GetConverter(fieldDescriptor.Converter, fieldDescriptor.ConverterFormat);

            return(converterInstance == null
                ? value
                : converterInstance.StringToField(value));
        }
Exemple #5
0
        /// <summary>
        /// <para>
        /// Decodes the input from Watson Representation to the specified format in <paramref name="options"/> and outputs it to the standard output
        /// Will read from the standard input if no files are specified
        /// </para>
        /// </summary>
        /// <param name="options">The decoding options</param>
        /// <returns>A string containing the Watson input in the specified format</returns>
        public static string Decode(DecodeOptions options)
        {
            var vm = new VM(new Lexer(options.InitialMode));

            Converter converter = ConverterFactory.GetConverter(options.Type);

            string input;
            string output = null;

            if (options.Files.Count() == 0)
            {
                input  = Console.ReadLine();
                output = converter.Decode(input, vm);
            }
            else
            {
                var sb = new StringBuilder();
                foreach (var file in options.Files)
                {
                    using (var fileStream = new FileStream(file, FileMode.Open))
                    {
                        using (var reader = new StreamReader(fileStream))
                        {
                            output = converter.Decode(reader.ReadToEnd(), vm);
                        }
                    }
                }
            }
            return(output);
        }
Exemple #6
0
        /// <summary>
        /// <para>Encodes the input to Watson Representation using <paramref name="options"/> and outputs it to the standard output.
        /// Will read from the standard input if the file isn't specified
        /// </para>
        /// </summary>
        /// <param name="options">The encoding options</param>
        /// <returns>A string containing the input's Watson Representation</returns>
        public static string Encode(EncodeOptions options)
        {
            var vm = new VM(options.InitialMode);

            Converter converter = ConverterFactory.GetConverter(options.Type);

            string output;

            if (options.File == null)
            {
                string input = Console.ReadLine();
                output = converter.Encode(input, vm);
            }
            else
            {
                using (var fileStream = new FileStream(options.File, FileMode.Open))
                {
                    using (var streamReader = new StreamReader(fileStream))
                    {
                        output = converter.Encode(streamReader.ReadToEnd(), vm);
                    }
                }
            }
            return(output);
        }
        public void When_Custom_Converter_Configured_In_AppConfig_It_Is_Returned()
        {
            var section   = (CouchbaseClientSection)ConfigurationManager.GetSection("couchbaseClients/couchbase_2");
            var converter = ConverterFactory.GetConverter(section.Converter);

            Assert.IsNotNull(converter);
            Assert.IsInstanceOf <FakeConverter>(converter());
        }
Exemple #8
0
        public static Angle operator+(Angle op1, Angle op2)
        {
            IAngleConverter converter = ConverterFactory.GetConverter(op1.AngluarUnit);

            Angle newAngle = converter.Convert(op1);

            return(((IAngleOperations)op1).Add(newAngle));
        }
 public void ReplaceDatetimeConverter()
 {
     ConverterFactory f = new ConverterFactory();
     f.RemoveConverter( typeof( DateTime ) );
     f.AddConverter( typeof( DateTime ), new ConverterStub( null ) );
     IConverter c = f.GetConverter( typeof( DateTime ) );
     DateTime now = DateTime.Now;
     Assert.AreEqual( "Stub: " + now.ToString(), c.ToString( now ) );
 }
Exemple #10
0
        private static void ApplyProperties(string[] args, Command c, object instance)
        {
            var all = c.Type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
            var r   = new HashSet <string>();

            foreach (var prop in all)
            {
                var required = prop.GetCustomAttribute(typeof(RequiredAttribute), false);
                if (required == null)
                {
                    continue;
                }

                r.Add(prop.Name);
            }

            var regexp           = new Regex(ParameterPattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);
            var groupCollections = args
                                   .Where(p => regexp.IsMatch(p))
                                   .Select(p => regexp.Matches(p))
                                   .Where(m => m.Count == 1)
                                   .Where(m => m[0].Groups.Count == 3)
                                   .Select(m => m[0].Groups);

            foreach (var groups in groupCollections)
            {
                const int parameter = 1;
                const int value     = 2;

                var p = groups[parameter].Value;
                var v = groups[value].Value;

                if (!c.HasAlias(p))
                {
                    continue;
                }

                var prop = c.GetParameterForAlias(p);
                prop.SetValue(
                    instance,
                    ConverterFactory.GetConverter(prop.PropertyType).GetValue(v));

                if (r.Contains(prop.Name))
                {
                    r.Remove(prop.Name);
                }
            }

            if (r.Count > 0)
            {
                throw new ArgumentException(
                          string.Format(
                              "Required arguments not supplied: {0}.",
                              string.Join(", ", r.ToArray())));
            }
        }
Exemple #11
0
        internal static object StringToRecord(this IFieldInfoDescriptor fieldInfoDescriptor, string fieldString, char nullChar)
        {
            if (fieldString == null)
            {
                return(fieldInfoDescriptor.NullValue ?? null);
            }

            string stringNullRepresentation = new string(nullChar, fieldString.Length);

            if (fieldString == stringNullRepresentation)
            {
                return(fieldInfoDescriptor.NullValue ?? null);
            }

            fieldString = fieldInfoDescriptor.StringTrim(fieldString);
            ConverterBase converterInstance;

            if (string.Empty.Equals(fieldString) && fieldInfoDescriptor.Converter == null)
            {
                if (fieldInfoDescriptor.NullValue != null)
                {
                    fieldString = fieldInfoDescriptor.NullValue.ToString();
                }
                if (string.Empty.Equals(fieldString) && fieldInfoDescriptor.Converter == null)
                {
                    if (fieldInfoDescriptor.Type != null)
                    {
                        converterInstance = ConverterFactory.GetDefaultConverter(fieldInfoDescriptor.Type, fieldInfoDescriptor.ConverterFormat);
                        return(converterInstance == null
                            ? fieldString
                            : converterInstance.StringToField(fieldString));
                    }
                    return(fieldString);
                }
            }

            if (fieldInfoDescriptor.Converter == null && fieldInfoDescriptor.Type == null)
            {
                return(fieldString);
            }

            if (string.IsNullOrWhiteSpace(fieldString) && fieldInfoDescriptor.NullValue != null)
            {
                fieldString = fieldInfoDescriptor.NullValue.ToString();
            }

            converterInstance =
                fieldInfoDescriptor.Converter == null
                ? ConverterFactory.GetDefaultConverter(fieldInfoDescriptor.Type, fieldInfoDescriptor.ConverterFormat)
                : ConverterFactory.GetConverter(fieldInfoDescriptor.Converter, fieldInfoDescriptor.ConverterFormat);

            return(converterInstance == null
                ? fieldString
                : converterInstance.StringToField(fieldString));
        }
Exemple #12
0
        public void ReplaceDatetimeConverter()
        {
            ConverterFactory f = new ConverterFactory();

            f.RemoveConverter(typeof(DateTime));
            f.AddConverter(typeof(DateTime), new ConverterStub(null));
            IConverter c   = f.GetConverter(typeof(DateTime));
            DateTime   now = DateTime.Now;

            Assert.AreEqual("Stub: " + now.ToString(), c.ToString(now));
        }
Exemple #13
0
        public string Convert(string inputPath)
        {
            string outputPath = GetOutputFilePath(inputPath);

            string extension = Path.GetExtension(inputPath);

            Converter converter = ConverterFactory.GetConverter(extension);

            converter.Convert(inputPath, outputPath);

            return(outputPath);
        }
Exemple #14
0
        public static void ConvertAndSetProperty(object obj, string propertyName, object value)
        {
            PropertyInfo propertyInfo = Reflector.GetProperty(obj, propertyName);

            if (propertyInfo == null)
            {
                throw new ArgumentException($"Property '{propertyName}' not found for type {obj.GetType()}");
            }
            var converter = ConverterFactory.GetConverter(propertyInfo.PropertyType);

            converter.SetProperty(obj, propertyName, converter.Convert(value));
        }
        public void TestConverterFactoryShouldReturnCsvToJsonConverter()
        {
            //Arrange
            var mockServiceProvider = new Mock <IServiceProvider>();

            var sut = new ConverterFactory(mockServiceProvider.Object);

            //Act
            sut.GetConverter(ConverterType.CsvToJson);

            //Assert
            mockServiceProvider.Verify(s => s.GetService(typeof(CsvToJsonConverter)), Times.Once);
        }
Exemple #16
0
 public void GetConverter_When_ConverterIsRequested_Then_FactoryReturnsCorrectInstance()
 {
     Assert.That(ConverterFactory.GetConverter(SupportedExtensions.doc), Is.TypeOf <WordToPdfConverter>());
     Assert.That(ConverterFactory.GetConverter(SupportedExtensions.docx), Is.TypeOf <WordToPdfConverter>());
     Assert.That(ConverterFactory.GetConverter(SupportedExtensions.pdf), Is.Null);
     Assert.That(ConverterFactory.GetConverter(SupportedExtensions.ppt), Is.TypeOf <PowerPointToPdfConverter>());
     Assert.That(ConverterFactory.GetConverter(SupportedExtensions.pptx), Is.TypeOf <PowerPointToPdfConverter>());
     Assert.That(ConverterFactory.GetConverter(SupportedExtensions.xls), Is.TypeOf <ExcelToHtmlConverter>());
     Assert.That(ConverterFactory.GetConverter(SupportedExtensions.xlsx), Is.TypeOf <ExcelToHtmlConverter>());
     Assert.That(ConverterFactory.GetConverter(SupportedExtensions.rtf), Is.TypeOf <RtfToPdfConverter>());
     Assert.That(ConverterFactory.GetConverter(SupportedExtensions.txt), Is.Null);
     Assert.That(ConverterFactory.GetConverter(SupportedExtensions.msg), Is.TypeOf <MailToHtmlConverter>());
     Assert.That(ConverterFactory.GetConverter(SupportedExtensions.eml), Is.TypeOf <MailToHtmlConverter>());
 }
        private static string CreateFieldString(this IXmlFieldInfoDescriptor fieldDescriptor, object fieldValue)
        {
            if (fieldDescriptor.Converter == null)
            {
                if (fieldValue == null)
                {
                    return(string.Empty);
                }
                return(fieldValue.ToString());
            }

            ConverterBase converterInstance =
                ConverterFactory.GetConverter(fieldDescriptor.Converter, fieldDescriptor.ConverterFormat);

            return(converterInstance?.FieldToString(fieldValue) ?? string.Empty);
        }
Exemple #18
0
        /// <summary>
        /// Converts units of data
        /// </summary>
        /// <param name="from">Contains numeric value and units from which to convert separated by space. Units are provided in singular form</param>
        /// <param name="to">Contains to which conversion is done. Should contain units in singular form</param>
        /// <returns>String desribing the result of conversion</returns>
        public static string ConvertData(string from, string to)
        {
            if (String.IsNullOrEmpty(from) || String.IsNullOrEmpty(to))
            {
                throw new ArgumentException("Please provide correct number and conversion units");
            }

            try
            {
                var converter = ConverterFactory.GetConverter(ConverterType.Data);
                return(converter.Convert(from, to));
            }
            catch (Exception ex)
            {
                throw new ArgumentException("Please provide correct number and conversion units");
            }
        }
Exemple #19
0
        protected RepositoryColumn <T> CreateColumn <T>(string name)
        {
            lock (_lockObject)
            {
                var converter = _converters.GetConverter <T>();
                if (converter == null)
                {
                    throw new InvalidOperationException("No converter found");
                }

                var column = new RepositoryColumn <T>(_columns.Count, name, converter);
                _columns.Add(column);
                column.CellUpdated(cellUpdate => _cellUpdated.OnNext(cellUpdate));

                return(column);
            }
        }
Exemple #20
0
        public StringBuilder BuildControl(string filePhysicalPath, string fileVirtualPath, string tempDirectoryPhysicalPath,
                                          string tempDirectoryVirtualPath, string appDomain, string appRootUrl)
        {
            try
            {
                string fileExtension          = Path.GetExtension(fileVirtualPath);
                string frameSource            = fileVirtualPath;
                SupportedExtensions extension = (SupportedExtensions)Enum.Parse(typeof(SupportedExtensions), fileExtension.Replace(".", ""));
                IConverter          converter = ConverterFactory.GetConverter(extension);
                if (converter != null)
                {
                    string tempFileName = converter.Convert(filePhysicalPath, tempDirectoryPhysicalPath);
                    if (string.IsNullOrEmpty(tempFileName))
                    {
                        throw new Exception("An error ocurred while trying to convert the file");
                    }

                    frameSource = string.Format("{0}/{1}", tempDirectoryVirtualPath, tempFileName);
                }

                if (PdfRenderer == PdfRenderers.PdfJs && Enum.IsDefined(typeof(PdfJsSupportedExtensions), extension.ToString()))
                {
                    frameSource = string.Format("{0}{1}Scripts/pdf.js/web/viewer.html?file={0}{2}", appDomain, appRootUrl, frameSource);
                }
                else
                {
                    frameSource = string.Format("{0}/{1}", appDomain, frameSource);
                }

                StringBuilder sb = new StringBuilder();
                sb.Append("<iframe ");
                if (!string.IsNullOrEmpty(ID))
                {
                    sb.Append("id=" + ClientID + " ");
                }
                sb.Append("src=" + frameSource + " ");
                sb.Append("width=" + Width.ToString() + " ");
                sb.Append("height=" + Height.ToString() + ">");
                sb.Append("</iframe>");
                return(sb);
            }
            catch
            {
                return(new StringBuilder("Cannot display document viewer"));
            }
        }
Exemple #21
0
        public void Launch(Launchable command, string[] args)
        {
            var commander = (Commander)command;
            var instance  = Activator.CreateInstance(commander.Type);

            var map  = new Dictionary <string, int>();
            var prms = commander.Method.GetParameters().ToList();
            var data = new object[prms.Count];

            var idx = 0;

            foreach (var param in prms)
            {
                map.Add(param.Name, idx++);
            }

            var regexp           = new Regex(ParameterPattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);
            var groupCollections = args
                                   .Where(p => regexp.IsMatch(p))
                                   .Select(p => regexp.Matches(p))
                                   .Where(m => m.Count == 1)
                                   .Where(m => m[0].Groups.Count == 3)
                                   .Select(m => m[0].Groups);

            var cmp = StringComparer.OrdinalIgnoreCase;

            foreach (var groups in groupCollections)
            {
                const int parameter = 1;
                const int value     = 2;

                var p = groups[parameter].Value;
                var v = groups[value].Value;

                // todo
                if (commander.HasAlias(p))
                {
                    var param = commander.GetAlias(p);
                    var pidx  = map[param.Name];
                    data[pidx] = ConverterFactory.GetConverter(param.ParameterType).GetValue(v);
                }
            }

            commander.Method.Invoke(instance, data);
        }
Exemple #22
0
        public static string ResolveType(this IFieldInfoDescriptor fieldDescriptor)
        {
            if (fieldDescriptor.Type == null && fieldDescriptor.Converter == null)
            {
                return("string");
            }

            var converterInstance =
                fieldDescriptor.Converter == null
                    ? ConverterFactory.GetDefaultConverter(fieldDescriptor.Type, fieldDescriptor.ConverterFormat)
                    : ConverterFactory.GetConverter(fieldDescriptor.Converter, fieldDescriptor.ConverterFormat);

            if (converterInstance == null)
            {
                return("string");
            }

            return(converterInstance.FieldType);
        }
Exemple #23
0
        public TreeEntity ConvertFile(ENUMConverterType type, TreeEntity file)
        {
            if (file.File == null)
            {
                throw new InvalidParametersException();
            }

            FileConverter converter = ConverterFactory.GetConverter(type);

            if (converter == null)
            {
                throw new InvalidParametersException();
            }

            file.File = converter.Convert(file);
            file.Name = converter.getNewFileName(file.Name);

            this.unitOfWork.TreeRepository.Update(file);
            this.unitOfWork.Save();

            return(file);
        }
Exemple #24
0
        public static string CreateFieldString(this IFieldInfoDescriptor fieldBuilder, object fieldValue)
        {
            ConverterBase converterInstance = null;

            if (fieldBuilder.Type != null || fieldBuilder.Converter != null)
            {
                converterInstance = fieldBuilder.Converter == null
                ? ConverterFactory.GetDefaultConverter(fieldBuilder.Type, fieldBuilder.ConverterFormat)
                : ConverterFactory.GetConverter(fieldBuilder.Converter, fieldBuilder.ConverterFormat);
            }

            if (converterInstance == null)
            {
                if (fieldValue == null)
                {
                    return(string.Empty);
                }

                return(fieldValue.ToString());
            }

            return(converterInstance.FieldToString(fieldValue) ?? string.Empty);
        }
Exemple #25
0
        public ClientConfiguration()
        {
            //For operation timing
            Timer = TimingFactory.GetTimer(Log);

            UseSsl                  = false;
            SslPort                 = 11207;
            ApiPort                 = 8092;
            DirectPort              = 11210;
            MgmtPort                = 8091;
            HttpsMgmtPort           = 18091;
            HttpsApiPort            = 18092;
            ObserveInterval         = 10;    //ms
            ObserveTimeout          = 500;   //ms
            MaxViewRetries          = 2;
            ViewHardTimeout         = 30000; //ms
            HeartbeatConfigInterval = 10000; //ms
            EnableConfigHeartBeat   = true;
            SerializationSettings   = new JsonSerializerSettings {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
            DeserializationSettings = new JsonSerializerSettings {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
            ViewRequestTimeout       = 5000; //ms
            DefaultConnectionLimit   = 5;    //connections
            Expect100Continue        = false;
            EnableOperationTiming    = false;
            BufferSize               = 1024 * 16;
            DefaultOperationLifespan = 2500;//ms
            EnableTcpKeepAlives      = true;
            TcpKeepAliveTime         = 2 * 60 * 60 * 1000;
            TcpKeepAliveInterval     = 1000;

            //the default serializer
            Serializer = SerializerFactory.GetSerializer();

            //the default byte converter
            Converter = ConverterFactory.GetConverter();

            //the default transcoder
            Transcoder = TranscoderFactory.GetTranscoder(this);

            PoolConfiguration = new PoolConfiguration(this)
            {
                BufferSize      = BufferSize,
                BufferAllocator = (p) => new BufferAllocator(p.MaxSize * p.BufferSize, p.BufferSize)
            };

            BucketConfigs = new Dictionary <string, BucketConfiguration>
            {
                { DefaultBucket, new BucketConfiguration
                  {
                      PoolConfiguration = PoolConfiguration,
                  } }
            };
            Servers = new List <Uri> {
                _defaultServer
            };

            //Set back to default
            _operationLifespanChanged = false;
            _serversChanged           = false;
            _poolConfigurationChanged = false;
        }
Exemple #26
0
        /// <summary>
        /// For synchronization with App.config or Web.configs.
        /// </summary>
        /// <param name="section"></param>
        public ClientConfiguration(CouchbaseClientSection section)
        {
            Timer = TimingFactory.GetTimer(Log);

            UseSsl                = section.UseSsl;
            SslPort               = section.SslPort;
            ApiPort               = section.ApiPort;
            DirectPort            = section.DirectPort;
            MgmtPort              = section.MgmtPort;
            HttpsMgmtPort         = section.HttpsMgmtPort;
            HttpsApiPort          = section.HttpsApiPort;
            ObserveInterval       = section.ObserveInterval;
            ObserveTimeout        = section.ObserveTimeout;
            MaxViewRetries        = section.MaxViewRetries;
            ViewHardTimeout       = section.ViewHardTimeout;
            SerializationSettings = new JsonSerializerSettings {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
            DeserializationSettings = new JsonSerializerSettings {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
            EnableConfigHeartBeat    = section.EnableConfigHeartBeat;
            HeartbeatConfigInterval  = section.HeartbeatConfigInterval;
            ViewRequestTimeout       = section.ViewRequestTimeout;
            Expect100Continue        = section.Expect100Continue;
            EnableOperationTiming    = section.EnableOperationTiming;
            PoolConfiguration        = new PoolConfiguration(this);
            DefaultOperationLifespan = section.OperationLifespan;

            //transcoders, converters, and serializers...o mai.
            Serializer = SerializerFactory.GetSerializer(this, section.Serializer);
            Converter  = ConverterFactory.GetConverter(section.Converter);
            Transcoder = TranscoderFactory.GetTranscoder(this, section.Transcoder);

            //to enable tcp keep-alives
            EnableTcpKeepAlives  = section.EnableTcpKeepAlives;
            TcpKeepAliveInterval = section.TcpKeepAliveInterval;
            TcpKeepAliveTime     = section.TcpKeepAliveTime;

            var keepAlivesChanged = EnableTcpKeepAlives != true ||
                                    TcpKeepAliveInterval != 1000 ||
                                    TcpKeepAliveTime != 2 * 60 * 60 * 1000;

            foreach (var server in section.Servers)
            {
                Servers.Add(((UriElement)server).Uri);
                _serversChanged = true;
            }

            BucketConfigs = new Dictionary <string, BucketConfiguration>();
            foreach (var bucketElement in section.Buckets)
            {
                var bucket = (BucketElement)bucketElement;
                var bucketConfiguration = new BucketConfiguration
                {
                    BucketName               = bucket.Name,
                    UseSsl                   = bucket.UseSsl,
                    Password                 = bucket.Password,
                    ObserveInterval          = bucket.ObserveInterval,
                    DefaultOperationLifespan = bucket.OperationLifespan ?? (uint)DefaultOperationLifespan,
                    ObserveTimeout           = bucket.ObserveTimeout,
                    PoolConfiguration        = new PoolConfiguration
                    {
                        MaxSize              = bucket.ConnectionPool.MaxSize,
                        MinSize              = bucket.ConnectionPool.MinSize,
                        WaitTimeout          = bucket.ConnectionPool.WaitTimeout,
                        ShutdownTimeout      = bucket.ConnectionPool.ShutdownTimeout,
                        UseSsl               = bucket.ConnectionPool.UseSsl,
                        BufferSize           = bucket.ConnectionPool.BufferSize,
                        BufferAllocator      = (p) => new BufferAllocator(p.MaxSize * p.BufferSize, p.BufferSize),
                        ConnectTimeout       = bucket.ConnectionPool.ConnectTimeout,
                        SendTimeout          = bucket.ConnectionPool.SendTimeout,
                        EnableTcpKeepAlives  = keepAlivesChanged ? EnableTcpKeepAlives : bucket.ConnectionPool.EnableTcpKeepAlives,
                        TcpKeepAliveInterval = keepAlivesChanged ? TcpKeepAliveInterval : bucket.ConnectionPool.TcpKeepAliveInterval,
                        TcpKeepAliveTime     = keepAlivesChanged ? TcpKeepAliveTime : bucket.ConnectionPool.TcpKeepAliveTime,
                        CloseAttemptInterval = bucket.ConnectionPool.CloseAttemptInterval,
                        MaxCloseAttempts     = bucket.ConnectionPool.MaxCloseAttempts,
                        ClientConfiguration  = this
                    }
                };
                BucketConfigs.Add(bucket.Name, bucketConfiguration);
            }

            //Set back to default
            _operationLifespanChanged = false;
            _poolConfigurationChanged = false;
        }
        public static object StringToRecord(this IFixedFieldInfoDescriptor recordInfo, string line, ref int offset)
        {
            if (offset >= line.Length)
            {
                return(null);
            }
            int length = recordInfo.Length;

            if (line.Length < recordInfo.Length + offset)
            {
                length = line.Length - offset;
            }

            var stringValue = line.Substring(offset, length);

            offset += length;

            string stringNullRepresentation = new string('\u0000', length);

            if ((stringValue == null || stringValue == stringNullRepresentation) && recordInfo.NullValue == null)
            {
                return(null);
            }
            else if ((stringValue == null || stringValue == stringNullRepresentation) && recordInfo.NullValue != null)
            {
                stringValue = recordInfo.NullValue.ToString();
            }

            stringValue = recordInfo.StringTrim(stringValue);
            ConverterBase converterInstance;

            if (string.Empty.Equals(stringValue) && recordInfo.Converter == null)
            {
                if (recordInfo.NullValue != null)
                {
                    stringValue = recordInfo.NullValue.ToString();
                }
                if (string.Empty.Equals(stringValue) && recordInfo.Converter == null)
                {
                    if (recordInfo.Type != null)
                    {
                        converterInstance = ConverterFactory.GetDefaultConverter(recordInfo.Type, recordInfo.ConverterFormat);
                        return(converterInstance == null
                            ? stringValue
                            : converterInstance.StringToField(stringValue));
                    }
                    return(stringValue);
                }
            }

            if (recordInfo.Converter == null && recordInfo.Type == null)
            {
                return(stringValue);
            }

            if (string.IsNullOrWhiteSpace(stringValue) && recordInfo.NullValue != null)
            {
                stringValue = recordInfo.NullValue.ToString();
            }

            converterInstance =
                recordInfo.Converter == null
                ? ConverterFactory.GetDefaultConverter(recordInfo.Type, recordInfo.ConverterFormat)
                : ConverterFactory.GetConverter(recordInfo.Converter, recordInfo.ConverterFormat);

            return(converterInstance == null
                ? stringValue
                : converterInstance.StringToField(stringValue));
        }
        public ClientConfiguration()
        {
            //For operation timing
            Timer = TimingFactory.GetTimer();
            QueryRequestTimeout = Defaults.QueryRequestTimeout;
            EnableQueryTiming   = Defaults.EnableQueryTiming;
            UseSsl          = Defaults.UseSsl;
            SslPort         = (int)Defaults.SslPort;
            ApiPort         = (int)Defaults.ApiPort;
            DirectPort      = (int)Defaults.DirectPort;
            MgmtPort        = (int)Defaults.MgmtPort;
            HttpsMgmtPort   = (int)Defaults.HttpsMgmtPort;
            HttpsApiPort    = (int)Defaults.HttpsApiPort;
            ObserveInterval = (int)Defaults.ObserveInterval; //ms
            ObserveTimeout  = (int)Defaults.ObserveTimeout;  //ms
            MaxViewRetries  = (int)Defaults.MaxViewRetries;
#pragma warning disable 618
            ViewHardTimeout = (int)Defaults.ViewHardTimeout;            //ms
#pragma warning restore 618
            HeartbeatConfigInterval = Defaults.HeartbeatConfigInterval; //ms
            EnableConfigHeartBeat   = Defaults.EnableConfigHeartBeat;
#pragma warning disable 618
            SerializationSettings = new JsonSerializerSettings {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
            DeserializationSettings = new JsonSerializerSettings {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
#pragma warning restore 618
            ViewRequestTimeout    = (int)Defaults.ViewRequestTimeout; //ms
            SearchRequestTimeout  = Defaults.SearchRequestTimeout;
            VBucketRetrySleepTime = Defaults.VBucketRetrySleepTime;

            //service point settings
            DefaultConnectionLimit  = Defaults.DefaultConnectionLimit; //connections
            Expect100Continue       = Defaults.Expect100Continue;
            MaxServicePointIdleTime = (int)Defaults.MaxServicePointIdleTime;

            EnableOperationTiming    = Defaults.EnableOperationTiming;
            BufferSize               = (int)Defaults.BufferSize;
            DefaultOperationLifespan = Defaults.DefaultOperationLifespan;//ms
            EnableTcpKeepAlives      = Defaults.EnableTcpKeepAlives;
            QueryFailedThreshold     = (int)Defaults.QueryFailedThreshold;

            TcpKeepAliveTime     = Defaults.TcpKeepAliveTime;
            TcpKeepAliveInterval = Defaults.TcpKeepAliveInterval;

            NodeAvailableCheckInterval = Defaults.NodeAvailableCheckInterval;//ms
            IOErrorCheckInterval       = Defaults.IOErrorCheckInterval;
            IOErrorThreshold           = Defaults.IOErrorThreshold;
            EnableDeadServiceUriPing   = Defaults.EnableDeadServiceUriPing;

            //the default serializer
            Serializer = SerializerFactory.GetSerializer();

            //the default byte converter
            Converter = ConverterFactory.GetConverter();

            //the default transcoder
            Transcoder = TranscoderFactory.GetTranscoder(this);

            //the default ioservice
            IOServiceCreator = IOServiceFactory.GetFactory(this);

            //the default connection pool creator
            ConnectionPoolCreator = ConnectionPoolFactory.GetFactory();

            //The default sasl mechanism creator
            CreateSaslMechanism = SaslFactory.GetFactory();

#if NETSTANDARD
            LoggerFactory = new LoggerFactory();
#endif

            PoolConfiguration = new PoolConfiguration(this)
            {
                BufferSize      = BufferSize,
                BufferAllocator = (p) => new BufferAllocator(p.MaxSize * p.BufferSize, p.BufferSize)
            };

            BucketConfigs = new Dictionary <string, BucketConfiguration>
            {
                { DefaultBucket, new BucketConfiguration
                  {
                      PoolConfiguration = PoolConfiguration,
                  } }
            };
            Servers = new List <Uri> {
                Defaults.Server
            };

            //Set back to default
            _operationLifespanChanged = false;
            _serversChanged           = false;
            _poolConfigurationChanged = false;
        }
        /// <summary>
        /// For synchronization with App.config or Web.configs.
        /// </summary>
        /// <param name="definition"></param>
        public ClientConfiguration(ICouchbaseClientDefinition definition)
        {
            Timer = TimingFactory.GetTimer();
            UseConnectionPooling       = definition.UseConnectionPooling;
            EnableDeadServiceUriPing   = definition.EnableDeadServiceUriPing;
            NodeAvailableCheckInterval = definition.NodeAvailableCheckInterval;
            UseSsl          = definition.UseSsl;
            SslPort         = definition.SslPort;
            ApiPort         = definition.ApiPort;
            DirectPort      = definition.DirectPort;
            MgmtPort        = definition.MgmtPort;
            HttpsMgmtPort   = definition.HttpsMgmtPort;
            HttpsApiPort    = definition.HttpsApiPort;
            ObserveInterval = definition.ObserveInterval;
            ObserveTimeout  = definition.ObserveTimeout;
            MaxViewRetries  = definition.MaxViewRetries;
#pragma warning disable 618
            ViewHardTimeout       = definition.ViewHardTimeout;
            SerializationSettings = new JsonSerializerSettings {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
            DeserializationSettings = new JsonSerializerSettings {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
#pragma warning restore 618
            EnableConfigHeartBeat    = definition.EnableConfigHeartBeat;
            HeartbeatConfigInterval  = definition.HeartbeatConfigInterval;
            ViewRequestTimeout       = definition.ViewRequestTimeout;
            Expect100Continue        = definition.Expect100Continue;
            DefaultConnectionLimit   = definition.DefaultConnectionLimit;
            MaxServicePointIdleTime  = definition.MaxServicePointIdleTime;
            EnableOperationTiming    = definition.EnableOperationTiming;
            DefaultOperationLifespan = definition.OperationLifespan;
            QueryFailedThreshold     = definition.QueryFailedThreshold;
            QueryRequestTimeout      = definition.QueryRequestTimeout;
            EnableQueryTiming        = definition.EnableQueryTiming;
            SearchRequestTimeout     = definition.SearchRequestTimeout;
            VBucketRetrySleepTime    = definition.VBucketRetrySleepTime;

            IOErrorCheckInterval = definition.IOErrorCheckInterval;
            IOErrorThreshold     = definition.IOErrorThreshold;

            //transcoders, converters, and serializers...o mai.
            Serializer = definition.Serializer != null
                ? SerializerFactory.GetSerializer(definition.Serializer)
                : SerializerFactory.GetSerializer();

            Converter = definition.Converter != null
                ? ConverterFactory.GetConverter(definition.Converter)
                : ConverterFactory.GetConverter();

            Transcoder = definition.Transcoder != null
                ? TranscoderFactory.GetTranscoder(this, definition.Transcoder)
                : TranscoderFactory.GetTranscoder(this);

            IOServiceCreator = definition.IOService != null
                ? IOServiceFactory.GetFactory(definition.IOService)
                : IOServiceFactory.GetFactory(this);

#if NETSTANDARD
            //TODO not implemented for json configs...yet, so default
            LoggerFactory = new LoggerFactory();
#endif

            //to enable tcp keep-alives
            EnableTcpKeepAlives  = definition.EnableTcpKeepAlives;
            TcpKeepAliveInterval = definition.TcpKeepAliveInterval;
            TcpKeepAliveTime     = definition.TcpKeepAliveTime;

            var keepAlivesChanged = EnableTcpKeepAlives != true ||
                                    TcpKeepAliveInterval != 1000 ||
                                    TcpKeepAliveTime != 2 * 60 * 60 * 1000;

            //The default sasl mechanism creator
            CreateSaslMechanism = SaslFactory.GetFactory();

            //NOTE: this is a global setting and applies to all instances
            IgnoreRemoteCertificateNameMismatch = definition.IgnoreRemoteCertificateNameMismatch;

            UseInterNetworkV6Addresses = definition.UseInterNetworkV6Addresses;

            List <Uri> servers;
            if (!string.IsNullOrEmpty(definition.ServerResolverType))
            {
                servers = ServerResolverUtil.GetServers(definition.ServerResolverType);
            }
            else if (definition.Servers != null && definition.Servers.Any())
            {
                servers = definition.Servers.ToList();
            }
            else
            {
                servers = new List <Uri> {
                    Defaults.Server
                };
            }

            Servers         = servers;
            _serversChanged = true;

            if (definition.ConnectionPool != null)
            {
                ConnectionPoolCreator = definition.ConnectionPool.Type != null
                    ? ConnectionPoolFactory.GetFactory(definition.ConnectionPool.Type)
                    : ConnectionPoolFactory.GetFactory();

                PoolConfiguration = new PoolConfiguration
                {
                    MaxSize             = definition.ConnectionPool.MaxSize,
                    MinSize             = definition.ConnectionPool.MinSize,
                    WaitTimeout         = definition.ConnectionPool.WaitTimeout,
                    ShutdownTimeout     = definition.ConnectionPool.ShutdownTimeout,
                    UseSsl              = UseSsl ? UseSsl : definition.ConnectionPool.UseSsl,
                    BufferSize          = definition.ConnectionPool.BufferSize,
                    BufferAllocator     = (p) => new BufferAllocator(p.MaxSize * p.BufferSize, p.BufferSize),
                    ConnectTimeout      = definition.ConnectionPool.ConnectTimeout,
                    SendTimeout         = definition.ConnectionPool.SendTimeout,
                    EnableTcpKeepAlives =
                        keepAlivesChanged ? EnableTcpKeepAlives : definition.ConnectionPool.EnableTcpKeepAlives,
                    TcpKeepAliveInterval =
                        keepAlivesChanged ? TcpKeepAliveInterval : definition.ConnectionPool.TcpKeepAliveInterval,
                    TcpKeepAliveTime     = keepAlivesChanged ? TcpKeepAliveTime : definition.ConnectionPool.TcpKeepAliveTime,
                    CloseAttemptInterval = definition.ConnectionPool.CloseAttemptInterval,
                    MaxCloseAttempts     = definition.ConnectionPool.MaxCloseAttempts,
                    ClientConfiguration  = this
                };
            }
            else
            {
                ConnectionPoolCreator = ConnectionPoolFactory.GetFactory();
                PoolConfiguration     = new PoolConfiguration(this);
            }

            BucketConfigs = new Dictionary <string, BucketConfiguration>();
            if (definition.Buckets != null)
            {
                foreach (var bucket in definition.Buckets)
                {
                    var bucketConfiguration = new BucketConfiguration
                    {
                        BucketName               = bucket.Name,
                        UseSsl                   = bucket.UseSsl,
                        Password                 = bucket.Password,
                        ObserveInterval          = bucket.ObserveInterval,
                        DefaultOperationLifespan = bucket.OperationLifespan ?? (uint)DefaultOperationLifespan,
                        ObserveTimeout           = bucket.ObserveTimeout,
                        UseEnhancedDurability    = bucket.UseEnhancedDurability
                    };

                    //By skipping the bucket specific connection pool settings we allow inheritance from clien-wide connection pool settings.
                    if (bucket.ConnectionPool != null)
                    {
                        bucketConfiguration.PoolConfiguration = new PoolConfiguration
                        {
                            MaxSize             = bucket.ConnectionPool.MaxSize,
                            MinSize             = bucket.ConnectionPool.MinSize,
                            WaitTimeout         = bucket.ConnectionPool.WaitTimeout,
                            ShutdownTimeout     = bucket.ConnectionPool.ShutdownTimeout,
                            UseSsl              = bucket.ConnectionPool.UseSsl,
                            BufferSize          = bucket.ConnectionPool.BufferSize,
                            BufferAllocator     = (p) => new BufferAllocator(p.MaxSize * p.BufferSize, p.BufferSize),
                            ConnectTimeout      = bucket.ConnectionPool.ConnectTimeout,
                            SendTimeout         = bucket.ConnectionPool.SendTimeout,
                            EnableTcpKeepAlives =
                                keepAlivesChanged ? EnableTcpKeepAlives : bucket.ConnectionPool.EnableTcpKeepAlives,
                            TcpKeepAliveInterval =
                                keepAlivesChanged ? TcpKeepAliveInterval : bucket.ConnectionPool.TcpKeepAliveInterval,
                            TcpKeepAliveTime =
                                keepAlivesChanged ? TcpKeepAliveTime : bucket.ConnectionPool.TcpKeepAliveTime,
                            CloseAttemptInterval  = bucket.ConnectionPool.CloseAttemptInterval,
                            MaxCloseAttempts      = bucket.ConnectionPool.MaxCloseAttempts,
                            UseEnhancedDurability = bucket.UseEnhancedDurability,
                            ClientConfiguration   = this
                        };
                    }
                    else
                    {
                        bucketConfiguration.PoolConfiguration        = PoolConfiguration;
                        bucketConfiguration.PoolConfiguration.UseSsl = bucketConfiguration.UseSsl;
                        bucketConfiguration.PoolConfiguration.UseEnhancedDurability = bucketConfiguration.UseEnhancedDurability;
                    }
                    BucketConfigs.Add(bucket.Name, bucketConfiguration);
                }
            }

            //Set back to default
            _operationLifespanChanged = false;
            _poolConfigurationChanged = false;
        }
Exemple #30
0
        public void TryString()
        {
            IConverter c = _factory.GetConverter(typeof(string));

            Assert.AreEqual("uhus", c.ToString("uhus"));
            Assert.AreEqual(null, c.ParseString("uhus"));
        }
        /// <summary>
        /// For synchronization with App.config or Web.configs.
        /// </summary>
        /// <param name="section"></param>
        public ClientConfiguration(CouchbaseClientSection section)
        {
            Timer = TimingFactory.GetTimer(Log);
            NodeAvailableCheckInterval = section.NodeAvailableCheckInterval;
            UseSsl                = section.UseSsl;
            SslPort               = section.SslPort;
            ApiPort               = section.ApiPort;
            DirectPort            = section.DirectPort;
            MgmtPort              = section.MgmtPort;
            HttpsMgmtPort         = section.HttpsMgmtPort;
            HttpsApiPort          = section.HttpsApiPort;
            ObserveInterval       = section.ObserveInterval;
            ObserveTimeout        = section.ObserveTimeout;
            MaxViewRetries        = section.MaxViewRetries;
            ViewHardTimeout       = section.ViewHardTimeout;
            SerializationSettings = new JsonSerializerSettings {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
            DeserializationSettings = new JsonSerializerSettings {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
            EnableConfigHeartBeat    = section.EnableConfigHeartBeat;
            HeartbeatConfigInterval  = section.HeartbeatConfigInterval;
            ViewRequestTimeout       = section.ViewRequestTimeout;
            Expect100Continue        = section.Expect100Continue;
            EnableOperationTiming    = section.EnableOperationTiming;
            DefaultOperationLifespan = section.OperationLifespan;
            QueryRequestTimeout      = section.QueryRequestTimeout;
            IOErrorCheckInterval     = section.IOErrorCheckInterval;
            IOErrorThreshold         = section.IOErrorThreshold;

            //transcoders, converters, and serializers...o mai.
            Serializer = SerializerFactory.GetSerializer(this, section.Serializer);
            Converter  = ConverterFactory.GetConverter(section.Converter);
            Transcoder = TranscoderFactory.GetTranscoder(this, section.Transcoder);

            //to enable tcp keep-alives
            EnableTcpKeepAlives  = section.EnableTcpKeepAlives;
            TcpKeepAliveInterval = section.TcpKeepAliveInterval;
            TcpKeepAliveTime     = section.TcpKeepAliveTime;

            var keepAlivesChanged = EnableTcpKeepAlives != true ||
                                    TcpKeepAliveInterval != 1000 ||
                                    TcpKeepAliveTime != 2 * 60 * 60 * 1000;

            foreach (var server in section.Servers)
            {
                Servers.Add(((UriElement)server).Uri);
                _serversChanged = true;
            }

            PoolConfiguration = new PoolConfiguration
            {
                MaxSize              = section.ConnectionPool.MaxSize,
                MinSize              = section.ConnectionPool.MinSize,
                WaitTimeout          = section.ConnectionPool.WaitTimeout,
                ShutdownTimeout      = section.ConnectionPool.ShutdownTimeout,
                UseSsl               = section.ConnectionPool.UseSsl,
                BufferSize           = section.ConnectionPool.BufferSize,
                BufferAllocator      = (p) => new BufferAllocator(p.MaxSize * p.BufferSize, p.BufferSize),
                ConnectTimeout       = section.ConnectionPool.ConnectTimeout,
                SendTimeout          = section.ConnectionPool.SendTimeout,
                EnableTcpKeepAlives  = keepAlivesChanged ? EnableTcpKeepAlives : section.ConnectionPool.EnableTcpKeepAlives,
                TcpKeepAliveInterval = keepAlivesChanged ? TcpKeepAliveInterval : section.ConnectionPool.TcpKeepAliveInterval,
                TcpKeepAliveTime     = keepAlivesChanged ? TcpKeepAliveTime : section.ConnectionPool.TcpKeepAliveTime,
                CloseAttemptInterval = section.ConnectionPool.CloseAttemptInterval,
                MaxCloseAttempts     = section.ConnectionPool.MaxCloseAttempts,
                ClientConfiguration  = this
            };

            BucketConfigs = new Dictionary <string, BucketConfiguration>();
            foreach (var bucketElement in section.Buckets)
            {
                var bucket = (BucketElement)bucketElement;
                var bucketConfiguration = new BucketConfiguration
                {
                    BucketName               = bucket.Name,
                    UseSsl                   = bucket.UseSsl,
                    Password                 = bucket.Password,
                    ObserveInterval          = bucket.ObserveInterval,
                    DefaultOperationLifespan = bucket.OperationLifespan ?? (uint)DefaultOperationLifespan,
                    ObserveTimeout           = bucket.ObserveTimeout,
                    UseEnhancedDurability    = bucket.UseEnhancedDurability
                };
                //Configuration properties (including elements) can not be null, but we can check if it was originally presnt in xml and skip it.
                //By skipping the bucket specific connection pool settings we allow inheritance from clien-wide connection pool settings.
                if (bucket.ConnectionPool.ElementInformation.IsPresent)
                {
                    bucketConfiguration.PoolConfiguration = new PoolConfiguration
                    {
                        MaxSize             = bucket.ConnectionPool.MaxSize,
                        MinSize             = bucket.ConnectionPool.MinSize,
                        WaitTimeout         = bucket.ConnectionPool.WaitTimeout,
                        ShutdownTimeout     = bucket.ConnectionPool.ShutdownTimeout,
                        UseSsl              = bucket.ConnectionPool.UseSsl,
                        BufferSize          = bucket.ConnectionPool.BufferSize,
                        BufferAllocator     = (p) => new BufferAllocator(p.MaxSize * p.BufferSize, p.BufferSize),
                        ConnectTimeout      = bucket.ConnectionPool.ConnectTimeout,
                        SendTimeout         = bucket.ConnectionPool.SendTimeout,
                        EnableTcpKeepAlives =
                            keepAlivesChanged ? EnableTcpKeepAlives : bucket.ConnectionPool.EnableTcpKeepAlives,
                        TcpKeepAliveInterval =
                            keepAlivesChanged ? TcpKeepAliveInterval : bucket.ConnectionPool.TcpKeepAliveInterval,
                        TcpKeepAliveTime      = keepAlivesChanged ? TcpKeepAliveTime : bucket.ConnectionPool.TcpKeepAliveTime,
                        CloseAttemptInterval  = bucket.ConnectionPool.CloseAttemptInterval,
                        MaxCloseAttempts      = bucket.ConnectionPool.MaxCloseAttempts,
                        UseEnhancedDurability = bucket.UseEnhancedDurability,
                        ClientConfiguration   = this
                    };
                }
                else
                {
                    bucketConfiguration.PoolConfiguration = PoolConfiguration;
                }
                BucketConfigs.Add(bucket.Name, bucketConfiguration);
            }

            //Set back to default
            _operationLifespanChanged = false;
            _poolConfigurationChanged = false;
        }