public static void TestConversion(IConverter converter, string sourceFileName, FileTypes sourceFormat, FileTypes targetFormat, bool assertSuccess)
        {
            string sourceFile = Path.GetFullPath(sourceFileName);

            // Get a temporary target file
            TempFolder tempFolder = new TempFolder();
            string targetFile = tempFolder.getFilePath("target." + targetFormat);

            // Do the conversion
            bool converted = converter.Convert(sourceFile, (int)sourceFormat, targetFile, (int)targetFormat);

            if (assertSuccess)
            {
                // Check that converter returned true
                Assert.IsTrue(converted);
                // Check that converter created the target file and it's not empty
                Assert.AreNotEqual(0, new FileInfo(targetFile).Length);
            }
            else
            {
                // Check that converter returned false
                Assert.IsFalse(converted);
            }

            // Delete the temp folder created
            tempFolder.Release();
        }
        /// <inheritdoc />
        public object Convert(object sourceValue, Type targetType, IConverter elementConverter, bool nullable)
        {
            var sourceArray = (Array)sourceValue;
            int length = sourceArray.Length;

            Type targetElementType = targetType.GetElementType();
            Array targetArray = Array.CreateInstance(targetElementType, length);

            for (int i = 0; i < length; i++)
                targetArray.SetValue(elementConverter.Convert(sourceArray.GetValue(i), targetElementType), i);

            return targetArray;
        }
Beispiel #3
0
        public override void OnEntry(MethodExecutionArgs args)
        {
            _stopWatch = Stopwatch.StartNew();
            _converter = new JsonConverter();
            var stringBuilder = new StringBuilder().AppendFormat("{0} [", args.Method.Name);

            for (var index = 0; index < args.Arguments.Count; index++)
            {
                var arg = args.Arguments.GetArgument(index);
                stringBuilder.AppendFormat("({0}: {1}) ", args.Method.GetParameters()[index].ParameterType.Name,
                    _converter.Convert(arg));
            }
            MvcApplication.Log.Info(stringBuilder.Append(']').ToString());
            base.OnEntry(args);
        }
        public static Section Add(this Section section, string contents, IConverter converter)
        {
            if (string.IsNullOrEmpty(contents))
            {
                throw new ArgumentNullException("contents");
            }
            if (converter == null)
            {
                throw new ArgumentNullException("converter");
            }

            var addAction = converter.Convert(contents);
            addAction(section);
            return section;
        }
        public void Convert_IfDictionaryContainsRowKey_PopulatesFromOfficialRowKey()
        {
            // Arrange
            const string expectedRowKey = "RK";
            IConverter <TableEntity, PocoWithRowKey> product = CreateProductUnderTest <PocoWithRowKey>();
            TableEntity entity = new TableEntity
            {
                RowKey     = expectedRowKey,
                ["RowKey"] = "UnexpectedRK"
            };
            // Act
            PocoWithRowKey actual = product.Convert(entity);

            // Assert
            Assert.NotNull(actual);
            Assert.AreSame(expectedRowKey, actual.RowKey);
        }
        public void Convert_IfRowKeyIsWriteOnly_PopulatesRowKey()
        {
            // Arrange
            const string expectedRowKey = "RK";
            IConverter <TableEntity, PocoWithWriteOnlyRowKey> product =
                CreateProductUnderTest <PocoWithWriteOnlyRowKey>();
            TableEntity entity = new TableEntity
            {
                RowKey = expectedRowKey
            };
            // Act
            PocoWithWriteOnlyRowKey actual = product.Convert(entity);

            // Assert
            Assert.NotNull(actual);
            Assert.AreSame(expectedRowKey, actual.ReadRowKey);
        }
Beispiel #7
0
        public byte[] PDF(Proceso proceso, String tipoPDF)
        {
            String html, titulo;

            if (tipoPDF.Equals("Solicitud"))
            {
                html   = TemplatePDF.SolicitudPdf(proceso);
                titulo = "PDF Solicitud";
            }
            else
            {
                html   = TemplatePDF.DeclaracionGastosPdf(proceso);
                titulo = "PDF Declaración de Gastos";
            }

            //var convertidor = new SynchronizedConverter(new PdfTools());
            //var convertidor = new BasicConverter(new PdfTools());
            var globalSettings = new GlobalSettings
            {
                ColorMode   = ColorMode.Color,
                Orientation = Orientation.Portrait,
                PaperSize   = PaperKind.Letter,

                /*ColorMode = ColorMode.Color,
                 * Orientation = Orientation.Portrait,
                 * PaperSize = PaperKind.A4,
                 * Margins = new MarginSettings { Top = 10 },*/
                DocumentTitle = titulo
            };
            var objectSettings = new ObjectSettings
            {
                PagesCount  = true,
                HtmlContent = @"" + html,
                //HtmlContent = TemplatePDF.SolicitudPdf(proceso),
                WebSettings = { DefaultEncoding = "utf-8", UserStyleSheet = Path.Combine(Directory.GetCurrentDirectory(), "assets", "estiloPDF.css") },
                //HeaderSettings = { FontName = "Arial", FontSize = 9, Right = "Page [page] of [toPage]", Line = true },
                //FooterSettings = { FontName = "Arial", FontSize = 9, Line = true, Center = "Report Footer" }
            };
            var pdf = new HtmlToPdfDocument()
            {
                GlobalSettings = globalSettings,
                Objects        = { objectSettings }
            };

            return(_converter.Convert(pdf));
        }
        public async Task <IActionResult> PrintDoc()
        {
            if (_objectSettings.HtmlContent != "" && _objectSettings.HtmlContent != null)
            {
                var pdf = new HtmlToPdfDocument
                {
                    GlobalSettings = _globalSettings,
                    Objects        = { _objectSettings }
                };

                var file = await Task.FromResult(_converter.Convert(pdf));

                return(File(file, "application/pdf"));
            }

            return(BadRequest(new ErrorModel(1, 400, "Report Not Available")));
        }
Beispiel #9
0
        public void Convert_IfETagIsReadOnly_Ignores()
        {
            // Arrange
            const string expectedPartitionKey = "PK";
            IConverter <ITableEntity, PocoWithReadOnlyETag> product = CreateProductUnderTest <PocoWithReadOnlyETag>();
            DynamicTableEntity entity = new DynamicTableEntity
            {
                PartitionKey = expectedPartitionKey
            };

            // Act
            PocoWithReadOnlyETag actual = product.Convert(entity);

            // Assert
            Assert.NotNull(actual);
            Assert.Same(expectedPartitionKey, actual.PartitionKey);
        }
Beispiel #10
0
        public void Convert_PopulatesRowKey()
        {
            // Arrange
            const string expectedRowKey = "RK";
            IConverter <ITableEntity, PocoWithRowKey> product = CreateProductUnderTest <PocoWithRowKey>();
            DynamicTableEntity entity = new DynamicTableEntity
            {
                RowKey = expectedRowKey
            };

            // Act
            PocoWithRowKey actual = product.Convert(entity);

            // Assert
            Assert.NotNull(actual);
            Assert.Same(expectedRowKey, actual.RowKey);
        }
        public void Convert_IfDictionaryContainsETag_PopulatesFromOfficialETag()
        {
            // Arrange
            const string expectedETag = "ETag";
            IConverter <TableEntity, PocoWithETag> product = CreateProductUnderTest <PocoWithETag>();
            TableEntity entity = new TableEntity
            {
                ETag     = new ETag(expectedETag),
                ["ETag"] = "UnexpectedETag"
            };
            // Act
            PocoWithETag actual = product.Convert(entity);

            // Assert
            Assert.NotNull(actual);
            Assert.AreSame(expectedETag, actual.ETag);
        }
Beispiel #12
0
        private static void AssertCanConvertNullValue <TValue>(IConverter <EntityProperty, TValue?> converter,
                                                               EntityProperty propertyWithNullValue) where TValue : struct
        {
            if (propertyWithNullValue == null)
            {
                throw new ArgumentNullException("propertyWithNullValue");
            }
            else if (propertyWithNullValue.PropertyAsObject != null)
            {
                throw new ArgumentException("propertyWithNullValue");
            }

            Assert.NotNull(converter);
            TValue?actual = converter.Convert(propertyWithNullValue);

            Assert.False(actual.HasValue);
        }
Beispiel #13
0
        private static void AssertConvertThrowsIfNullValue <TOutput>(IConverter <EntityProperty, TOutput> converter,
                                                                     EntityProperty propertyWithNullValue)
        {
            if (propertyWithNullValue == null)
            {
                throw new ArgumentNullException("propertyWithNullValue");
            }
            else if (propertyWithNullValue.PropertyAsObject != null)
            {
                throw new ArgumentException("propertyWithNullValue");
            }

            // Assert
            Assert.NotNull(converter);
            ExceptionAssert.ThrowsInvalidOperation(() => converter.Convert(propertyWithNullValue),
                                                   "Nullable object must have a value.");
        }
Beispiel #14
0
        public void Create_OtherType_CanConvert()
        {
            // Act
            IConverter <EntityProperty, Poco> converter = EntityPropertyToTConverterFactory.Create <Poco>();

            // Assert
            Assert.NotNull(converter);
            Poco original = new Poco {
                Value = "abc"
            };
            string         expected = JsonConvert.SerializeObject(original, Formatting.Indented);
            EntityProperty property = new EntityProperty(expected);
            Poco           actual   = converter.Convert(property);

            Assert.NotNull(actual);
            Assert.Equal(original.Value, actual.Value);
        }
Beispiel #15
0
        public void Convert_IfETagIsWriteOnly_PopulatesETag()
        {
            // Arrange
            string expectedETag = "abc";
            IConverter <ITableEntity, PocoWithWriteOnlyETag> product = CreateProductUnderTest <PocoWithWriteOnlyETag>();
            DynamicTableEntity entity = new DynamicTableEntity
            {
                ETag = expectedETag
            };

            // Act
            PocoWithWriteOnlyETag actual = product.Convert(entity);

            // Assert
            Assert.NotNull(actual);
            Assert.Same(expectedETag, actual.ReadETag);
        }
Beispiel #16
0
        public bool Convert(KakasiReader input, TextWriter output)
        {
            bool ret = front.Convert(input, pipeOutput);

            if (ret)
            {
                while (pipeInput.Get() >= 0)
                {
                    if (!back.Convert(pipeInput, output))
                    {
                        output.Write((char)pipeInput.Get());
                        pipeInput.Consume(1);
                    }
                }
            }
            return(ret);
        }
        public void Convert_PopulatesTimestamp()
        {
            // Arrange
            DateTimeOffset expectedTimestamp = DateTimeOffset.Now;
            IConverter <TableEntity, PocoWithTimestamp> product = CreateProductUnderTest <PocoWithTimestamp>();
            TableEntity entity = new TableEntity
            {
                Timestamp = expectedTimestamp
            };
            // Act
            PocoWithTimestamp actual = product.Convert(entity);

            // Assert
            Assert.NotNull(actual);
            Assert.AreEqual(expectedTimestamp, actual.Timestamp);
            Assert.AreEqual(expectedTimestamp.Offset, actual.Timestamp.Offset);
        }
