0 Comments

AngleSharp is a HTML parser library for .NET. Previously I’ve mainly used Html Agility Pack for parsing, but AngleSharp seems to be getting quite much traction nowadays.

I had a scenario where I wanted to use AngleSharp to wrap all the images with links. Given the following HTML:

<img src="2019-02-17-13-10-47.png" class="img-fluid" alt="Test stuff">

I wanted to transform it to this:

<a href="2019-02-17-13-10-47.png" class="lightbox">
	<img src="2019-02-17-13-10-47.png" class="img-fluid" alt="Test stuff">
</a>

Here’s how you can do this:

  1. Create the new link wrapper
  2. Get image’s original parent element
  3. Replace the image parent element’s image with the link wrapper
  4. Set image as the child of the wrapper

In C# using AngleSharp:

                var wrapperLink = document.CreateElement("a");
                wrapperLink.SetAttribute("href", image.GetAttribute("src"));
                wrapperLink.ClassName = "lightbox";

                var imageParent = image.ParentElement;
                imageParent.ReplaceChild(wrapperLink, image);
                wrapperLink.AppendChild(image);
Where document is of type IHtmlDocument and image is of type IHtmlImageElement.

0 Comments

I’ve been doing some work converting Graze to .NET Core. Graze is a static web site generator which uses Razor and is built using .NET Framework.

One of the problems I hit when converting a class library to .NET Standard 2.0 was the following error at compile time:

Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create'

Graze uses dynamics in some places and turns out this error is related to dynamic keyword. To fix it I had to include I just had to include Microsoft.CSharp from Nuget.

Your Razor Components can implement interfaces even if you’re not using code-behind files. Given that a basic components looks like the following:

@page "/"

<h1>Hello, world!</h1>

Welcome to your new app.

@functions {

}

It’s not directly obvious how the implementation happens. But for that, we have the “@implements” directive:

@page "/"
@implements IMainPage

We can do the actual implementation in the functions-block:

@functions {
    public void UpdateText()
    {
        // Implementation logic
    }
}

Here’s a full example:

@page "/"
@implements IMainPage

<h1>Hello, world!</h1>

Welcome to your new app.

@functions {
    public void UpdateText()
    {
        // Implementation logic
    }
}

In some child & parent component situations it would be good if you could render or at least get an access to an instance of a Razor Component.

Given the following scenario where we try to render an instance of the Counter-component inside the Index-component:

<h1>Hello, world!</h1>

Welcome to your new app.

@counterInstance

@functions{
    Counter counterInstance = new Counter();
}

The following doesn’t work as it only draws the type name of the component:

image

There are couple options around this.

Capturing reference

In many (if not most?) cases you should let Razor Components to take care of creating the instance of your component and then use the “ref” keyword to capture the rendered instance:

<h1>Hello, world!</h1>

Welcome to your new app.

@DrawCounter()

@functions{

    private Counter _myCounter = null;

    RenderFragment DrawCounter()
    {
        return new RenderFragment(builder =>
        {
            builder.OpenComponent<Counter>(0);
            builder.AddComponentReferenceCapture(1, inst => { _myCounter = (Counter)inst; });
            builder.CloseComponent();
        });
    }

Reflection

If you really want, you can access the RenderFragment of the instance using reflection and then draw that:

Welcome to your new app.

@RenderContent(counterInstance)

@functions{
    Counter counterInstance = new Counter();

    RenderFragment RenderContent(ComponentBase instance)
    {
        var fragmentField = GetPrivateField(instance.GetType(), "_renderFragment");

        var value = (RenderFragment)fragmentField.GetValue(instance);

        return value;
    }

    //https://stackoverflow.com/a/48551735/66988
    private static FieldInfo GetPrivateField(Type t, String name)
    {
        const BindingFlags bf = BindingFlags.Instance |
                                BindingFlags.NonPublic |
                                BindingFlags.DeclaredOnly;

        FieldInfo fi;
        while ((fi = t.GetField(name, bf)) == null && (t = t.BaseType) != null) ;

        return fi;
    }

0 Comments

Blazor.EventAggregator is a lightweight Event Aggregator for Razor Components. Razor Components (and formerly known as Blazor) is an upcoming technology included in ASP.NET Core 3.0 (currently in Preview 2).

Event aggregator is used for indirect component to component communication. In event aggregator pattern you have message/event publishers and subscribers. In the case of Razor Components, component can publish its events and other component(s) can react to those events.

Note:

Blazor.EventAggregator is completely based on the work done in Caliburn.Micro. The source code was copied from it and then altered to work with Blazor.

Getting Started

First register EventAggregator as singleton in app’s ConfigureServices:

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton<EventAggregator.Blazor.IEventAggregator, EventAggregator.Blazor.EventAggregator>();
        }

The rest depends on if you’re using components with code-behinds (inheritance) or without inheritance. The following guidance is for code-behind scenarios. I’ll add another example of using event aggregator without the code-behind model.

Creating the publisher

To create an event publishing component, first inject IEventAggregator:

        [Inject]
        private IEventAggregator _eventAggregator { get; set; }

Then publish the message when something interesting happens:

await _eventAggregator.PublishAsync(new CounterIncreasedMessage());

Here’s a full example of a publisher:

    public class CounterComponent : ComponentBase
    {
        [Inject]
        private IEventAggregator _eventAggregator { get; set; }

        public int currentCount = 0;

        public async Task IncrementCountAsync()
        {
            currentCount++;
            await _eventAggregator.PublishAsync(new CounterIncreasedMessage());
        }
    }

    public class CounterIncreasedMessage
    {
    }

Creating the subscriber

To create an event subscriber, also start by injecting IEventAggregator:

        [Inject]
        private IEventAggregator _eventAggregator { get; set; }

Then make sure to add and implement the IHandle<TMessageType> interface for all the event’s your component is interested in:

public class CounterListenerComponent : ComponentBase, IHandle<CounterIncreasedMessage>
...
public Task HandleAsync(CounterIncreasedMessage message)
{
    currentCount += 1;
    return Task.CompletedTask;
}

Here’s full example of a subscriber:

    public class CounterListenerComponent : ComponentBase, IHandle<CounterIncreasedMessage>
    {
        [Inject]
        private IEventAggregator _eventAggregator { get; set; }

        public int currentCount = 0;

        protected override void OnInit()
        {
            _eventAggregator.Subscribe(this);
        }

        public Task HandleAsync(CounterIncreasedMessage message)
        {
            currentCount += 1;
            return Task.CompletedTask;
        }
    }

Samples

The project site contains a full working sample of the code-behind model in the samples-folder.

Project Location

Source code is available through GitHub: https://github.com/mikoskinen/Blazor.EventAggregator

Requirements

The library has been developed and tested using the following tools:

  • .NET Core 3.0 Preview 2
  • ASP.NET Core 3.0 Preview 2
  • Visual Studio 2019

Acknowledgements

Work is based on the code available in Caliburn.Micro.