Example #1
0
        public static void EncapsulateWithExtension <TExtension>(
            this IExtensionProvider <TExtension> provider,
            Action f,
            Action <TExtension> begin,
            Action <TExtension> end,
            FailAction <TExtension> fail)
        {
            foreach (TExtension extension in provider.Extensions)
            {
                begin(extension);
            }

            try
            {
                f();
            }
            catch (Exception exception)
            {
                var exceptionToRethrow = exception;
                foreach (TExtension fileExtension in provider.Extensions)
                {
                    var e = exception;
                    fail(fileExtension, ref e);

                    exceptionToRethrow = e;
                }

                throw exceptionToRethrow;
            }

            foreach (TExtension fileExtension in provider.Extensions)
            {
                end(fileExtension);
            }
        }
Example #2
0
 public Task PrintAsync(Xamarin.Forms.WebView webView, string jobName, FailAction failAction)
 {
     Device.BeginInvokeOnMainThread(async() =>
     {
         if (string.IsNullOrWhiteSpace(jobName))
         {
             jobName = Forms9Patch.ApplicationInfoService.Name;
         }
         WebViewPrintHelper printHelper = null;
         var properties = new Dictionary <string, string>
         {
             { "class", "Forms9Patch.UWP.PrintService" },
             { "method", "PrintAsync" },
         };
         try
         {
             if (webView.Source is HtmlWebViewSource htmlSource && !string.IsNullOrWhiteSpace(htmlSource.Html))
             {
                 properties["line"] = "47";
                 printHelper        = new WebViewPrintHelper(htmlSource.Html, htmlSource.BaseUrl, jobName);
             }
             else if (webView.Source is UrlWebViewSource urlSource && !string.IsNullOrWhiteSpace(urlSource.Url))
             {
                 properties["line"] = "53";
                 printHelper        = new WebViewPrintHelper(urlSource.Url, jobName);
             }
Example #3
0
        public Task PrintAsync(string html, string jobName, FailAction failAction = FailAction.ShowAlert)
        {
            _activityIndicatorPopup = ActivityIndicatorPopup.Create();
            var taskCompletionSource = new TaskCompletionSource <ToFileResult>();

            InnerPrint(taskCompletionSource, html, jobName, failAction);
            return(taskCompletionSource.Task);
        }
Example #4
0
 /// <summary>
 /// Print HTML string
 /// </summary>
 /// <param name="html"></param>
 /// <param name="jobName"></param>
 /// <param name="failAction">What to do if there is a failure.</param>
 public static Task PrintAsync(this string html, string jobName, FailAction failAction = FailAction.ShowAlert)
 {
     _service = _service ?? DependencyService.Get <IPrintService>();
     if (_service == null)
     {
         throw new NotSupportedException("Cannot get IWebViewService: must not be supported on this platform.");
     }
     return(_service.PrintAsync(html, jobName ?? ApplicationInfoService.Name, failAction));
 }
Example #5
0
        public Task PrintAsync(WebView viewToPrint, string jobName, FailAction failAction = FailAction.ShowAlert)
        {
            try
            {
                if (Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat)
                {
                    IVisualElementRenderer existingRenderer = Platform.GetRenderer(viewToPrint);
                    if ((existingRenderer ?? Platform.CreateRendererWithContext(viewToPrint, Settings.Context)) is IVisualElementRenderer renderer)
                    {
                        Android.Webkit.WebView droidWebView = renderer.View as Android.Webkit.WebView;
                        if (droidWebView == null && renderer.View is WebViewRenderer xfWebViewRenderer)
                        {
                            droidWebView = xfWebViewRenderer.Control;
                        }
                        if (droidWebView != null)
                        {
                            droidWebView.Settings.JavaScriptEnabled = true;
                            droidWebView.Settings.DomStorageEnabled = true;
                            droidWebView.SetLayerType(Android.Views.LayerType.Software, null);

                            // Only valid for API 19+
                            if (string.IsNullOrWhiteSpace(jobName))
                            {
                                jobName = Forms9Patch.ApplicationInfoService.Name;
                            }
                            var printMgr = (PrintManager)Settings.Context.GetSystemService(Context.PrintService);
                            printMgr.Print(jobName, droidWebView.CreatePrintDocumentAdapter(jobName), null);
                        }

                        if (existingRenderer == null)
                        {
                            renderer.Dispose();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (failAction == FailAction.ShowAlert)
                {
                    Xamarin.Essentials.MainThread.BeginInvokeOnMainThread(async() =>
                    {
                        using (var toast = Forms9Patch.Alert.Create("Print Failure", e.Message))
                        {
                            await toast.WaitForPoppedAsync();
                        }
                    });
                }
                else if (failAction == FailAction.ThrowException)
                {
                    throw e;
                }
            }
            return(Task.CompletedTask);
        }
Example #6
0
        protected DateFormatTransformation(Builder builder) : this()
        {
            DateFormatTransformation instance = builder.Build();

            fieldName      = instance.fieldName;
            outputFormat   = instance.outputFormat;
            inputFormat    = instance.inputFormat;
            outputTimeZone = instance.outputTimeZone;
            inputTimeZone  = instance.inputTimeZone;
            rangeStart     = instance.rangeStart;
            rangeEnd       = instance.rangeEnd;
            onFailure      = instance.onFailure;
        }
Example #7
0
        public static TResult EncapsulateWithExtension <TExtension, TResult>(
            this IExtensionProvider <TExtension> provider,
            Func <TResult> f,
            Action <TExtension> begin,
            Action <TExtension, TResult> end,
            FailAction <TExtension> fail)
        {
            foreach (TExtension extension in provider.Extensions)
            {
                begin(extension);
            }

            try
            {
                TResult result = f();

                foreach (TExtension fileExtension in provider.Extensions)
                {
                    end(fileExtension, result);
                }

                return(result);
            }
            catch (Exception exception)
            {
                var exceptionToRethrow = exception;
                foreach (TExtension fileExtension in provider.Extensions)
                {
                    var e = exception;
                    fail(fileExtension, ref e);

                    exceptionToRethrow = e;
                }

                throw exceptionToRethrow;
            }
        }
Example #8
0
 private DateFormatTransformation() : base(null, null, null, null)
 {
     onFailure = FailAction.ReplaceWithNull;
 }
Example #9
0
 public Builder SetOnFailure(FailAction value)
 {
     instance.onFailure = value;
     return(this);
 }
Example #10
0
 /// <summary>
 /// Adds the content from file (as byte[]) to collection.  Alternative to adding file as FileInfo as the Value of a MimeItem.
 /// </summary>
 /// <returns>The bytes from file.</returns>
 /// <param name="mimeItemCollection">MIME item collection.</param>
 /// <param name="mimeType">MIME type.</param>
 /// <param name="path">File Path.</param>
 /// <param name="failAction">What to do if the method fails</param>
 public static byte[] AddBytesFromFile(this Forms9Patch.MimeItemCollection mimeItemCollection, string mimeType, string path, FailAction failAction = FailAction.ShowAlert)
 {
     if (File.ReadAllBytes(path) is byte[] byteArray && byteArray.Length > 0)
     {
         mimeItemCollection.Items.Add(new MimeItem <byte[]>(mimeType, byteArray));
         return(byteArray);
     }
     if (failAction == FailAction.ShowAlert)
     {
         using (Alert.Create(null, "Cannot access empty file [" + path + "]")) { }
     }
     else if (failAction == FailAction.ThrowException)
     {
         throw new System.Exception("Cannot access empty file [" + path + "]");
     }
     return(null);
 }
 public DeviceReliabilityServiceClient(FailAction defaultReliability)
 {
     _defaultReliability = defaultReliability;
 }
Example #12
0
        void InnerPrint(TaskCompletionSource <ToFileResult> taskCompletionSource, string html, string jobName, FailAction failAction)
        {
            try
            {
                var size    = new Size(8.5, 11);
                var webView = new Android.Webkit.WebView(Android.App.Application.Context);
                webView.Settings.JavaScriptEnabled = true;
                webView.Settings.DomStorageEnabled = true;
#pragma warning disable CS0618 // Type or member is obsolete
                webView.DrawingCacheEnabled = true;
#pragma warning restore CS0618 // Type or member is obsolete
                webView.SetLayerType(LayerType.Software, null);

                //webView.Layout(0, 0, (int)((size.Width - 0.5) * 72), (int)((size.Height - 0.5) * 72));
                webView.Layout(36, 36, (int)((PageSize.Default.Width - 0.5) * 72), (int)((PageSize.Default.Height - 0.5) * 72));

                webView.SetWebViewClient(new WebViewCallBack(taskCompletionSource, jobName, PageSize.Default, null, OnPageFinished));
                webView.LoadData(html, "text/html; charset=utf-8", "UTF-8");
            }
            catch (Exception e)
            {
                if (failAction == FailAction.ShowAlert)
                {
                    using (Forms9Patch.Alert.Create("Print Failure", e.Message)) { }
                }
                else if (failAction == FailAction.ThrowException)
                {
                    throw e;
                }
            }
        }
 public DeviceReliabilityServiceClient(FailAction defaultReliability)
 {
     _defaultReliability = defaultReliability;
 }
Example #14
0
        //UIView AppleViewToPrint;
        //WebView ViewToPrint;

        /// <summary>
        /// Print the specified viewToPrint and jobName.
        /// </summary>
        /// <param name="viewToPrint">View to print.</param>
        /// <param name="jobName">Job name.</param>
        public async Task PrintAsync(WebView viewToPrint, string jobName, FailAction failAction)
        {
            var effectApplied = viewToPrint.Effects.Any(e => e is Forms9Patch.WebViewPrintEffect);
            var actualSource  = viewToPrint.ActualSource() as WebViewSource;

            if (effectApplied && actualSource != null)
            {
                var printInfo = UIPrintInfo.PrintInfo;

                printInfo.JobName    = jobName;
                printInfo.Duplex     = UIPrintInfoDuplex.None;
                printInfo.OutputType = UIPrintInfoOutputType.General;

                var printController = UIPrintInteractionController.SharedPrintController;
                printController.ShowsPageRange = true;
                printController.ShowsPaperSelectionForLoadedPapers = true;
                printController.PrintInfo = printInfo;
                printController.Delegate  = this;

                string html = null;

                if (actualSource is HtmlWebViewSource htmlSource)
                {
                    html = htmlSource.Html;
                }
                else if (actualSource is EmbeddedHtmlViewSource embeddedHtmlViewSource)
                {
                    html = embeddedHtmlViewSource.Html;
                }

                /*
                 * else if (actualSource is UrlWebViewSource urlSource
                 *  && urlSource.Url is string url
                 *  && !string.IsNullOrWhiteSpace(url)
                 *  && url.StartsWith($"file://", StringComparison.OrdinalIgnoreCase))
                 * {
                 *  var path = url.Substring(7).TrimEnd('/');
                 *      html = System.IO.File.ReadAllText(path);
                 * }
                 */

                if (!string.IsNullOrWhiteSpace(html))
                {
                    printController.PrintFormatter = new UIMarkupTextPrintFormatter(html);
                }
                else if (actualSource is UrlWebViewSource urlSource &&
                         urlSource.Url is string url &&
                         !string.IsNullOrWhiteSpace(url) &&
                         Foundation.NSUrl.FromString(url) is Foundation.NSUrl candidateUrl &&
                         candidateUrl.Scheme != null
                         )
                {
                    //printController.PrintingItem = printData;
                    //printController.PrintingItem = new NSUrl(url);
                    if (await Forms9Patch.ToPdfService.ToPdfAsync(viewToPrint, "Forms9Patch.PdfPrintFile") is ToFileResult result)
                    {
                        if (result.IsError)
                        {
                            using (var alert = Forms9Patch.Alert.Create("Print File Generation Error", result.Result))
                            {
                                await alert.WaitForPoppedAsync();
                            }
                            return;
                        }
                        else
                        {
                            var fileUrl = NSUrl.CreateFileUrl(result.Result, null);
                            printController.PrintingItem = fileUrl;
                        }
                    }
                }
                else
                {
                    printController.PrintFormatter = Platform.CreateRenderer(viewToPrint).NativeView.ViewPrintFormatter;
                }

                printController.Present(true, (printInteractionController, completed, error) =>
                {
                    System.Diagnostics.Debug.WriteLine(GetType() + "." + P42.Utils.ReflectionExtensions.CallerMemberName() + ": PRESENTED completed[" + completed + "] error[" + error + "]");
                });
            }
 /// <summary>
 /// Adds the content from file (as byte[]) to collection.  Alternative to adding file as FileInfo as the Value of a MimeItem.
 /// </summary>
 /// <returns>The bytes from file.</returns>
 /// <param name="mimeItemCollection">MIME item collection.</param>
 /// <param name="mimeType">MIME type.</param>
 /// <param name="path">File Path.</param>
 /// <param name="failAction">What to do if the method fails</param>
 public static byte[] AddBytesFromFile(this Forms9Patch.MimeItemCollection mimeItemCollection, string mimeType, string path, FailAction failAction = FailAction.ShowAlert)
 {
     if (File.ReadAllBytes(path) is byte[] byteArray && byteArray.Length > 0)
     {
         mimeItemCollection.Items.Add(new MimeItem <byte[]>(mimeType, byteArray));
         return(byteArray);
     }
     if (failAction == FailAction.ShowAlert)
     {
         Xamarin.Essentials.MainThread.BeginInvokeOnMainThread(async() =>
         {
             using (var toast = Alert.Create(null, "Cannot access empty file [" + path + "]"))
             {
                 await toast.WaitForPoppedAsync();
             }
         });
     }
     else if (failAction == FailAction.ThrowException)
     {
         throw new System.Exception("Cannot access empty file [" + path + "]");
     }
     return(null);
 }