logo
down
shadow

c# uwp : dispatch webview navigation and capture on each avaible logical cpu


c# uwp : dispatch webview navigation and capture on each avaible logical cpu

By : fhv1374
Date : October 17 2020, 01:08 AM
I wish this helpful for you Ok, after many trials, I have good results.
The code is here for who want to use it :
code :
public static class DispatcherTaskExtensions
    {
        public static async Task<T> RunTaskAsync<T>(this CoreDispatcher dispatcher,
            Func<Task<T>> func, CoreDispatcherPriority priority = CoreDispatcherPriority.Normal)
        {
            var taskCompletionSource = new TaskCompletionSource<T>();
            await dispatcher.RunAsync(priority, async () =>
            {
                try
                {
                    taskCompletionSource.SetResult(await func());
                }
                catch (Exception ex)
                {
                    taskCompletionSource.SetException(ex);
                }
            });
            return await taskCompletionSource.Task;
        }

        // There is no TaskCompletionSource<void> so we use a bool that we throw away.
        public static async Task RunTaskAsync(this CoreDispatcher dispatcher,
            Func<Task> func, CoreDispatcherPriority priority = CoreDispatcherPriority.Normal) =>
            await RunTaskAsync(dispatcher, async () => { await func(); return false; }, priority);
    }
    private async void GetHDMT2_Click(object sender, RoutedEventArgs e)
    {
        if (outputFolder == null)
        {
            var folderPicker = new Windows.Storage.Pickers.FolderPicker();
            folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
            folderPicker.FileTypeFilter.Add("*");

            outputFolder = await folderPicker.PickSingleFolderAsync();
            if (outputFolder != null)
            {
                Windows.Storage.AccessCache.StorageApplicationPermissions.
                FutureAccessList.AddOrReplace("PickedFolderToken", outputFolder);
            }
            else
            {
            }
        }
        if (mylat.Count > 0)
        {
            await GetImagesAsyncHD2();
        }
    }

    private async Task GetImagesAsyncHD2()
    {
        // Make a dictionary with html code string (with street view iframe inside .
        var Width = 4000;
        var Height = 2000;
        Dictionary<int,string> urls = SetUpURLListHD(Width, Height);

        //Code to estimate time for completely loading the first page (compute a time to use in await task.delay, and the size of first frame nextly used to know if image is pixelised or not (street view fisnish loading or not)
        SoftwareBitmap softwareBitmap = null;
        InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();
        BitmapDecoder decoder = null;
        var k = 0;
        WebView saveWebView = new WebView();
        saveWebView.Width = Width;
        saveWebView.Height = Height;
        TopGrid.Children.Add(saveWebView);
        var stopwatch = new Stopwatch();
        stopwatch.Start();
        long elapsed_time=0;
        saveWebView.NavigateToString(urls[0]);
        await Task.Delay(10);
        bool equals = false;
        bool findeq = false;
        int t = 0;
        int countTrue = 0;
        bool checka = false;
        List<byte[]> bytes400a = null;
        List<byte[]> bytes400b = null;
        await saveWebView.CapturePreviewToStreamAsync(stream);
        decoder = await BitmapDecoder.CreateAsync(stream);
        softwareBitmap = await decoder.GetSoftwareBitmapAsync();
        bytes400a = GetPixelsP(softwareBitmap);
        while (countTrue < 20)
        {
            await Task.Delay(50);
            if (checka)
            {
                await saveWebView.CapturePreviewToStreamAsync(stream);
                decoder = await BitmapDecoder.CreateAsync(stream);
                softwareBitmap = await decoder.GetSoftwareBitmapAsync();
                bytes400a = GetPixelsP(softwareBitmap);
                checka = false;
            }
            else
            {
                await saveWebView.CapturePreviewToStreamAsync(stream);
                decoder = await BitmapDecoder.CreateAsync(stream);
                softwareBitmap = await decoder.GetSoftwareBitmapAsync();
                bytes400b = GetPixelsP(softwareBitmap);
                checka = true;
            }
            t = t + 1;
            equals = EqualsByte(bytes400a, bytes400b);
            if (equals)
            {
                countTrue = countTrue + 1;
            }
            if ((equals) && (findeq == false))
            {
                k = t;
                elapsed_time = stopwatch.ElapsedMilliseconds;
                SlidetimeCompute.Value = elapsed_time;
                findeq = true;
            }
            if (equals == false) { findeq = false; }
        }
        stopwatch.Stop();
        var elapsed_timeForTest = stopwatch.ElapsedMilliseconds;
        await SaveSSAsync(softwareBitmap, "0");
        ulong firstFrameSize = await GetSizePicAsync("0");
        TopGrid.Children.Remove(saveWebView);
        stream.Dispose();
        softwareBitmap.Dispose();

        double timeTowait = (double)elapsed_time;
        timeTowait = Math.Round(timeTowait / 4);

        // prepare somes grids
        var nj = 7;
        List<Grid> grids = new List<Grid>();
        Grid tmpgrid0 = new Grid();
        grids.Add(tmpgrid0);
        Grid tmpgrid1 = new Grid();
        grids.Add(tmpgrid1);
        Grid tmpgrid2 = new Grid();
        grids.Add(tmpgrid2);
        Grid tmpgrid3 = new Grid();
        grids.Add(tmpgrid3);
        Grid tmpgrid4 = new Grid();
        grids.Add(tmpgrid4);
        Grid tmpgrid5 = new Grid();
        grids.Add(tmpgrid5);
        Grid tmpgrid6 = new Grid();
        grids.Add(tmpgrid6);
        Grid tmpgrid7 = new Grid();
        grids.Add(tmpgrid7);
        Grid tmpgrid8 = new Grid();
        grids.Add(tmpgrid8);
        Grid tmpgrid9 = new Grid();
        grids.Add(tmpgrid9);
        Grid tmpgrid10 = new Grid();
        grids.Add(tmpgrid10);
        Grid tmpgrid11 = new Grid();
        grids.Add(tmpgrid11);
        Grid tmpgrid12 = new Grid();
        grids.Add(tmpgrid12);
        Grid tmpgrid13 = new Grid();
        grids.Add(tmpgrid13);
        Grid tmpgrid14 = new Grid();
        grids.Add(tmpgrid14);
        Grid tmpgrid15 = new Grid();
        grids.Add(tmpgrid15);
        Grid tmpgrid16 = new Grid();
        grids.Add(tmpgrid16);

        // add tasks
        List<Task> tasks = new List<Task>();
        for (var i = 1; i < nj+1; i++)
        {
            TopGrid.Children.Add(grids[i]);
            await Task.Delay(1000);
            tasks.Add(await AddTaskAsync(i, nj, Width, Height, firstFrameSize,outputFolder, grids[i], urls, timeTowait)
                );
        }
        // await all tasks
        await Task.WhenAll(tasks);
    }

    public static async Task<Task> AddTaskAsync(int i, int nj, int width, int height, ulong firstFrameSize, StorageFolder folder, Grid grid, Dictionary<int, string> urls, double timeTowait)
    {
        var t0 = Task.Run(async () =>
        {
            for (var j = i; j < urls.Count; j = j + nj)
                await ProcessURLHD1Async(urls[j], j, width, height, firstFrameSize, folder, grid, timeTowait);
        });
        await Task.Delay(200);
        return t0;
    }

    public static async Task ProcessURLHD1Async(string url, int i, int width, int height, ulong firstFrameSize, StorageFolder folder, Grid grid, double timeTowait)
    {
        try
        {
            var Dispatcher = CoreApplication.MainView.CoreWindow.Dispatcher;
            await grid.Dispatcher.RunTaskAsync(async () =>
            {
                var saveWeb1 = new WebView(WebViewExecutionMode.SeparateThread)
                {
                    Width = width,
                    Height = height
                };
                grid.Children.Add(saveWeb1);
                saveWeb1.NavigateToString(url);
                //give street view some delay to load
                await Task.Delay((int)timeTowait*5);
                var kk = 0;
                var pixelised = true;
                SoftwareBitmap softwareBitmap = null;
                InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();
                BitmapDecoder decoder = null;

                while (pixelised == true)
                {
                    await saveWeb1.CapturePreviewToStreamAsync(stream);
                    decoder = await BitmapDecoder.CreateAsync(stream);
                    softwareBitmap = await decoder.GetSoftwareBitmapAsync();


                    StorageFile file_Save = await folder.CreateFileAsync(i + ".jpg", CreationCollisionOption.ReplaceExisting);
                    if (file_Save != null)
                    {
                        using (var streamF = await file_Save.OpenAsync(FileAccessMode.ReadWrite))
                        {
                            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(Windows.Graphics.Imaging.BitmapEncoder.JpegEncoderId, streamF);
                            encoder.SetSoftwareBitmap(softwareBitmap);
                            await encoder.FlushAsync();
                        }
                    }
                    var basicProperties = await file_Save.GetBasicPropertiesAsync();
                    ulong thissize = basicProperties.Size;
                    while (thissize < 21)
                    {
                        await Task.Delay(100);
                        basicProperties = await file_Save.GetBasicPropertiesAsync();
                        thissize = basicProperties.Size;
                    }

                    if ((thissize > 0.7 * firstFrameSize) || kk > 10)
                    {
                        pixelised = false;
                    }
                    else
                    {
                        await Task.Delay((int)timeTowait*2);
                        kk = kk + 1;
                    }
                }
                stream.Dispose();
                softwareBitmap.Dispose();
                grid.Children.Clear();

            });
        }
        catch (Exception)
        {
            throw;
        }
    }


Share : facebook icon twitter icon
C# Windows Form: How to capture Capture Function, Arrow & Navigation Keys

C# Windows Form: How to capture Capture Function, Arrow & Navigation Keys


By : Singman
Date : March 29 2020, 07:55 AM
Hope that helps Override the ProcessCmdKey() method of the form. It gets called straight from the message loop, before the keyboard message is dispatched to the control with the focus. Which is why overriding WndProc() doesn't work.
code :
    protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
        if (keyData == (Keys.Control | Keys.F)) {
            MessageBox.Show("What the Ctrl+F?");
            return true;
        }
        return base.ProcessCmdKey(ref msg, keyData);
    }
capture navigation events from WebView

capture navigation events from WebView


By : richard_frisbee
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further Create a subclass of WebViewClient and override shouldOverrideUrlLoading(). Then, attach an instance of that class to your WebView via setWebViewClient(). This works for simple hyperlinks and server-issued redirects.
How do I capture a navigation event in a webview on Windows 8?

How do I capture a navigation event in a webview on Windows 8?


By : Dinesh Sehgal
Date : March 29 2020, 07:55 AM
To fix this issue It seems there isn't any way to catch any navigation events. However, you can intercept script events called in JavaScript with window.external.notify()
Assuming the page is something you're hosting yourself, you can replace
code :
<a href="http://www.lightwoodgames.com">LINK</a>
<a href="javascript:window.external.notify('http://www.lightwoodgames.com')">LINK</a>
webview.ScriptNotify += webview_ScriptNotify;
webview.AllowedScriptNotifyUris = WebView.AnyScriptNotifyUri;

protected async void webview_ScriptNotify(object sender, NotifyEventArgs e)
{
  await Windows.System.Launcher.LaunchUriAsync(new Uri(e.Value));
}
cannot read property 'dispatch' of undefined in this.props.navigation.dispatch()

cannot read property 'dispatch' of undefined in this.props.navigation.dispatch()


By : piatikantrop
Date : March 29 2020, 07:55 AM
With these it helps I have to cutomize my drawer then I create a DrawerComponent with all items thas I need, I create a function with NavigationActions to dispatch my routes but it doesn't work. when I click on any item I have this error: cannot read property 'dispatch' of undefine
code :
{
  contentComponent: props => {
    return <DrawerComponent {...props} />;
  };
}
React navigation without navigation prop, 'dispatch undefined'

React navigation without navigation prop, 'dispatch undefined'


By : Zbigniew Pomianowski
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , In my app I set up my navigation with React-Navigation without navigation props like this: https://reactnavigation.org/docs/en/navigating-without-navigation-prop.html , You can use withNavigation. Like this:
code :
import {withNavigation} from 'react-navigation'
class SplashScreen extends Component {

    componentDidMount = () => {
        this.props.navigation.navigate('LoginScreen'); // Change it
    }

    render() {
        return (
            <View style={styles.container}>
                <Text onPress={() => this.props.navigation.navigate('LoginScreen')}>SplashScreen</Text>
            </View>
        )
    }
}