Beispiel #18
0
        public static bool export(string file, string url)
        {
            //const string url = "http://localhost:9096/pdf/giay-yeu-cau-bao-hiem.html";
            HtmlToPdfDocument Document = new HtmlToPdfDocument()
            {
                Objects = { new ObjectSettings {
                                PageUrl = url
                            } }
            };

            byte[] buf = null;

            try
            {
                buf = converter.Convert(Document);
                Console.WriteLine("All conversions done");

                if (buf == null)
                {
                    Console.WriteLine("No exceptions were raised but wkhtmltopdf failed to convert. => Error Converting");
                    return(false);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception Occurred1: " + ex.Message);
            }

            try
            {
                //string fn = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "test.pdf");
                FileStream fs = new FileStream(file, FileMode.Create);
                fs.Write(buf, 0, buf.Length);
                fs.Close();
                //Process myProcess = new Process();
                //myProcess.StartInfo.FileName = fn;
                //myProcess.Start();
                //Console.WriteLine("OK >>> " + fn);
                return(true);
            }
            catch (Exception ex)
            {
                //Console.WriteLine("Exception Occurred2: " + ex.Message);
                return(false);
            }
        }
        public void Convert_IfTimestampIsReadOnly_Ignores()
        {
            // Arrange
            const string expectedPartitionKey = "PK";
            IConverter <TableEntity, PocoWithReadOnlyTimestamp> product =
                CreateProductUnderTest <PocoWithReadOnlyTimestamp>();
            TableEntity entity = new TableEntity
            {
                PartitionKey = expectedPartitionKey
            };
            // Act
            PocoWithReadOnlyTimestamp actual = product.Convert(entity);

            // Assert
            Assert.NotNull(actual);
            Assert.AreSame(expectedPartitionKey, actual.PartitionKey);
        }
Beispiel #20
0
        private async Task <string> SavePdf(PdfRequest request, HtmlToPdfDocument pdf)
        {
            string fileName = Path.ChangeExtension(request.FileName, ".pdf");

            using (var pdfStream = new MemoryStream(_converter.Convert(pdf)))
            {
                var httpHeader = new BlobHttpHeaders()
                {
                    ContentType     = "application/pdf",
                    ContentEncoding = "utf-8",
                };

                await _storageService.UploadFromStream(request.BlobContainer, fileName, pdfStream, httpHeader);
            }

            return(fileName);
        }
        public void Convert_IfOtherPropertyIsWriteOnly_PopulatesOtherProperty()
        {
            // Arrange
            int?expectedOtherProperty = 123;
            IConverter <TableEntity, PocoWithWriteOnlyOtherProperty> product =
                CreateProductUnderTest <PocoWithWriteOnlyOtherProperty>();
            TableEntity entity = new TableEntity
            {
                ["OtherProperty"] = expectedOtherProperty
            };
            // Act
            PocoWithWriteOnlyOtherProperty actual = product.Convert(entity);

            // Assert
            Assert.NotNull(actual);
            Assert.AreEqual(expectedOtherProperty, actual.ReadOtherProperty);
        }
Beispiel #22
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"));
            }
        }
        public void Convert_PopulatesPartitionKey()
        {
            // Arrange
            const string expectedPartitionKey = "PK";
            IConverter <PocoWithPartitionKey, ITableEntity> product = CreateProductUnderTest <PocoWithPartitionKey>();
            PocoWithPartitionKey input = new PocoWithPartitionKey
            {
                PartitionKey = expectedPartitionKey
            };

            // Act
            ITableEntity actual = product.Convert(input);

            // Assert
            Assert.NotNull(actual);
            Assert.Same(expectedPartitionKey, actual.PartitionKey);
        }
        public override IObservable <T> Load <T>(Uri uri, Options options = null)
        {
            if (!Supports <T>(uri))
            {
                throw new NotSupportedException($"Uri not supported: {uri}");
            }

            var contentType = options?.ContentType;

            GetPathAndContentType(uri, ref contentType, true);

            return(LoadFile(uri, options, contentType)
                   .ContinueWith(
                       x =>
                       _converter.Convert <T>(x.Bytes, options?.ContentType ?? x.ContentType ?? contentType,
                                              x.Encoding)));
        }
Beispiel #25
0
        public Election[] CreateElections(ElectionParticipationResult Elections, RegionResult Regions)
        {
            var t_Regions = m_RegionConverter.Convert(Regions);

            return
                (m_ElectionConverter.Convert(Elections)
                 .Select(E =>
            {
                E.Results = E.Results.Select(R =>
                {
                    R.Region.Name = _LookupRegionByCode(R.Region.Code, t_Regions)?.Name;
                    return R;
                }).ToList();
                return E;
            })
                 .ToArray());
        }
        public void Convert_IfRowKeyIsReadOnly_PopulatesRowKey()
        {
            // Arrange
            const string expectedRowKey = "RK";
            IConverter <PocoWithReadOnlyRowKey, ITableEntity> product = CreateProductUnderTest <PocoWithReadOnlyRowKey>();
            PocoWithReadOnlyRowKey input = new PocoWithReadOnlyRowKey
            {
                WriteRowKey = expectedRowKey
            };

            // Act
            ITableEntity actual = product.Convert(input);

            // Assert
            Assert.NotNull(actual);
            Assert.Same(expectedRowKey, actual.RowKey);
        }
        public void Convert_IfETagIsReadOnly_PopulatesETag()
        {
            // Arrange
            string expectedETag = "abc";
            IConverter <PocoWithReadOnlyETag, ITableEntity> product = CreateProductUnderTest <PocoWithReadOnlyETag>();
            PocoWithReadOnlyETag input = new PocoWithReadOnlyETag
            {
                WriteETag = expectedETag
            };

            // Act
            ITableEntity actual = product.Convert(input);

            // Assert
            Assert.NotNull(actual);
            Assert.Same(expectedETag, actual.ETag);
        }
        public void Convert_IfExtraPropertyIsPresentInDictionary_Ignores()
        {
            // Arrange
            const string expectedPartitionKey = "PK";
            IConverter <TableEntity, PocoWithPartitionKey> product = CreateProductUnderTest <PocoWithPartitionKey>();
            TableEntity entity = new TableEntity
            {
                PartitionKey      = expectedPartitionKey,
                ["ExtraProperty"] = "abc"
            };
            // Act
            PocoWithPartitionKey actual = product.Convert(entity);

            // Assert
            Assert.NotNull(actual);
            Assert.AreSame(expectedPartitionKey, actual.PartitionKey);
        }
Beispiel #29
0
        public async Task <IActionResult> GetById([FromRoute] Guid ticketId)
        {
            GetTicketRequest ticket;

            try
            {
                ticket = await _ticketService.GetTicketById(ticketId);
            }
            catch (Exception ex)
            {
                return(NotFound(ex));
            }

            var globalSettings = new GlobalSettings
            {
                ColorMode   = ColorMode.Color,
                Orientation = Orientation.Portrait,
                PaperSize   = PaperKind.A4,
                Margins     = new MarginSettings {
                    Top = 10
                },
                DocumentTitle = "PDF Report"
            };

            var objectSettings = new ObjectSettings
            {
                PagesCount     = true,
                HtmlContent    = PdfGenerator.GetHTMLString(ticket),
                WebSettings    = { DefaultEncoding = "utf-8", UserStyleSheet = Path.Combine(Directory.GetCurrentDirectory(), "assets", "styles.css") },
                HeaderSettings = { FontName = "Arial", FontSize = 9, Right = "Page [page] of [toPage]", Line = true },
                FooterSettings = { FontName = "Arial", FontSize = 9, Line = true, Center = "Report Footer" }
            };

            var pdf = new HtmlToPdfDocument()
            {
                GlobalSettings = globalSettings,
                Objects        = { objectSettings }
            };

            var file = _converter.Convert(pdf);

            Convert.ToBase64String(file);

            return(Ok(file));
        }
