Skip to content

Instantly share code, notes, and snippets.

@conficient
Last active October 27, 2021 15:32
Show Gist options
  • Save conficient/3051a99d1b03705619393930928ab057 to your computer and use it in GitHub Desktop.
Save conficient/3051a99d1b03705619393930928ab057 to your computer and use it in GitHub Desktop.
ICalendar link generator
@using Ical.Net
@using Ical.Net.Serialization
@* requires Ical.Net library from NUGET *@
@if(Calendar != null)
{
<a href=@dataUrl download=@Filename >@ChildContent</a>
}
@code
{
[Parameter] public Calendar Calendar { get; set; }
[Parameter] public RenderFragment ChildContent {get;set;}
[Parameter] public string Filename { get; set; } = "Calendar.ics";
string dataUrl => GetDataUrl();
string GetDataUrl()
{
var serializer = new CalendarSerializer();
var text = serializer.SerializeToString(Calendar);
var data = System.Text.Encoding.UTF8.GetBytes(text);
var base64 = Convert.ToBase64String(data);
return $"data:text/calendar;base64,{base64}";
}
}
@conficient
Copy link
Author

conficient commented Oct 27, 2021

Usage:

  1. import the Ical.Net library - this provides the ICalendar classes and logic.
  2. create the ICalendar.razor as shown in the snippet.
  3. add <ICalendar Calendar=@myCalendar Filename="test.ics">Add to Calendar</ICalendar> to a page
  4. when the myCalendar value is set the link will be valid.

Example

<ICalendar Calendar=@calendar File="example.ics">Add to Calendar</ICalendar>

C# code..

@code {

   Calendar calendar;

   protected override void OnInitialized()
   {
        var start = DateTime.Now.AddHours(1);
        var end = start.AddHours(1);

        var e = new CalendarEvent
        {
            Start = new CalDateTime(start),
            End = new CalDateTime(end),
            Description = "appointment details"
        };

        calendar= new Calendar();
        calendar.Events.Add(e);
   }
}

@conficient
Copy link
Author

I've updated the gist to use base64 encoding rather than using URL encoding, as it does not corrupt the description or summary, etc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment