Adding new legacy nuget package to recover old session serialization method

This commit is contained in:
Florian Zevedei 2024-12-02 01:56:32 +01:00
parent d72ee38349
commit 9146788ab0
5 changed files with 201 additions and 1 deletions

View File

@ -0,0 +1,41 @@
using System;
using System.IO;
using TelegramBotBase.Builder;
using TelegramBotBase.Builder.Interfaces;
namespace TelegramBotBase.Extensions.Serializer.Legacy.NewtonsoftJson
{
public static class BotBaseBuilderExtensions
{
/// <summary>
/// Using the complex version of .Net JSON, which can serialize all objects.
/// Saves in application directory.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static ILanguageSelectionStage UseNewtonsoftJson(this ISessionSerializationStage builder)
{
var path = Path.Combine(Directory.GetCurrentDirectory(), "states.json");
builder.UseNewtonsoftJson(path);
return builder as BotBaseBuilder;
}
/// <summary>
/// Using the complex version of .Net JSON, which can serialize all objects.
/// Saves in application directory.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static ILanguageSelectionStage UseNewtonsoftJson(this ISessionSerializationStage builder, String path)
{
var _stateMachine = new NewtonsoftJsonStateMachine(path);
builder.UseSerialization(_stateMachine);
return builder as BotBaseBuilder;
}
}
}

View File

@ -0,0 +1,94 @@
using System;
using System.Data;
using System.IO;
using Newtonsoft.Json;
using TelegramBotBase.Args;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
using TelegramBotBase.Interfaces;
namespace TelegramBotBase.Extensions.Serializer.Legacy.NewtonsoftJson
{
/// <summary>
/// Is used for all complex data types. Use if other default machines are not working.
/// </summary>
public class NewtonsoftJsonStateMachine : IStateMachine
{
/// <summary>
/// Will initialize the state machine.
/// </summary>
/// <param name="file">Path of the file and name where to save the session details.</param>
/// <param name="fallbackStateForm">
/// Type of Form which will be saved instead of Form which has
/// <seealso cref="Attributes.IgnoreState" /> attribute declared. Needs to be subclass of
/// <seealso cref="Form.FormBase" />.
/// </param>
/// <param name="overwrite">Declares of the file could be overwritten.</param>
public NewtonsoftJsonStateMachine(string file, Type fallbackStateForm = null, bool overwrite = true)
{
FallbackStateForm = fallbackStateForm;
if (FallbackStateForm != null && !FallbackStateForm.IsSubclassOf(typeof(FormBase)))
{
throw new ArgumentException($"{nameof(FallbackStateForm)} is not a subclass of {nameof(FormBase)}");
}
FilePath = file ?? throw new ArgumentNullException(nameof(file));
Overwrite = overwrite;
}
public string FilePath { get; set; }
public bool Overwrite { get; set; }
public Type FallbackStateForm { get; }
public StateContainer LoadFormStates()
{
try
{
var content = File.ReadAllText(FilePath);
var sc = JsonConvert.DeserializeObject<StateContainer>(content, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All,
TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple
});
return sc;
}
catch
{
}
return new StateContainer();
}
public void SaveFormStates(SaveStatesEventArgs e)
{
if (File.Exists(FilePath))
{
if (!Overwrite)
{
throw new Exception("File exists already.");
}
File.Delete(FilePath);
}
try
{
var content = JsonConvert.SerializeObject(e.States, Formatting.Indented, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All,
TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple
});
File.WriteAllText(FilePath, content);
}
catch
{
}
}
}
}

View File