Beispiel #30
0
        /// <summary>
        /// Observes the property change and executes the given callback each time it changes. The action is also executed at initialization.
        /// </summary>
        /// <returns>The property.</returns>
        /// <param name="sourceProperty">Source property.</param>
        /// <param name="action">Action.</param>
        /// <typeparam name="TSourceProperty">The 1st type parameter.</typeparam>
        public Binder <TSource, TTarget> ObserveProperty <TSourceProperty, TTargetProperty>(Expression <Func <TSource, TSourceProperty> > sourceProperty, Action <TSource, TTarget, TTargetProperty> action, IConverter <TSourceProperty, TTargetProperty> converter = null)
        {
            converter = converter ?? Converters.Default <TSourceProperty, TTargetProperty>();

            var sourceAccessors = sourceProperty.BuildAccessors();
            Action <TSource, TTarget> onEvent = (s, t) => action(s, t, converter.Convert(sourceAccessors.Item1(s)));

            // Initialization
            onEvent(this.Source, this.Target);

            // Changes
            if (this.Source is INotifyPropertyChanged)
            {
                this.Add(new RelayEventBinding <TSource, TTarget, PropertyChangedEventArgs>(this.Source, this.Target, nameof(INotifyPropertyChanged.PropertyChanged), onEvent, (a) => (a.PropertyName == sourceAccessors.Item3)));
            }

            return(this);
        }
        public async Task <IActionResult> NewPatientAsync([FromBody] PatientDto patient)
        {
            Logger.LogDebug(nameof(NewPatientAsync));
            try
            {
                var newpatient = _patientDtoToNewpatientCoverter.Convert(patient);
                var response   = await _patientAdminService.NewPatientAsync(newpatient);

                return(Ok(response));
            }
            catch (FlurlHttpException ex)
            {
                var error = await ex.GetResponseStringAsync();

                var jsonError = JObject.Parse(error);
                return(NotFound(jsonError));
            }
        }
Beispiel #32
0
        public string ValidateAccountNumber(string input)
        {
            string accountNumber = _converter.Convert(input);

            if (CheckIsAccountNumeric(accountNumber))
            {
                if (ValidateChecksum(accountNumber))
                {
                    return(accountNumber);
                }

                return(MarkAccountNumberAsInvalid(accountNumber));
            }
            else
            {
                return(MarkAccountNumberAsIllegible(accountNumber));
            }
        }
Beispiel #33
0
        public async Task <IValueProvider> BindAsync(TableEntityContext value, ValueBindingContext context)
        {
            IStorageTable          table    = value.Table;
            IStorageTableOperation retrieve = table.CreateRetrieveOperation <DynamicTableEntity>(
                value.PartitionKey, value.RowKey);
            TableResult result = await table.ExecuteAsync(retrieve, context.CancellationToken);

            DynamicTableEntity entity = (DynamicTableEntity)result.Result;

            if (entity == null)
            {
                return(new NullEntityValueProvider <TElement>(value));
            }

            TElement userEntity = Converter.Convert(entity);

            return(new PocoEntityValueBinder <TElement>(value, entity.ETag, userEntity));
        }
Beispiel #34
0
        internal static ClientSecretIdentityModel With(this ClientSecretIdentityModel clientSecretIdentityModel, IEnumerable <Claim> claimCollection, RepositoryContext context, IConverter securityModelConverter)
        {
            NullGuard.NotNull(clientSecretIdentityModel, nameof(clientSecretIdentityModel))
            .NotNull(claimCollection, nameof(claimCollection))
            .NotNull(context, nameof(context))
            .NotNull(securityModelConverter, nameof(securityModelConverter));

            IList <ClaimModel> claimModelCollection = context.Claims.ToListAsync()
                                                      .GetAwaiter()
                                                      .GetResult();

            clientSecretIdentityModel.ClientSecretIdentityClaims = claimCollection.AsParallel()
                                                                   .Where(claim => claimModelCollection.Any(c => c.ClaimType == claim.Type))
                                                                   .Select(claim => securityModelConverter.Convert <Claim, ClientSecretIdentityClaimModel>(claim).With(clientSecretIdentityModel).With(claimModelCollection.Single(c => c.ClaimType == claim.Type)))
                                                                   .ToList();

            return(clientSecretIdentityModel);
        }
Beispiel #35
0
		private void BindParameter(ViewComponentParamAttribute paramAtt, PropertyInfo property, IConverter converter)
		{
			var compParamKey = string.IsNullOrEmpty(paramAtt.ParamName) ? property.Name : paramAtt.ParamName;

			var value = ComponentParams[compParamKey] ?? paramAtt.Default;

			if (value == null)
			{
				if (paramAtt.Required &&
				    (property.PropertyType.IsValueType || property.GetValue(this, null) == null))
				{
					throw new ViewComponentException(string.Format("The parameter '{0}' is required by " +
					                                               "the ViewComponent {1} but was not passed or had a null value",
					                                               compParamKey, GetType().Name));
				}
			}
			else
			{
				try
				{
					bool succeeded;

					var converted = converter.Convert(property.PropertyType, value.GetType(), value, out succeeded);

					if (succeeded)
					{
						property.SetValue(this, converted, null);
					}
					else
					{
						throw new Exception("Could not convert '" + value + "' to type " + property.PropertyType);
					}
				}
				catch (Exception ex)
				{
					throw new ViewComponentException(string.Format("Error trying to set value for parameter '{0}' " +
					                                               "on ViewComponent {1}: {2}", compParamKey, GetType().Name,
					                                               ex.Message), ex);
				}
			}
		}
 /// <inheritdoc />
 public object Convert(object sourceValue, Type targetType, IConverter elementConverter, bool nullable)
 {
     XPathNavigator node = (XPathNavigator)sourceValue;
     return elementConverter.Convert(node.Value, targetType);
 }
Beispiel #37
0
    public Section AddHtml(ExCSS.Stylesheet sheet, string contents, IConverter converter)
    {
        if (string.IsNullOrEmpty(contents))
        {
            throw new ArgumentNullException("contents");
        }
        if (converter == null)
        {
            throw new ArgumentNullException("converter");
        }

        Action<Section> addAction = converter.Convert(sheet, contents);
        addAction(this);
        return this;
    }
 /// <inheritdoc />
 public object Convert(object sourceValue, Type targetType, IConverter elementConverter, bool nullable)
 {
     IXPathNavigable node = (IXPathNavigable)sourceValue;
     return elementConverter.Convert(node.CreateNavigator(), targetType);
 }
 /// <inheritdoc />
 public object Convert(object sourceValue, Type targetType, IConverter elementConverter, bool nullable)
 {
     var doc = new XmlDocument();
     doc.LoadXml((string)sourceValue);
     return elementConverter.Convert(doc, targetType);
 }
        /// <summary>
        /// Convert a url to a pdf
        /// </summary>
        /// <param name="ConverterToUse">converter to use. Use TuesConverter.PdfConverter</param>
        /// <param name="ProduceTableOfContentsOutline">Product the table of contents outline</param>
        /// <param name="PaperSize">Paper Size</param>
        /// <param name="WhatToRun">What to run. Either Html or a url</param>
        /// <param name="ModeToRun">What mode is the What To Run In.</param>
        /// <param name="HtmlToConvert">Html to convert</param>
        /// <param name="MarginTop">Margin Top</param>
        /// <param name="MarginRight">Margin Right</param>
        /// <param name="MarginBottom">Margin Bottom</param>
        /// <param name="MarginLeft">Margin Left</param>
        /// <param name="UsePrintMediaCssSelectors">When running do you want to run under the css 3 print media selectors</param>
        /// <returns>pdf file byte array</returns>
        public static byte[] ConvertAUrlToPdf(IConverter ConverterToUse,
                                              bool ProduceTableOfContentsOutline,
                                              System.Drawing.Printing.PaperKind PaperSize,
                                              IWhatToRunParameter WhatToRun,
                                              double? MarginTop,
                                              double? MarginRight,
                                              double? MarginBottom,
                                              double? MarginLeft,
                                              bool UsePrintMediaCssSelectors)
        {
            //let's build up the object settings
            var ObjectSettingsToUse = WhatToRun.ToObjectSettings();

            //add anything else now
            ObjectSettingsToUse.WebSettings = new WebSettings { PrintMediaType = UsePrintMediaCssSelectors };

            //go build the main settings to use
            var DocumentSettings = new HtmlToPdfDocument
            {
                GlobalSettings =
                {
                    ProduceOutline = ProduceTableOfContentsOutline,
                    PaperSize = PaperSize,
                    Margins =
                    {
                        Top = MarginTop,
                        Right = MarginRight,
                        Bottom = MarginBottom,
                        Left = MarginLeft,
                        Unit = Unit.Inches
                    }
                },
                Objects =
                {
                    ObjectSettingsToUse
                }
            };

            //go convert and return it
            return ConverterToUse.Convert(DocumentSettings);
        }
 private void HandlePasteAction(IConverter converter)
 {
     var data = Clipboard.GetDataObject();
     // If the data is text, then set the text of the
     // TextBox to the text in the Clipboard.
     if (data != null && data.GetDataPresent(DataFormats.Text))
     {
         var expenses = converter.Convert(data.GetData(DataFormats.Text).ToString());
         foreach (var expense in expenses)
         {
             _controller.AddExpense(expense);
         }
     }
 }