export default withNavigation(SplashScreen) // export component like this
Related Posts Related Posts :
  • Do these static application properties need to be locked?
  • How to count sum on the day of entering record
  • Web API facebook, email claim returns null
  • Service reference - why reuse types in referenced assemblies
  • How to use Group By query in Model Binding
  • Linq method based left join with multiple criteria
  • How to get exact regex for accepting Number with alphabet only?
  • Nhibernate queryover matching two IEnumerable
  • Authenticating with MVC application from a Web API authentication
  • Unit testing HttpClient with timeout
  • How to skip the VirtualStore and read files in Program Files folder?
  • To many threads waiting on semaphore
  • EF junction table with additional Id throws exception on save
  • Asp.net core model doesn't bind from form
  • Asp Net Core WebHostBuilder strange behavior during integration testing
  • Which corner case unit test would this fail?
  • Property injection not working
  • Adding Signature Line Word-Excel
  • ediFabric 6.7.7 - validation of generic EDI message
  • How to use System.Runtime.CompilerServices.RuntimeHelpers.PrepareMethod with CoreCLR and CoreFX?
  • run batch file xcopy from .NET (C#) and get the result
  • Use "Optional, DefaultParameterValue" attribute, or not?
  • Automapper Map.CreateMap not used anymore?
  • C# , MVC , EnityFramework , How to processing data
  • How can I optionally include an external library?
  • How to join tables using LINQ and navigation properties
  • Deserialize Bytes Array directly to Object in JSON.Net
  • FileNotFoundException, but catch block is not entered (Async method)
  • How does GameRanger works?
  • See the AvailableFreeSpace of drives via IP-Address
  • How to convert Sql Datetime query into Linq
  • Email sending always fails, what is wrong with my contact us code
  • how to get a part from a string with regular expression in C#
  • Mapping List`1 to Object properties
  • Handle UnauthorizedAccessException When Directory.CreateDirectory() Run
  • Whats the equivalent of C# "Click.add" for Visual Basic .net
  • C# - Need help generating a random number and using the same number multiple times in other functions
  • WPF Binding StringFormat doesn't change the output
  • Convert Expression<Func<TDocument, object>> to Expression<Func<TDocument, TOutput>>
  • How do I save current user in another table when saving objects?
  • CLOCKS_PER_SEC equivalent in C#
  • Unable to start debugging on the web server. Operation not supported. Unknown error 0x800040005
  • Why is private variable of another class accessible inside .Equals override?
  • Why does HttpClient continue to fail during subsequent retries using Polly?
  • How to create autocompletion in Excel?
  • image problems with webcamtexture
  • Most efficient way to search enumerable
  • How to pass array property in model Asp.net Core in HttpGet?
  • Installing a .NetStandard 2.0 Nuget package into a VS2015 Net 4.6.1 project
  • How to sum a field on linq that has a where clause which pulls data that returns nulls too?
  • Can we assign more RAM to a program that gets an OutOfMemoryException
  • GC Alloc for unknown reason
  • How to address "You are using an unsupported command-line flag: --ignore-certificate-errors, Stability and security
  • get image url from SharePoint genericlist with CSOM
  • Calculate difference between datetime and convert to int
  • The type or namespace name `IGraphResult` could not be found. But it's there and it works fine elsewhere
  • Using MEF in an Azure function App
  • How to listen for Pub/Sub messages in an ASP.NET Core app continuously?
  • How to store multiple checked Checkbox values in DB using ASP.NET MVC
  • What causes this amazon build error in UWP Release mode?
  • shadow
    Privacy Policy - Terms - Contact Us © soohba.com