@ -0,0 +1,31 @@
# TelegramBotBase.Extensions.Serializer.Legacy.NewtonsoftJson
[![NuGet version (TelegramBotBase)](https://img.shields.io/nuget/v/TelegramBotBase.Extensions.Serializer.Legacy.NewtonsoftJson.svg?style=flat-square)](https://www.nuget.org/packages/TelegramBotBase.Extensions.Serializer.Legacy.NewtonsoftJson/)
[![Telegram chat](https://img.shields.io/badge/Support_Chat-Telegram-blue.svg?style=flat-square)](https://www.t.me/tgbotbase)
[![License](https://img.shields.io/github/license/MajMcCloud/telegrambotframework.svg?style=flat-square&maxAge=2592000&label=License)](https://raw.githubusercontent.com/MajMcCloud/TelegramBotFramework/master/LICENCE.md)
[![Package Downloads](https://img.shields.io/nuget/dt/TelegramBotBase.Extensions.Serializer.Legacy.NewtonsoftJson.svg?style=flat-square&label=Package%20Downloads)](https://www.nuget.org/packages/TelegramBotBase.Extensions.Serializer.Legacy.NewtonsoftJson)
### Legacy version to recover with old dependencies using Newtonsoft.Json for session serialization
## How to use
```csharp
using TelegramBotBase.Extensions.Serializer.Legacy.NewtonsoftJson;
var bot = BotBaseBuilder
.Create()
.WithAPIKey(APIKey)
.DefaultMessageLoop()
.WithStartForm<Start>()
.NoProxy()
.OnlyStart()
.UseNewtonsoftJson()
.UseEnglish()
.Build();
bot.Start();
```

View File

@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netstandard2.0;netcoreapp3.1;net6;net7;net8;net9</TargetFrameworks>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<RepositoryUrl>https://github.com/MajMcCloud/TelegramBotFramework</RepositoryUrl>
<PackageProjectUrl>https://github.com/MajMcCloud/TelegramBotFramework</PackageProjectUrl>
<Copyright>MIT</Copyright>
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<AssemblyVersion>1.0.1</AssemblyVersion>
<FileVersion>1.0.1</FileVersion>
<Version>1.0.1</Version>
<Description>A session serializer for Newtonsoft Json.
</Description>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="TelegramBotBase" Version="6.0.0" />
</ItemGroup>
</Project>

View File

@ -38,7 +38,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TelegramBotBase.Extensions.
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TelegramBotBase.Extensions.Images.IronSoftware", "TelegramBotBase.Extensions.Images.IronSoftware\TelegramBotBase.Extensions.Images.IronSoftware.csproj", "{DC521A4C-7446-46F7-845B-AAF10EDCF8C6}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TelegramBotBase.SourceGenerators", "TelegramBotBase.SourceGenerators\TelegramBotBase.SourceGenerators.csproj", "{B78455D6-8AF2-459C-B56A-210DC89D7793}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TelegramBotBase.SourceGenerators", "TelegramBotBase.SourceGenerators\TelegramBotBase.SourceGenerators.csproj", "{B78455D6-8AF2-459C-B56A-210DC89D7793}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TelegramBotBase.Extensions.Serializer.Legacy.NewtonsoftJson", "TelegramBotBase.Extensions.Serializer.Legacy.NewtonsoftJson\TelegramBotBase.Extensions.Serializer.Legacy.NewtonsoftJson.csproj", "{21C44B20-1ED8-4BE6-A629-C2EC737C06E0}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -102,6 +104,10 @@ Global
{B78455D6-8AF2-459C-B56A-210DC89D7793}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B78455D6-8AF2-459C-B56A-210DC89D7793}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B78455D6-8AF2-459C-B56A-210DC89D7793}.Release|Any CPU.Build.0 = Release|Any CPU
{21C44B20-1ED8-4BE6-A629-C2EC737C06E0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{21C44B20-1ED8-4BE6-A629-C2EC737C06E0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{21C44B20-1ED8-4BE6-A629-C2EC737C06E0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{21C44B20-1ED8-4BE6-A629-C2EC737C06E0}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@ -118,6 +124,7 @@ Global
{689B16BC-200E-4C68-BB2E-8B209070849B} = {BFA71E3F-31C0-4FC1-A320-4DCF704768C5}
{7C55D9FF-7DC1-41D0-809C-469EBFA20992} = {E3193182-6FDA-4FA3-AD26-A487291E7681}
{DC521A4C-7446-46F7-845B-AAF10EDCF8C6} = {E3193182-6FDA-4FA3-AD26-A487291E7681}
{21C44B20-1ED8-4BE6-A629-C2EC737C06E0} = {E3193182-6FDA-4FA3-AD26-A487291E7681}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {59CB40E1-9FA7-4867-A56F-4F418286F057}