Beispiel #42
0
 public override void OnSuccess(MethodExecutionArgs args)
 {
     _converter = new JsonConverter();
     MvcApplication.Log.Info(_converter.Convert(args.ReturnValue) + " [Elapsed time: " + _stopWatch.ElapsedMilliseconds + ']');
 }
 /// <inheritdoc />
 public object Convert(object sourceValue, Type targetType, IConverter elementConverter, bool nullable)
 {
     return elementConverter.Convert(sourceValue.ToString(), targetType);
 }
        public static void TestHighConcurrencyConversion(IConverter converter, string sourceFileName, FileTypes sourceFormat, FileTypes targetFormat, int concurrentConversions)
        {
            // Try to convert always the same file
            string sourceFile = Path.GetFullPath(sourceFileName);

            // Count the succeded conversion in this var
            int successes = 0;

            // Create the thread pool
            List<Thread> threads = new List<Thread>();
            for (int i = 0; i < concurrentConversions; i++)
            {
                threads.Add(new Thread(delegate () {
                    // This code will run many times in the same moment on many threads,
                    // so be very careful to not make two Office instances write the same
                    // file, or they will raise exceptions. The most problems I had 
                    // happened exactly because of this. Always make Office instance write
                    // to a clean filepath that points to a still non-existent file.
                    // Don't try anything else, 90% it will raise errors.

                    // The safest way to create a clean lonely filepath is using the 
                    // TempFolder class
                    TempFolder tempFolder = new TempFolder();
                    string targetFile = tempFolder.getFilePath("target." + targetFormat);

                    // Ok, let's do the real conversion
                    try
                    {
                        bool converted = converter.Convert(sourceFile, (int)sourceFormat, targetFile, (int)targetFormat);
                        if (converted) Interlocked.Increment(ref successes);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Conversion failed:\n" + e + "\n");
                    }
                    finally
                    {
                        // Delete the temp target folder
                        tempFolder.Release();
                    }
                }));
            }

            // Launch all the threads in the same time
            foreach (var thread in threads)
            {
                thread.Start();
            }

            // Wait for all threads completion
            foreach (var thread in threads)
            {
                thread.Join();
            }

            // Check test final result
            Assert.AreEqual(concurrentConversions, successes);
        }