fix: some build & linter warnings

This commit is contained in:
ZavaruKitsu 2022-10-08 19:15:51 +03:00
parent 3f0d109fe2
commit a731e2a8d0
159 changed files with 2738 additions and 3742 deletions

View File

@ -1,26 +1,24 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers; using System.Timers;
using AsyncFormUpdates.forms;
using TelegramBotBase;
using TelegramBotBase.Builder; using TelegramBotBase.Builder;
namespace AsyncFormUpdates namespace AsyncFormUpdates
{ {
class Program internal class Program
{ {
static TelegramBotBase.BotBase bot = null; private static BotBase __bot;
static void Main(string[] args) private static void Main(string[] args)
{ {
String apiKey = "APIKey"; var apiKey = "APIKey";
bot = BotBaseBuilder.Create() __bot = BotBaseBuilder.Create()
.QuickStart<forms.Start>(apiKey) .QuickStart<Start>(apiKey)
.Build(); .Build();
bot.Start(); __bot.Start();
var timer = new Timer(5000); var timer = new Timer(5000);
@ -30,19 +28,19 @@ namespace AsyncFormUpdates
Console.ReadLine(); Console.ReadLine();
timer.Stop(); timer.Stop();
bot.Stop(); __bot.Stop();
} }
private static async void Timer_Elapsed(object sender, ElapsedEventArgs e) private static async void Timer_Elapsed(object sender, ElapsedEventArgs e)
{ {
foreach(var s in bot.Sessions.SessionList) foreach(var s in __bot.Sessions.SessionList)
{ {
//Only for AsyncUpdateForm //Only for AsyncUpdateForm
if (s.Value.ActiveForm.GetType() != typeof(forms.AsyncFormUpdate) && s.Value.ActiveForm.GetType() != typeof(forms.AsyncFormEdit)) if (s.Value.ActiveForm.GetType() != typeof(AsyncFormUpdate) && s.Value.ActiveForm.GetType() != typeof(AsyncFormEdit))
continue; continue;
await bot.InvokeMessageLoop(s.Key); await __bot.InvokeMessageLoop(s.Key);
} }

View File

@ -1,5 +1,4 @@
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden // Allgemeine Informationen über eine Assembly werden über die folgenden

View File

@ -1,8 +1,4 @@
using System; using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Attributes; using TelegramBotBase.Attributes;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Form; using TelegramBotBase.Form;
@ -11,19 +7,19 @@ namespace AsyncFormUpdates.forms
{ {
public class AsyncFormEdit : FormBase public class AsyncFormEdit : FormBase
{ {
[SaveState] [SaveState] private int _counter;
int counter = 0;
int MessageId = 0; private int _messageId;
public override async Task Load(MessageResult message) public override Task Load(MessageResult message)
{ {
counter++; _counter++;
return Task.CompletedTask;
} }
public override async Task Action(MessageResult message) public override async Task Action(MessageResult message)
{ {
await message.ConfirmAction(""); await message.ConfirmAction();
switch (message.RawData ?? "") switch (message.RawData ?? "")
{ {
@ -41,14 +37,14 @@ namespace AsyncFormUpdates.forms
var bf = new ButtonForm(); var bf = new ButtonForm();
bf.AddButtonRow("Back", "back"); bf.AddButtonRow("Back", "back");
if (MessageId != 0) if (_messageId != 0)
{ {
await Device.Edit(MessageId, $"Your current count is at: {counter}", bf); await Device.Edit(_messageId, $"Your current count is at: {_counter}", bf);
} }
else else
{ {
var m = await Device.Send($"Your current count is at: {counter}", bf, disableNotification: true); var m = await Device.Send($"Your current count is at: {_counter}", bf, disableNotification: true);
MessageId = m.MessageId; _messageId = m.MessageId;
} }
} }

View File

@ -1,8 +1,4 @@
using System; using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Attributes; using TelegramBotBase.Attributes;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Form; using TelegramBotBase.Form;
@ -11,18 +7,18 @@ namespace AsyncFormUpdates.forms
{ {
public class AsyncFormUpdate : AutoCleanForm public class AsyncFormUpdate : AutoCleanForm
{ {
[SaveState] [SaveState] private int _counter;
int counter = 0;
public override async Task Load(MessageResult message) public override Task Load(MessageResult message)
{ {
counter++; _counter++;
return Task.CompletedTask;
} }
public override async Task Action(MessageResult message) public override async Task Action(MessageResult message)
{ {
await message.ConfirmAction(""); await message.ConfirmAction();
switch (message.RawData ?? "") switch (message.RawData ?? "")
{ {
@ -40,7 +36,7 @@ namespace AsyncFormUpdates.forms
var bf = new ButtonForm(); var bf = new ButtonForm();
bf.AddButtonRow("Back", "back"); bf.AddButtonRow("Back", "back");
await Device.Send($"Your current count is at: {counter}", bf, disableNotification: true); await Device.Send($"Your current count is at: {_counter}", bf, disableNotification: true);
} }

View File

@ -1,8 +1,4 @@
using System; using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Form; using TelegramBotBase.Form;
@ -14,7 +10,7 @@ namespace AsyncFormUpdates.forms
public override async Task Action(MessageResult message) public override async Task Action(MessageResult message)
{ {
await message.ConfirmAction(""); await message.ConfirmAction();
switch (message.RawData ?? "") switch (message.RawData ?? "")
{ {

View File

@ -1,17 +1,18 @@
using System; using System;
using JoinHiderBot.forms;
using TelegramBotBase.Builder; using TelegramBotBase.Builder;
namespace JoinHiderBot namespace JoinHiderBot
{ {
class Program internal class Program
{ {
static void Main(string[] args) private static void Main(string[] args)
{ {
String apiKey = ""; var apiKey = "";
var bot = BotBaseBuilder.Create() var bot = BotBaseBuilder.Create()
.QuickStart<forms.Start>(apiKey) .QuickStart<Start>(apiKey)
.Build(); .Build();
bot.Start(); bot.Start();

View File

@ -1,7 +1,5 @@
using System; using System.Threading.Tasks;
using System.Collections.Generic; using Telegram.Bot.Types.Enums;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Args; using TelegramBotBase.Args;
using TelegramBotBase.Form; using TelegramBotBase.Form;
@ -12,13 +10,13 @@ namespace JoinHiderBot.forms
public override async Task OnMemberChanges(MemberChangeEventArgs e) public override async Task OnMemberChanges(MemberChangeEventArgs e)
{ {
if (e.Type != Telegram.Bot.Types.Enums.MessageType.ChatMembersAdded && e.Type != Telegram.Bot.Types.Enums.MessageType.ChatMemberLeft) if (e.Type != MessageType.ChatMembersAdded && e.Type != MessageType.ChatMemberLeft)
return; return;
var m = e.Result.Message; var m = e.Result.Message;
await this.Device.DeleteMessage(m); await Device.DeleteMessage(m);
} }
} }

View File

@ -1,7 +1,4 @@
using System; using System.Threading.Tasks;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Form; using TelegramBotBase.Form;
@ -11,7 +8,7 @@ namespace JoinHiderBot.forms
{ {
public override async Task<bool> Open(MessageResult e) public override async Task<bool> Open(MessageResult e)
{ {
await this.Device.Send("This bot works only in groups."); await Device.Send("This bot works only in groups.");
return true; return true;
} }
@ -20,7 +17,7 @@ namespace JoinHiderBot.forms
{ {
var gmf = new GroupManageForm(); var gmf = new GroupManageForm();
await this.NavigateTo(gmf); await NavigateTo(gmf);
return true; return true;
} }

View File

@ -1,17 +1,19 @@
using System; using System;
using SystemCommandsBot.config;
using SystemCommandsBot.forms;
using TelegramBotBase.Builder; using TelegramBotBase.Builder;
namespace SystemCommandsBot namespace SystemCommandsBot
{ {
class Program internal class Program
{ {
public static config.Config BotConfig { get; set; } public static Config BotConfig { get; set; }
static void Main(string[] args) private static void Main(string[] args)
{ {
BotConfig = config.Config.load(); BotConfig = Config.Load();
if (BotConfig.ApiKey == null || BotConfig.ApiKey.Trim() == "") if (BotConfig.ApiKey == null || BotConfig.ApiKey.Trim() == "")
{ {
@ -21,7 +23,7 @@ namespace SystemCommandsBot
} }
var bot = BotBaseBuilder.Create() var bot = BotBaseBuilder.Create()
.QuickStart<forms.StartForm>(BotConfig.ApiKey) .QuickStart<StartForm>(BotConfig.ApiKey)
.Build(); .Build();
bot.Start(); bot.Start();

View File

@ -1,28 +1,23 @@
using System; namespace SystemCommandsBot.commands
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace SystemCommandsBot.commands
{ {
public class Commando public class Commando
{ {
public int ID { get; set; } public int Id { get; set; }
public String Title { get; set; } public string Title { get; set; }
public String ShellCmd { get; set; } public string ShellCmd { get; set; }
public bool Enabled { get; set; } = true; public bool Enabled { get; set; } = true;
public String Action { get; set; } public string Action { get; set; }
public bool UseShell { get; set; } = true; public bool UseShell { get; set; } = true;
public int? MaxInstances { get; set; } public int? MaxInstances { get; set; }
public String ProcName public string ProcName
{ {
get;set; get;set;
} }

View File

@ -1,36 +1,37 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Text; using Newtonsoft.Json;
using SystemCommandsBot.commands;
namespace SystemCommandsBot.config namespace SystemCommandsBot.config
{ {
public class Config public class Config
{ {
public String Password { get; set; } public string Password { get; set; }
public String ApiKey { get; set; } public string ApiKey { get; set; }
public List<commands.Commando> Commandos { get; set; } public List<Commando> Commandos { get; set; }
public Config() public Config()
{ {
this.Commandos = new List<commands.Commando>(); Commandos = new List<Commando>();
} }
public void loadDefaultValues() public void LoadDefaultValues()
{ {
this.ApiKey = ""; ApiKey = "";
this.Commandos.Add(new commands.Commando() { ID = 0, Enabled = true, Title = "Test Befehl", ShellCmd = "explorer.exe", Action = "start", MaxInstances = 2 }); Commandos.Add(new Commando { Id = 0, Enabled = true, Title = "Test Befehl", ShellCmd = "explorer.exe", Action = "start", MaxInstances = 2 });
} }
public static Config load() public static Config Load()
{ {
try try
{ {
return load(AppContext.BaseDirectory + "config\\default.cfg"); return Load(AppContext.BaseDirectory + "config\\default.cfg");
} }
@ -42,16 +43,16 @@ namespace SystemCommandsBot.config
} }
public static Config load(String path) public static Config Load(string path)
{ {
try try
{ {
var cfg = Newtonsoft.Json.JsonConvert.DeserializeObject<Config>(File.ReadAllText(path)) as Config; var cfg = JsonConvert.DeserializeObject<Config>(File.ReadAllText(path));
return cfg; return cfg;
} }
catch (DirectoryNotFoundException ex) catch (DirectoryNotFoundException)
{ {
DirectoryInfo di = new DirectoryInfo(path); var di = new DirectoryInfo(path);
if (!Directory.Exists(di.Parent.FullName)) if (!Directory.Exists(di.Parent.FullName))
{ {
@ -59,15 +60,15 @@ namespace SystemCommandsBot.config
} }
var cfg = new Config(); var cfg = new Config();
cfg.loadDefaultValues(); cfg.LoadDefaultValues();
cfg.save(path); cfg.Save(path);
return cfg; return cfg;
} }
catch (FileNotFoundException ex) catch (FileNotFoundException)
{ {
var cfg = new Config(); var cfg = new Config();
cfg.loadDefaultValues(); cfg.LoadDefaultValues();
cfg.save(path); cfg.Save(path);
return cfg; return cfg;
} }
catch(Exception ex) catch(Exception ex)
@ -77,11 +78,11 @@ namespace SystemCommandsBot.config
return null; return null;
} }
public void save(String path) public void Save(string path)
{ {
try try
{ {
File.WriteAllText(path, Newtonsoft.Json.JsonConvert.SerializeObject(this)); File.WriteAllText(path, JsonConvert.SerializeObject(this));
} }
catch catch
{ {

View File

@ -1,31 +1,29 @@
using System; using System;
using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace SystemCommandsBot.forms namespace SystemCommandsBot.forms
{ {
public class CmdForm : TelegramBotBase.Form.AutoCleanForm public class CmdForm : AutoCleanForm
{ {
public DateTime ExpiresAt { get; set; } public DateTime ExpiresAt { get; set; }
public int? MessageId { get; set; } public int? MessageId { get; set; }
public override async Task Load(MessageResult message) public override Task Load(MessageResult message)
{ {
return Task.CompletedTask;
} }
public override async Task Action(MessageResult message) public override async Task Action(MessageResult message)
{ {
var btn = message.RawData; var btn = message.RawData;
int id = -1; var id = -1;
if (!int.TryParse(btn, out id)) if (!int.TryParse(btn, out id))
{ {
@ -33,10 +31,10 @@ namespace SystemCommandsBot.forms
return; return;
} }
var cmd = Program.BotConfig.Commandos.Where(a => a.Enabled && a.ID == id).FirstOrDefault(); var cmd = Program.BotConfig.Commandos.Where(a => a.Enabled && a.Id == id).FirstOrDefault();
if (cmd == null) if (cmd == null)
{ {
await this.Device.Send("Cmd nicht verfügbar."); await Device.Send("Cmd nicht verfügbar.");
return; return;
} }
@ -46,14 +44,14 @@ namespace SystemCommandsBot.forms
{ {
case "start": case "start":
FileInfo fi = new FileInfo(cmd.ShellCmd); var fi = new FileInfo(cmd.ShellCmd);
if (cmd.MaxInstances != null && cmd.MaxInstances >= 0) if (cmd.MaxInstances != null && cmd.MaxInstances >= 0)
{ {
if (Process.GetProcessesByName(cmd.ProcName).Count() >= cmd.MaxInstances) if (Process.GetProcessesByName(cmd.ProcName).Count() >= cmd.MaxInstances)
{ {
await this.Device.Send("Anwendung läuft bereits."); await Device.Send("Anwendung läuft bereits.");
await message.ConfirmAction("Anwendung läuft bereits."); await message.ConfirmAction("Anwendung läuft bereits.");
return; return;
@ -61,14 +59,16 @@ namespace SystemCommandsBot.forms
} }
ProcessStartInfo psi = new ProcessStartInfo(); var psi = new ProcessStartInfo
psi.FileName = cmd.ShellCmd; {
psi.WorkingDirectory = fi.DirectoryName; FileName = cmd.ShellCmd,
psi.UseShellExecute = cmd.UseShell; WorkingDirectory = fi.DirectoryName,
UseShellExecute = cmd.UseShell
};
Process.Start(psi); Process.Start(psi);
await this.Device.Send(fi.Name + " wurde gestarted."); await Device.Send(fi.Name + " wurde gestarted.");
await message.ConfirmAction(fi.Name + " wurde gestarted."); await message.ConfirmAction(fi.Name + " wurde gestarted.");
@ -76,9 +76,9 @@ namespace SystemCommandsBot.forms
case "kill": case "kill":
FileInfo fi2 = new FileInfo(cmd.ShellCmd); var fi2 = new FileInfo(cmd.ShellCmd);
String pros = fi2.Name.Replace(fi2.Extension, ""); var pros = fi2.Name.Replace(fi2.Extension, "");
var proc = Process.GetProcessesByName(pros).ToList(); var proc = Process.GetProcessesByName(pros).ToList();
@ -94,7 +94,7 @@ namespace SystemCommandsBot.forms
} }
} }
await this.Device.Send(fi2.Name + " wurde beendet."); await Device.Send(fi2.Name + " wurde beendet.");
await message.ConfirmAction(fi2.Name + " wurde beendet."); await message.ConfirmAction(fi2.Name + " wurde beendet.");
@ -102,9 +102,9 @@ namespace SystemCommandsBot.forms
case "restart": case "restart":
FileInfo fi3 = new FileInfo(cmd.ShellCmd); var fi3 = new FileInfo(cmd.ShellCmd);
String pros2 = fi3.Name.Replace(fi3.Extension, ""); var pros2 = fi3.Name.Replace(fi3.Extension, "");
var proc2 = Process.GetProcessesByName(pros2).ToList(); var proc2 = Process.GetProcessesByName(pros2).ToList();
@ -120,17 +120,19 @@ namespace SystemCommandsBot.forms
} }
} }
FileInfo fi4 = new FileInfo(cmd.ShellCmd); var fi4 = new FileInfo(cmd.ShellCmd);
ProcessStartInfo psi2 = new ProcessStartInfo(); var psi2 = new ProcessStartInfo
psi2.FileName = cmd.ShellCmd; {
psi2.WorkingDirectory = fi4.DirectoryName; FileName = cmd.ShellCmd,
WorkingDirectory = fi4.DirectoryName
};
psi2.FileName = cmd.ShellCmd; psi2.FileName = cmd.ShellCmd;
psi2.UseShellExecute = cmd.UseShell; psi2.UseShellExecute = cmd.UseShell;
Process.Start(psi2); Process.Start(psi2);
await this.Device.Send(fi3.Name + " wurde neugestarted."); await Device.Send(fi3.Name + " wurde neugestarted.");
await message.ConfirmAction(fi3.Name + " wurde neugestarted."); await message.ConfirmAction(fi3.Name + " wurde neugestarted.");
@ -151,15 +153,13 @@ namespace SystemCommandsBot.forms
public override async Task Render(MessageResult message) public override async Task Render(MessageResult message)
{ {
if (this.MessageId == null) if (MessageId == null)
{ {
var buttons = Program.BotConfig.Commandos.Where(a => a.Enabled).Select(a => new ButtonBase(a.Title, a.ID.ToString())); var buttons = Program.BotConfig.Commandos.Where(a => a.Enabled).Select(a => new ButtonBase(a.Title, a.Id.ToString()));
ButtonForm bf = new ButtonForm(); var bf = new ButtonForm();
bf.AddSplitted(buttons, 1); bf.AddSplitted(buttons, 1);
await this.Device.Send("Deine Optionen", bf); await Device.Send("Deine Optionen", bf);
return;
} }

View File

@ -1,40 +1,39 @@
using System; using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Form;
namespace SystemCommandsBot.forms namespace SystemCommandsBot.forms
{ {
public class StartForm : TelegramBotBase.Form.FormBase public class StartForm : FormBase
{ {
public String Password { get; set; } public string Password { get; set; }
public override async Task Load(MessageResult message) public override Task Load(MessageResult message)
{ {
var inp = message.MessageText; var inp = message.MessageText;
if (Program.BotConfig.Password == inp) if (Program.BotConfig.Password == inp)
{ {
this.Password = inp; Password = inp;
} }
return Task.CompletedTask;
} }
public override async Task Render(MessageResult message) public override async Task Render(MessageResult message)
{ {
if (this.Password == null || this.Password.Trim() == "") if (Password == null || Password.Trim() == "")
{ {
await this.Device.Send("Bitte gib dein Passwort an."); await Device.Send("Bitte gib dein Passwort an.");
return; return;
} }
var cmd = new forms.CmdForm(); var cmd = new CmdForm();
cmd.ExpiresAt = DateTime.Now.AddDays(14); cmd.ExpiresAt = DateTime.Now.AddDays(14);
await this.NavigateTo(cmd); await NavigateTo(cmd);
} }

View File

@ -1,12 +1,11 @@
using System; using System.Drawing;
using System.Drawing;
using System.Drawing.Imaging; using System.Drawing.Imaging;
using System.IO; using System.IO;
using System.Threading.Tasks; using System.Threading.Tasks;
using Telegram.Bot.Types.InputFiles;
using Telegram.Bot.Types; using Telegram.Bot.Types;
using TelegramBotBase.Sessions; using Telegram.Bot.Types.InputFiles;
using TelegramBotBase.Form; using TelegramBotBase.Form;
using TelegramBotBase.Sessions;
namespace TelegramBotBase.Extensions.Images namespace TelegramBotBase.Extensions.Images
{ {
@ -14,7 +13,7 @@ namespace TelegramBotBase.Extensions.Images
{ {
public static Stream ToStream(this Image image, ImageFormat format) public static Stream ToStream(this Image image, ImageFormat format)
{ {
var stream = new System.IO.MemoryStream(); var stream = new MemoryStream();
image.Save(stream, format); image.Save(stream, format);
stream.Position = 0; stream.Position = 0;
return stream; return stream;
@ -29,11 +28,11 @@ namespace TelegramBotBase.Extensions.Images
/// <param name="replyTo"></param> /// <param name="replyTo"></param>
/// <param name="disableNotification"></param> /// <param name="disableNotification"></param>
/// <returns></returns> /// <returns></returns>
public static async Task<Message> SendPhoto(this DeviceSession session, Image image, String name, String caption, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false) public static async Task<Message> SendPhoto(this DeviceSession session, Image image, string name, string caption, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false)
{ {
using (var fileStream = ToStream(image, ImageFormat.Png)) using (var fileStream = ToStream(image, ImageFormat.Png))
{ {
InputOnlineFile fts = new InputOnlineFile(fileStream, name); var fts = new InputOnlineFile(fileStream, name);
return await session.SendPhoto(fts, caption: caption, buttons, replyTo, disableNotification); return await session.SendPhoto(fts, caption: caption, buttons, replyTo, disableNotification);
} }
@ -48,11 +47,11 @@ namespace TelegramBotBase.Extensions.Images
/// <param name="replyTo"></param> /// <param name="replyTo"></param>
/// <param name="disableNotification"></param> /// <param name="disableNotification"></param>
/// <returns></returns> /// <returns></returns>
public static async Task<Message> SendPhoto(this DeviceSession session, Bitmap image, String name, String caption, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false) public static async Task<Message> SendPhoto(this DeviceSession session, Bitmap image, string name, string caption, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false)
{ {
using (var fileStream = ToStream(image, ImageFormat.Png)) using (var fileStream = ToStream(image, ImageFormat.Png))
{ {
InputOnlineFile fts = new InputOnlineFile(fileStream, name); var fts = new InputOnlineFile(fileStream, name);
return await session.SendPhoto(fts, caption: caption, buttons, replyTo, disableNotification); return await session.SendPhoto(fts, caption: caption, buttons, replyTo, disableNotification);
} }

View File

@ -1,8 +1,4 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Builder; using TelegramBotBase.Builder;
using TelegramBotBase.Builder.Interfaces; using TelegramBotBase.Builder.Interfaces;
@ -15,13 +11,13 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL
/// Uses an Microsoft SQL Server Database to save and restore sessions. /// Uses an Microsoft SQL Server Database to save and restore sessions.
/// </summary> /// </summary>
/// <param name="builder"></param> /// <param name="builder"></param>
/// <param name="ConnectionString"></param> /// <param name="connectionString"></param>
/// <param name="tablePrefix"></param> /// <param name="tablePrefix"></param>
/// <param name="fallbackForm"></param> /// <param name="fallbackForm"></param>
/// <returns></returns> /// <returns></returns>
public static ILanguageSelectionStage UseSQLDatabase(this ISessionSerializationStage builder, String ConnectionString, Type fallbackForm = null, String tablePrefix = "tgb_") public static ILanguageSelectionStage UseSqlDatabase(this ISessionSerializationStage builder, string connectionString, Type fallbackForm = null, string tablePrefix = "tgb_")
{ {
var serializer = new MSSQLSerializer(ConnectionString, tablePrefix, fallbackForm); var serializer = new MssqlSerializer(connectionString, tablePrefix, fallbackForm);
builder.UseSerialization(serializer); builder.UseSerialization(serializer);
@ -33,18 +29,18 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL
/// Uses an Microsoft SQL Server Database to save and restore sessions. /// Uses an Microsoft SQL Server Database to save and restore sessions.
/// </summary> /// </summary>
/// <param name="builder"></param> /// <param name="builder"></param>
/// <param name="HostOrIP"></param> /// <param name="hostOrIP"></param>
/// <param name="UserId"></param> /// <param name="userId"></param>
/// <param name="Password"></param> /// <param name="password"></param>
/// <param name="DatabaseName"></param> /// <param name="databaseName"></param>
/// <param name="tablePrefix"></param> /// <param name="tablePrefix"></param>
/// <param name="fallbackForm"></param> /// <param name="fallbackForm"></param>
/// <returns></returns> /// <returns></returns>
public static ILanguageSelectionStage UseSQLDatabase(this ISessionSerializationStage builder, String HostOrIP, String DatabaseName, String UserId, String Password, Type fallbackForm = null, String tablePrefix = "tgb_") public static ILanguageSelectionStage UseSqlDatabase(this ISessionSerializationStage builder, string hostOrIP, string databaseName, string userId, string password, Type fallbackForm = null, string tablePrefix = "tgb_")
{ {
var connectionString = $"Server={HostOrIP}; Database={DatabaseName}; User Id={UserId}; Password={Password}; TrustServerCertificate=true;"; var connectionString = $"Server={hostOrIP}; Database={databaseName}; User Id={userId}; Password={password}; TrustServerCertificate=true;";
var serializer = new MSSQLSerializer(connectionString, tablePrefix, fallbackForm); var serializer = new MssqlSerializer(connectionString, tablePrefix, fallbackForm);
builder.UseSerialization(serializer); builder.UseSerialization(serializer);
@ -55,19 +51,19 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL
/// Uses an Microsoft SQL Server Database with Windows Authentication to save and restore sessions. /// Uses an Microsoft SQL Server Database with Windows Authentication to save and restore sessions.
/// </summary> /// </summary>
/// <param name="builder"></param> /// <param name="builder"></param>
/// <param name="HostOrIP"></param> /// <param name="hostOrIP"></param>
/// <param name="DatabaseName"></param> /// <param name="databaseName"></param>
/// <param name="tablePrefix"></param> /// <param name="tablePrefix"></param>
/// <param name="fallbackForm"></param> /// <param name="fallbackForm"></param>
/// <returns></returns> /// <returns></returns>
public static ILanguageSelectionStage UseSQLDatabase(this ISessionSerializationStage builder, String HostOrIP, String DatabaseName, bool IntegratedSecurity = true, Type fallbackForm = null, String tablePrefix = "tgb_") public static ILanguageSelectionStage UseSqlDatabase(this ISessionSerializationStage builder, string hostOrIP, string databaseName, bool integratedSecurity = true, Type fallbackForm = null, string tablePrefix = "tgb_")
{ {
if (!IntegratedSecurity) if (!integratedSecurity)
throw new ArgumentOutOfRangeException(); throw new ArgumentOutOfRangeException();
var connectionString = $"Server={HostOrIP}; Database={DatabaseName}; Integrated Security=true; TrustServerCertificate=true;"; var connectionString = $"Server={hostOrIP}; Database={databaseName}; Integrated Security=true; TrustServerCertificate=true;";
var serializer = new MSSQLSerializer(connectionString, tablePrefix, fallbackForm); var serializer = new MssqlSerializer(connectionString, tablePrefix, fallbackForm);
builder.UseSerialization(serializer); builder.UseSerialization(serializer);

View File

@ -1,19 +1,19 @@
using TelegramBotBase.Interfaces; using System;
using TelegramBotBase.Builder.Interfaces;
using System;
using TelegramBotBase.Base;
using TelegramBotBase.Args;
using TelegramBotBase.Form;
using Microsoft.Data.SqlClient;
using System.Data; using System.Data;
using Microsoft.Data.SqlClient;
using Newtonsoft.Json;
using TelegramBotBase.Args;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
using TelegramBotBase.Interfaces;
namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL
{ {
public class MSSQLSerializer : IStateMachine public class MssqlSerializer : IStateMachine
{ {
public Type FallbackStateForm { get; set; } public Type FallbackStateForm { get; set; }
public string ConnectionString { get; } public string ConnectionString { get; }
public String TablePrefix { get; set; } public string TablePrefix { get; set; }
/// <summary> /// <summary>
/// Will initialize the state machine. /// Will initialize the state machine.
@ -21,20 +21,15 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL
/// <param name="file">Path of the file and name where to save the session details.</param> /// <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="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> /// <param name="overwrite">Declares of the file could be overwritten.</param>
public MSSQLSerializer(String ConnectionString, String tablePrefix = "tgb_", Type fallbackStateForm = null) public MssqlSerializer(string connectionString, string tablePrefix = "tgb_", Type fallbackStateForm = null)
{ {
if (ConnectionString is null) this.ConnectionString = connectionString ?? throw new ArgumentNullException(nameof(connectionString));
{
throw new ArgumentNullException(nameof(ConnectionString));
}
this.ConnectionString = ConnectionString; TablePrefix = tablePrefix;
this.TablePrefix = tablePrefix; FallbackStateForm = fallbackStateForm;
this.FallbackStateForm = fallbackStateForm; if (FallbackStateForm != null && !FallbackStateForm.IsSubclassOf(typeof(FormBase)))
if (this.FallbackStateForm != null && !this.FallbackStateForm.IsSubclassOf(typeof(FormBase)))
{ {
throw new ArgumentException("FallbackStateForm is not a subclass of FormBase"); throw new ArgumentException("FallbackStateForm is not a subclass of FormBase");
} }
@ -58,7 +53,7 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL
foreach (DataRow r in dataTable.Rows) foreach (DataRow r in dataTable.Rows)
{ {
var se = new StateEntry() var se = new StateEntry
{ {
DeviceId = (long)r["deviceId"], DeviceId = (long)r["deviceId"],
ChatTitle = r["deviceTitle"].ToString(), ChatTitle = r["deviceTitle"].ToString(),
@ -77,21 +72,21 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL
sc.GroupIds.Add(se.DeviceId); sc.GroupIds.Add(se.DeviceId);
} }
var data_command = connection.CreateCommand(); var command2 = connection.CreateCommand();
data_command.CommandText = "SELECT [key], value, type FROM " + TablePrefix + "devices_sessions_data WHERE deviceId = @deviceId"; command2.CommandText = "SELECT [key], value, type FROM " + TablePrefix + "devices_sessions_data WHERE deviceId = @deviceId";
data_command.Parameters.Add(new SqlParameter("@deviceId", r["deviceId"])); command2.Parameters.Add(new SqlParameter("@deviceId", r["deviceId"]));
var data_table = new DataTable(); var dataTable2 = new DataTable();
using (var dataAdapter2 = new SqlDataAdapter(data_command)) using (var dataAdapter2 = new SqlDataAdapter(command2))
{ {
dataAdapter2.Fill(data_table); dataAdapter2.Fill(dataTable2);
foreach (DataRow r2 in data_table.Rows) foreach (DataRow r2 in dataTable2.Rows)
{ {
var key = r2["key"].ToString(); var key = r2["key"].ToString();
var type = Type.GetType(r2["type"].ToString()); var type = Type.GetType(r2["type"].ToString());
var value = Newtonsoft.Json.JsonConvert.DeserializeObject(r2["value"].ToString(), type); var value = JsonConvert.DeserializeObject(r2["value"].ToString(), type);
se.Values.Add(key, value); se.Values.Add(key, value);
} }
@ -118,61 +113,61 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL
connection.Open(); connection.Open();
//Cleanup old Session data //Cleanup old Session data
var clear_command = connection.CreateCommand(); var clearCommand = connection.CreateCommand();
clear_command.CommandText = $"DELETE FROM {TablePrefix}devices_sessions_data"; clearCommand.CommandText = $"DELETE FROM {TablePrefix}devices_sessions_data";
clear_command.ExecuteNonQuery(); clearCommand.ExecuteNonQuery();
clear_command.CommandText = $"DELETE FROM {TablePrefix}devices_sessions"; clearCommand.CommandText = $"DELETE FROM {TablePrefix}devices_sessions";
clear_command.ExecuteNonQuery(); clearCommand.ExecuteNonQuery();
//Prepare new session commands //Prepare new session commands
var session_command = connection.CreateCommand(); var sessionCommand = connection.CreateCommand();
var data_command = connection.CreateCommand(); var dataCommand = connection.CreateCommand();
session_command.CommandText = "INSERT INTO " + TablePrefix + "devices_sessions (deviceId, deviceTitle, FormUri, QualifiedName) VALUES (@deviceId, @deviceTitle, @FormUri, @QualifiedName)"; sessionCommand.CommandText = "INSERT INTO " + TablePrefix + "devices_sessions (deviceId, deviceTitle, FormUri, QualifiedName) VALUES (@deviceId, @deviceTitle, @FormUri, @QualifiedName)";
session_command.Parameters.Add(new SqlParameter("@deviceId", "")); sessionCommand.Parameters.Add(new SqlParameter("@deviceId", ""));
session_command.Parameters.Add(new SqlParameter("@deviceTitle", "")); sessionCommand.Parameters.Add(new SqlParameter("@deviceTitle", ""));
session_command.Parameters.Add(new SqlParameter("@FormUri", "")); sessionCommand.Parameters.Add(new SqlParameter("@FormUri", ""));
session_command.Parameters.Add(new SqlParameter("@QualifiedName", "")); sessionCommand.Parameters.Add(new SqlParameter("@QualifiedName", ""));
data_command.CommandText = "INSERT INTO " + TablePrefix + "devices_sessions_data (deviceId, [key], value, type) VALUES (@deviceId, @key, @value, @type)"; dataCommand.CommandText = "INSERT INTO " + TablePrefix + "devices_sessions_data (deviceId, [key], value, type) VALUES (@deviceId, @key, @value, @type)";
data_command.Parameters.Add(new SqlParameter("@deviceId", "")); dataCommand.Parameters.Add(new SqlParameter("@deviceId", ""));
data_command.Parameters.Add(new SqlParameter("@key", "")); dataCommand.Parameters.Add(new SqlParameter("@key", ""));
data_command.Parameters.Add(new SqlParameter("@value", "")); dataCommand.Parameters.Add(new SqlParameter("@value", ""));
data_command.Parameters.Add(new SqlParameter("@type", "")); dataCommand.Parameters.Add(new SqlParameter("@type", ""));
//Store session data in database //Store session data in database
foreach (var state in container.States) foreach (var state in container.States)
{ {
session_command.Parameters["@deviceId"].Value = state.DeviceId; sessionCommand.Parameters["@deviceId"].Value = state.DeviceId;
session_command.Parameters["@deviceTitle"].Value = state.ChatTitle ?? ""; sessionCommand.Parameters["@deviceTitle"].Value = state.ChatTitle ?? "";
session_command.Parameters["@FormUri"].Value = state.FormUri; sessionCommand.Parameters["@FormUri"].Value = state.FormUri;
session_command.Parameters["@QualifiedName"].Value = state.QualifiedName; sessionCommand.Parameters["@QualifiedName"].Value = state.QualifiedName;
session_command.ExecuteNonQuery(); sessionCommand.ExecuteNonQuery();
foreach (var data in state.Values) foreach (var data in state.Values)
{ {
data_command.Parameters["@deviceId"].Value = state.DeviceId; dataCommand.Parameters["@deviceId"].Value = state.DeviceId;
data_command.Parameters["@key"].Value = data.Key; dataCommand.Parameters["@key"].Value = data.Key;
var type = data.Value.GetType(); var type = data.Value.GetType();
if (type.IsPrimitive || type.Equals(typeof(string))) if (type.IsPrimitive || type.Equals(typeof(string)))
{ {
data_command.Parameters["@value"].Value = data.Value; dataCommand.Parameters["@value"].Value = data.Value;
} }
else else
{ {
data_command.Parameters["@value"].Value = Newtonsoft.Json.JsonConvert.SerializeObject(data.Value); dataCommand.Parameters["@value"].Value = JsonConvert.SerializeObject(data.Value);
} }
data_command.Parameters["@type"].Value = type.AssemblyQualifiedName;
data_command.ExecuteNonQuery(); dataCommand.Parameters["@type"].Value = type.AssemblyQualifiedName;
dataCommand.ExecuteNonQuery();
} }
} }
@ -183,4 +178,4 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL
} }
} }
} }

View File

@ -1,27 +1,24 @@
using System; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Telegram.Bot.Types; using TelegramBotBase.Args;
using TelegramBotBase;
using TelegramBotBase.Form;
using TelegramBotBaseTest.Tests;
using TelegramBotBase.Commands;
using TelegramBotBase.Builder; using TelegramBotBase.Builder;
using TelegramBotBase.Commands;
using TelegramBotBase.Enums;
using TelegramBotBaseTest.Tests;
namespace TelegramBotBaseTest namespace TelegramBotBaseTest
{ {
class Program internal class Program
{ {
static void Main(string[] args) private static void Main(string[] args)
{ {
String APIKey = ""; var apiKey = "";
var bb = BotBaseBuilder var bb = BotBaseBuilder
.Create() .Create()
.WithAPIKey(APIKey) .WithAPIKey(apiKey)
.DefaultMessageLoop() .DefaultMessageLoop()
.WithStartForm<Start>() .WithStartForm<Start>()
.NoProxy() .NoProxy()
@ -45,7 +42,7 @@ namespace TelegramBotBaseTest
//Update Bot commands to botfather //Update Bot commands to botfather
bb.UploadBotCommands().Wait(); bb.UploadBotCommands().Wait();
bb.SetSetting(TelegramBotBase.Enums.eSettings.LogAllMessages, true); bb.SetSetting(ESettings.LogAllMessages, true);
bb.Message += (s, en) => bb.Message += (s, en) =>
{ {
@ -65,7 +62,7 @@ namespace TelegramBotBaseTest
} }
private static async Task Bb_BotCommand(object sender, TelegramBotBase.Args.BotCommandEventArgs en) private static async Task Bb_BotCommand(object sender, BotCommandEventArgs en)
{ {
switch (en.Command) switch (en.Command)
{ {
@ -105,7 +102,7 @@ namespace TelegramBotBaseTest
case "/params": case "/params":
String m = en.Parameters.DefaultIfEmpty("").Aggregate((a, b) => a + " and " + b); var m = en.Parameters.DefaultIfEmpty("").Aggregate((a, b) => a + " and " + b);
await en.Device.Send("Your parameters are: " + m, replyTo: en.Device.LastMessageId); await en.Device.Send("Your parameters are: " + m, replyTo: en.Device.LastMessageId);

View File

@ -1,5 +1,4 @@
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden // Allgemeine Informationen über eine Assembly werden über die folgenden

View File

@ -1,7 +1,4 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Form; using TelegramBotBase.Form;
@ -13,12 +10,12 @@ namespace TelegramBotBaseTest.Tests
public ButtonTestForm() public ButtonTestForm()
{ {
this.Opened += ButtonTestForm_Opened; Opened += ButtonTestForm_Opened;
} }
private async Task ButtonTestForm_Opened(object sender, EventArgs e) private async Task ButtonTestForm_Opened(object sender, EventArgs e)
{ {
await this.Device.Send("Hello world! (Click 'back' to get back to Start)"); await Device.Send("Hello world! (Click 'back' to get back to Start)");
} }
public override async Task Action(MessageResult message) public override async Task Action(MessageResult message)
@ -38,25 +35,25 @@ namespace TelegramBotBaseTest.Tests
{ {
case "button1": case "button1":
await this.Device.Send("Button 1 pressed"); await Device.Send("Button 1 pressed");
break; break;
case "button2": case "button2":
await this.Device.Send("Button 2 pressed"); await Device.Send("Button 2 pressed");
break; break;
case "button3": case "button3":
await this.Device.Send("Button 3 pressed"); await Device.Send("Button 3 pressed");
break; break;
case "button4": case "button4":
await this.Device.Send("Button 4 pressed"); await Device.Send("Button 4 pressed");
break; break;
@ -64,7 +61,7 @@ namespace TelegramBotBaseTest.Tests
var st = new Menu(); var st = new Menu();
await this.NavigateTo(st); await NavigateTo(st);
break; break;
@ -82,7 +79,7 @@ namespace TelegramBotBaseTest.Tests
public override async Task Render(MessageResult message) public override async Task Render(MessageResult message)
{ {
ButtonForm btn = new ButtonForm(); var btn = new ButtonForm();
btn.AddButtonRow(new ButtonBase("Button 1", new CallbackData("a", "button1").Serialize()), new ButtonBase("Button 2", new CallbackData("a", "button2").Serialize())); btn.AddButtonRow(new ButtonBase("Button 1", new CallbackData("a", "button1").Serialize()), new ButtonBase("Button 2", new CallbackData("a", "button2").Serialize()));
@ -92,7 +89,7 @@ namespace TelegramBotBaseTest.Tests
btn.AddButtonRow(new ButtonBase("Back", new CallbackData("a", "back").Serialize())); btn.AddButtonRow(new ButtonBase("Back", new CallbackData("a", "back").Serialize()));
await this.Device.Send("Click a button", btn); await Device.Send("Click a button", btn);
} }

View File

@ -1,34 +1,30 @@
using System; using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Args; using TelegramBotBase.Args;
using TelegramBotBase.Controls;
using TelegramBotBase.Controls.Hybrid; using TelegramBotBase.Controls.Hybrid;
using TelegramBotBase.Enums;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Controls namespace TelegramBotBaseTest.Tests.Controls
{ {
public class ButtonGridForm : AutoCleanForm public class ButtonGridForm : AutoCleanForm
{ {
private ButtonGrid _mButtons;
ButtonGrid m_Buttons = null;
public ButtonGridForm() public ButtonGridForm()
{ {
this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; DeleteMode = EDeleteMode.OnLeavingForm;
this.Init += ButtonGridForm_Init; Init += ButtonGridForm_Init;
} }
private async Task ButtonGridForm_Init(object sender, InitEventArgs e) private Task ButtonGridForm_Init(object sender, InitEventArgs e)
{ {
m_Buttons = new ButtonGrid(); _mButtons = new ButtonGrid
{
KeyboardType = EKeyboardType.InlineKeyBoard
};
m_Buttons.KeyboardType = TelegramBotBase.Enums.eKeyboardType.InlineKeyBoard; var bf = new ButtonForm();
ButtonForm bf = new ButtonForm();
bf.AddButtonRow(new ButtonBase("Back", "back"), new ButtonBase("Switch Keyboard", "switch")); bf.AddButtonRow(new ButtonBase("Back", "back"), new ButtonBase("Switch Keyboard", "switch"));
@ -36,13 +32,12 @@ namespace TelegramBotBaseTest.Tests.Controls
bf.AddButtonRow(new ButtonBase("Button3", "b3"), new ButtonBase("Button4", "b4")); bf.AddButtonRow(new ButtonBase("Button3", "b3"), new ButtonBase("Button4", "b4"));
m_Buttons.ButtonsForm = bf; _mButtons.ButtonsForm = bf;
m_Buttons.ButtonClicked += Bg_ButtonClicked;
this.AddControl(m_Buttons);
_mButtons.ButtonClicked += Bg_ButtonClicked;
AddControl(_mButtons);
return Task.CompletedTask;
} }
private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e) private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e)
@ -53,26 +48,21 @@ namespace TelegramBotBaseTest.Tests.Controls
if (e.Button.Value == "back") if (e.Button.Value == "back")
{ {
var start = new Menu(); var start = new Menu();
await this.NavigateTo(start); await NavigateTo(start);
} }
else if (e.Button.Value == "switch") else if (e.Button.Value == "switch")
{ {
switch (m_Buttons.KeyboardType) _mButtons.KeyboardType = _mButtons.KeyboardType switch
{ {
case TelegramBotBase.Enums.eKeyboardType.ReplyKeyboard: EKeyboardType.ReplyKeyboard => EKeyboardType.InlineKeyBoard,
m_Buttons.KeyboardType = TelegramBotBase.Enums.eKeyboardType.InlineKeyBoard; EKeyboardType.InlineKeyBoard => EKeyboardType.ReplyKeyboard,
break; _ => _mButtons.KeyboardType
case TelegramBotBase.Enums.eKeyboardType.InlineKeyBoard: };
m_Buttons.KeyboardType = TelegramBotBase.Enums.eKeyboardType.ReplyKeyboard;
break;
}
} }
else else
{ {
await this.Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}"); await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}");
} }

View File

@ -1,55 +1,49 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using TelegramBotBase.Args; using TelegramBotBase.Args;
using TelegramBotBase.Controls;
using TelegramBotBase.Controls.Hybrid; using TelegramBotBase.Controls.Hybrid;
using TelegramBotBase.Enums;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Controls namespace TelegramBotBaseTest.Tests.Controls
{ {
public class ButtonGridPagingForm : AutoCleanForm public class ButtonGridPagingForm : AutoCleanForm
{ {
private ButtonGrid _mButtons;
ButtonGrid m_Buttons = null;
public ButtonGridPagingForm() public ButtonGridPagingForm()
{ {
this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; DeleteMode = EDeleteMode.OnLeavingForm;
this.Init += ButtonGridForm_Init; Init += ButtonGridForm_Init;
} }
private async Task ButtonGridForm_Init(object sender, InitEventArgs e) private Task ButtonGridForm_Init(object sender, InitEventArgs e)
{ {
m_Buttons = new ButtonGrid(); _mButtons = new ButtonGrid
{
m_Buttons.KeyboardType = TelegramBotBase.Enums.eKeyboardType.ReplyKeyboard; KeyboardType = EKeyboardType.ReplyKeyboard,
EnablePaging = true,
m_Buttons.EnablePaging = true; EnableSearch = true,
m_Buttons.EnableSearch = true; HeadLayoutButtonRow = new List<ButtonBase> { new ButtonBase("Back", "back") }
};
m_Buttons.HeadLayoutButtonRow = new List<ButtonBase>() { new ButtonBase("Back", "back") };
var countries = CultureInfo.GetCultures(CultureTypes.SpecificCultures); var countries = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
ButtonForm bf = new ButtonForm(); var bf = new ButtonForm();
foreach (var c in countries) foreach (var c in countries)
{ {
bf.AddButtonRow(new ButtonBase(c.EnglishName, c.EnglishName)); bf.AddButtonRow(new ButtonBase(c.EnglishName, c.EnglishName));
} }
m_Buttons.ButtonsForm = bf; _mButtons.ButtonsForm = bf;
m_Buttons.ButtonClicked += Bg_ButtonClicked;
this.AddControl(m_Buttons);
_mButtons.ButtonClicked += Bg_ButtonClicked;
AddControl(_mButtons);
return Task.CompletedTask;
} }
private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e) private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e)
@ -60,12 +54,12 @@ namespace TelegramBotBaseTest.Tests.Controls
if (e.Button.Value == "back") if (e.Button.Value == "back")
{ {
var start = new Menu(); var start = new Menu();
await this.NavigateTo(start); await NavigateTo(start);
} }
else else
{ {
await this.Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}"); await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}");
} }

View File

@ -1,58 +1,56 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.Linq; using System.Linq;
using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using TelegramBotBase.Args; using TelegramBotBase.Args;
using TelegramBotBase.Controls;
using TelegramBotBase.Controls.Hybrid; using TelegramBotBase.Controls.Hybrid;
using TelegramBotBase.DataSources;
using TelegramBotBase.Enums;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Controls namespace TelegramBotBaseTest.Tests.Controls
{ {
public class ButtonGridTagForm : AutoCleanForm public class ButtonGridTagForm : AutoCleanForm
{ {
private TaggedButtonGrid _mButtons;
TaggedButtonGrid m_Buttons = null;
public ButtonGridTagForm() public ButtonGridTagForm()
{ {
this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; DeleteMode = EDeleteMode.OnLeavingForm;
this.Init += ButtonGridTagForm_Init; Init += ButtonGridTagForm_Init;
} }
private async Task ButtonGridTagForm_Init(object sender, InitEventArgs e) private Task ButtonGridTagForm_Init(object sender, InitEventArgs e)
{ {
m_Buttons = new TaggedButtonGrid(); _mButtons = new TaggedButtonGrid
{
KeyboardType = EKeyboardType.ReplyKeyboard,
EnablePaging = true,
HeadLayoutButtonRow = new List<ButtonBase> { new ButtonBase("Back", "back") }
};
m_Buttons.KeyboardType = TelegramBotBase.Enums.eKeyboardType.ReplyKeyboard;
m_Buttons.EnablePaging = true;
m_Buttons.HeadLayoutButtonRow = new List<ButtonBase>() { new ButtonBase("Back", "back") };
var countries = CultureInfo.GetCultures(CultureTypes.SpecificCultures); var countries = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
ButtonForm bf = new ButtonForm(); var bf = new ButtonForm();
foreach (var c in countries) foreach (var c in countries)
{ {
bf.AddButtonRow(new TagButtonBase(c.EnglishName, c.EnglishName, c.Parent.EnglishName)); bf.AddButtonRow(new TagButtonBase(c.EnglishName, c.EnglishName, c.Parent.EnglishName));
} }
m_Buttons.Tags = countries.Select(a => a.Parent.EnglishName).Distinct().OrderBy(a => a).ToList(); _mButtons.Tags = countries.Select(a => a.Parent.EnglishName).Distinct().OrderBy(a => a).ToList();
m_Buttons.SelectedTags = countries.Select(a => a.Parent.EnglishName).Distinct().OrderBy(a => a).ToList(); _mButtons.SelectedTags = countries.Select(a => a.Parent.EnglishName).Distinct().OrderBy(a => a).ToList();
m_Buttons.EnableCheckAllTools = true; _mButtons.EnableCheckAllTools = true;
m_Buttons.DataSource = new TelegramBotBase.Datasources.ButtonFormDataSource(bf); _mButtons.DataSource = new ButtonFormDataSource(bf);
m_Buttons.ButtonClicked += Bg_ButtonClicked; _mButtons.ButtonClicked += Bg_ButtonClicked;
this.AddControl(m_Buttons); AddControl(_mButtons);
return Task.CompletedTask;
} }
private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e) private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e)
@ -65,13 +63,13 @@ namespace TelegramBotBaseTest.Tests.Controls
case "back": case "back":
var start = new Menu(); var start = new Menu();
await this.NavigateTo(start); await NavigateTo(start);
return; return;
} }
await this.Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}"); await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}");
} }
} }
} }

View File

@ -1,14 +1,9 @@
using System; using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
using TelegramBotBase.Controls;
using TelegramBotBase.Args; using TelegramBotBase.Args;
using TelegramBotBase.Base;
using TelegramBotBase.Controls.Inline; using TelegramBotBase.Controls.Inline;
using TelegramBotBase.Enums;
using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Controls namespace TelegramBotBaseTest.Tests.Controls
{ {
@ -17,20 +12,23 @@ namespace TelegramBotBaseTest.Tests.Controls
public CalendarPicker Picker { get; set; } public CalendarPicker Picker { get; set; }
int? selectedDateMessage { get; set; } private int? SelectedDateMessage { get; set; }
public CalendarPickerForm() public CalendarPickerForm()
{ {
this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; DeleteMode = EDeleteMode.OnLeavingForm;
this.Init += CalendarPickerForm_Init; Init += CalendarPickerForm_Init;
} }
private async Task CalendarPickerForm_Init(object sender, InitEventArgs e) private Task CalendarPickerForm_Init(object sender, InitEventArgs e)
{ {
this.Picker = new CalendarPicker(); Picker = new CalendarPicker
this.Picker.Title = "Datum auswählen / Pick date"; {
Title = "Datum auswählen / Pick date"
this.AddControl(Picker); };
AddControl(Picker);
return Task.CompletedTask;
} }
@ -43,7 +41,7 @@ namespace TelegramBotBaseTest.Tests.Controls
var s = new Menu(); var s = new Menu();
await this.NavigateTo(s); await NavigateTo(s);
break; break;
} }
@ -52,23 +50,23 @@ namespace TelegramBotBaseTest.Tests.Controls
public override async Task Render(MessageResult message) public override async Task Render(MessageResult message)
{ {
String s = ""; var s = "";
s = "Selected date is " + this.Picker.SelectedDate.ToShortDateString() + "\r\n"; s = "Selected date is " + Picker.SelectedDate.ToShortDateString() + "\r\n";
s += "Selected month is " + this.Picker.Culture.DateTimeFormat.MonthNames[this.Picker.VisibleMonth.Month - 1] + "\r\n"; s += "Selected month is " + Picker.Culture.DateTimeFormat.MonthNames[Picker.VisibleMonth.Month - 1] + "\r\n";
s += "Selected year is " + this.Picker.VisibleMonth.Year.ToString(); s += "Selected year is " + Picker.VisibleMonth.Year;
ButtonForm bf = new ButtonForm(); var bf = new ButtonForm();
bf.AddButtonRow(new ButtonBase("Back","back")); bf.AddButtonRow(new ButtonBase("Back","back"));
if (selectedDateMessage != null) if (SelectedDateMessage != null)
{ {
await this.Device.Edit(this.selectedDateMessage.Value, s, bf); await Device.Edit(SelectedDateMessage.Value, s, bf);
} }
else else
{ {
var m = await this.Device.Send(s, bf); var m = await Device.Send(s, bf);
this.selectedDateMessage = m.MessageId; SelectedDateMessage = m.MessageId;
} }

View File

@ -1,56 +1,54 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using TelegramBotBase.Args; using TelegramBotBase.Args;
using TelegramBotBase.Controls;
using TelegramBotBase.Controls.Hybrid; using TelegramBotBase.Controls.Hybrid;
using TelegramBotBase.DataSources;
using TelegramBotBase.Enums;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Controls namespace TelegramBotBaseTest.Tests.Controls
{ {
public class CheckedButtonListForm : AutoCleanForm public class CheckedButtonListForm : AutoCleanForm
{ {
private CheckedButtonList _mButtons;
CheckedButtonList m_Buttons = null;
public CheckedButtonListForm() public CheckedButtonListForm()
{ {
this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; DeleteMode = EDeleteMode.OnLeavingForm;
this.Init += CheckedButtonListForm_Init; Init += CheckedButtonListForm_Init;
} }
private async Task CheckedButtonListForm_Init(object sender, InitEventArgs e) private Task CheckedButtonListForm_Init(object sender, InitEventArgs e)
{ {
m_Buttons = new CheckedButtonList(); _mButtons = new CheckedButtonList
{
KeyboardType = EKeyboardType.InlineKeyBoard,
EnablePaging = true,
HeadLayoutButtonRow = new List<ButtonBase> { new ButtonBase("Back", "back"), new ButtonBase("Switch Keyboard", "switch") },
SubHeadLayoutButtonRow = new List<ButtonBase> { new ButtonBase("No checked items", "$") }
};
m_Buttons.KeyboardType = TelegramBotBase.Enums.eKeyboardType.InlineKeyBoard; var bf = new ButtonForm();
m_Buttons.EnablePaging = true;
m_Buttons.HeadLayoutButtonRow = new List<ButtonBase>() { new ButtonBase("Back", "back"), new ButtonBase("Switch Keyboard", "switch") }; for (var i = 0; i < 30; i++)
m_Buttons.SubHeadLayoutButtonRow = new List<ButtonBase>() { new ButtonBase("No checked items", "$") };
ButtonForm bf = new ButtonForm();
for (int i = 0; i < 30; i++)
{ {
bf.AddButtonRow($"{i + 1}. Item", i.ToString()); bf.AddButtonRow($"{i + 1}. Item", i.ToString());
} }
m_Buttons.DataSource = new TelegramBotBase.Datasources.ButtonFormDataSource(bf); _mButtons.DataSource = new ButtonFormDataSource(bf);
m_Buttons.ButtonClicked += Bg_ButtonClicked; _mButtons.ButtonClicked += Bg_ButtonClicked;
m_Buttons.CheckedChanged += M_Buttons_CheckedChanged; _mButtons.CheckedChanged += M_Buttons_CheckedChanged;
this.AddControl(m_Buttons); AddControl(_mButtons);
return Task.CompletedTask;
} }
private async Task M_Buttons_CheckedChanged(object sender, CheckedChangedEventArgs e) private Task M_Buttons_CheckedChanged(object sender, CheckedChangedEventArgs e)
{ {
m_Buttons.SubHeadLayoutButtonRow = new List<ButtonBase>() { new ButtonBase($"{m_Buttons.CheckedItems.Count} checked items", "$") }; _mButtons.SubHeadLayoutButtonRow = new List<ButtonBase> { new ButtonBase($"{_mButtons.CheckedItems.Count} checked items", "$") };
return Task.CompletedTask;
} }
private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e) private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e)
@ -68,16 +66,12 @@ namespace TelegramBotBaseTest.Tests.Controls
case "switch": case "switch":
switch (m_Buttons.KeyboardType) _mButtons.KeyboardType = _mButtons.KeyboardType switch
{ {
case TelegramBotBase.Enums.eKeyboardType.ReplyKeyboard: EKeyboardType.ReplyKeyboard => EKeyboardType.InlineKeyBoard,
m_Buttons.KeyboardType = TelegramBotBase.Enums.eKeyboardType.InlineKeyBoard; EKeyboardType.InlineKeyBoard => EKeyboardType.ReplyKeyboard,
break; _ => _mButtons.KeyboardType
case TelegramBotBase.Enums.eKeyboardType.InlineKeyBoard: };
m_Buttons.KeyboardType = TelegramBotBase.Enums.eKeyboardType.ReplyKeyboard;
break;
}
break; break;

View File

@ -1,14 +1,9 @@
using System; using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
using TelegramBotBase.Controls;
using TelegramBotBase.Args; using TelegramBotBase.Args;
using TelegramBotBase.Base;
using TelegramBotBase.Controls.Inline; using TelegramBotBase.Controls.Inline;
using TelegramBotBase.Enums;
using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Controls namespace TelegramBotBaseTest.Tests.Controls
{ {
@ -17,19 +12,22 @@ namespace TelegramBotBaseTest.Tests.Controls
public MonthPicker Picker { get; set; } public MonthPicker Picker { get; set; }
int? selectedDateMessage { get; set; } private int? SelectedDateMessage { get; set; }
public MonthPickerForm() public MonthPickerForm()
{ {
this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; DeleteMode = EDeleteMode.OnLeavingForm;
this.Init += MonthPickerForm_Init; Init += MonthPickerForm_Init;
} }
private async Task MonthPickerForm_Init(object sender, InitEventArgs e) private Task MonthPickerForm_Init(object sender, InitEventArgs e)
{ {
this.Picker = new MonthPicker(); Picker = new MonthPicker
this.Picker.Title = "Monat auswählen / Pick month"; {
this.AddControl(Picker); Title = "Monat auswählen / Pick month"
};
AddControl(Picker);
return Task.CompletedTask;
} }
@ -42,7 +40,7 @@ namespace TelegramBotBaseTest.Tests.Controls
var s = new Menu(); var s = new Menu();
await this.NavigateTo(s); await NavigateTo(s);
break; break;
} }
@ -51,22 +49,22 @@ namespace TelegramBotBaseTest.Tests.Controls
public override async Task Render(MessageResult message) public override async Task Render(MessageResult message)
{ {
String s = ""; var s = "";
s += "Selected month is " + this.Picker.Culture.DateTimeFormat.MonthNames[this.Picker.SelectedDate.Month - 1] + "\r\n"; s += "Selected month is " + Picker.Culture.DateTimeFormat.MonthNames[Picker.SelectedDate.Month - 1] + "\r\n";
s += "Selected year is " + this.Picker.VisibleMonth.Year.ToString(); s += "Selected year is " + Picker.VisibleMonth.Year;
ButtonForm bf = new ButtonForm(); var bf = new ButtonForm();
bf.AddButtonRow(new ButtonBase("Back","back")); bf.AddButtonRow(new ButtonBase("Back","back"));
if (selectedDateMessage != null) if (SelectedDateMessage != null)
{ {
await this.Device.Edit(this.selectedDateMessage.Value, s, bf); await Device.Edit(SelectedDateMessage.Value, s, bf);
} }
else else
{ {
var m = await this.Device.Send(s, bf); var m = await Device.Send(s, bf);
this.selectedDateMessage = m.MessageId; SelectedDateMessage = m.MessageId;
} }

View File

@ -1,11 +1,10 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using TelegramBotBase.Args; using TelegramBotBase.Args;
using TelegramBotBase.Controls;
using TelegramBotBase.Controls.Inline; using TelegramBotBase.Controls.Inline;
using TelegramBotBase.Enums;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Controls namespace TelegramBotBaseTest.Tests.Controls
@ -14,28 +13,33 @@ namespace TelegramBotBaseTest.Tests.Controls
{ {
public MultiToggleButtons() public MultiToggleButtons()
{ {
this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; DeleteMode = EDeleteMode.OnLeavingForm;
this.Init += ToggleButtons_Init; Init += ToggleButtons_Init;
} }
private async Task ToggleButtons_Init(object sender, InitEventArgs e) private Task ToggleButtons_Init(object sender, InitEventArgs e)
{ {
var mtb = new MultiToggleButton(); var mtb = new MultiToggleButton
{
Options = new List<ButtonBase> { new ButtonBase("Option 1", "1"), new ButtonBase("Option 2", "2"), new ButtonBase("Option 3", "3") }
};
mtb.Options = new List<ButtonBase>() { new ButtonBase("Option 1", "1"), new ButtonBase("Option 2", "2"), new ButtonBase("Option 3", "3") };
mtb.SelectedOption = mtb.Options.FirstOrDefault(); mtb.SelectedOption = mtb.Options.FirstOrDefault();
mtb.Toggled += Tb_Toggled; mtb.Toggled += Tb_Toggled;
this.AddControl(mtb); AddControl(mtb);
mtb = new MultiToggleButton(); mtb = new MultiToggleButton
{
Options = new List<ButtonBase> { new ButtonBase("Option 4", "4"), new ButtonBase("Option 5", "5"), new ButtonBase("Option 6", "6") }
};
mtb.Options = new List<ButtonBase>() { new ButtonBase("Option 4", "4"), new ButtonBase("Option 5", "5"), new ButtonBase("Option 6", "6") };
mtb.SelectedOption = mtb.Options.FirstOrDefault(); mtb.SelectedOption = mtb.Options.FirstOrDefault();
mtb.AllowEmptySelection = false; mtb.AllowEmptySelection = false;
mtb.Toggled += Tb_Toggled; mtb.Toggled += Tb_Toggled;
this.AddControl(mtb); AddControl(mtb);
return Task.CompletedTask;
} }
private void Tb_Toggled(object sender, EventArgs e) private void Tb_Toggled(object sender, EventArgs e)
@ -43,11 +47,11 @@ namespace TelegramBotBaseTest.Tests.Controls
var tb = sender as MultiToggleButton; var tb = sender as MultiToggleButton;
if (tb.SelectedOption != null) if (tb.SelectedOption != null)
{ {
Console.WriteLine(tb.ID.ToString() + " was pressed, and toggled to " + tb.SelectedOption.Value); Console.WriteLine(tb.Id + " was pressed, and toggled to " + tb.SelectedOption.Value);
return; return;
} }
Console.WriteLine("Selection for " + tb.ID.ToString() + " has been removed."); Console.WriteLine("Selection for " + tb.Id + " has been removed.");
} }
} }
} }

View File

@ -1,41 +1,42 @@
using System; using System.Threading.Tasks;
using System.Collections.Generic; using TelegramBotBase.Args;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Base;
using TelegramBotBase.Controls.Hybrid; using TelegramBotBase.Controls.Hybrid;
using TelegramBotBase.Enums;
using TelegramBotBase.Form; using TelegramBotBase.Form;
using TelegramBotBaseTest.Tests.Controls.Subclass;
namespace TelegramBotBaseTest.Tests.Controls namespace TelegramBotBaseTest.Tests.Controls
{ {
public class MultiViewForm : AutoCleanForm public class MultiViewForm : AutoCleanForm
{ {
private MultiViewTest _mvt;
Subclass.MultiViewTest mvt = null; private ButtonGrid _bg;
ButtonGrid bg = null;
public MultiViewForm() public MultiViewForm()
{ {
this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; DeleteMode = EDeleteMode.OnLeavingForm;
this.Init += MultiViewForm_Init; Init += MultiViewForm_Init;
} }
private async Task MultiViewForm_Init(object sender, TelegramBotBase.Args.InitEventArgs e) private Task MultiViewForm_Init(object sender, InitEventArgs e)
{ {
mvt = new Subclass.MultiViewTest(); _mvt = new MultiViewTest();
AddControl(mvt); AddControl(_mvt);
bg = new ButtonGrid(); _bg = new ButtonGrid
bg.ButtonsForm = new ButtonForm(); {
bg.ButtonsForm.AddButtonRow("Back", "$back$"); ButtonsForm = new ButtonForm()
bg.ButtonClicked += Bg_ButtonClicked; };
bg.KeyboardType = TelegramBotBase.Enums.eKeyboardType.ReplyKeyboard; _bg.ButtonsForm.AddButtonRow("Back", "$back$");
AddControl(bg); _bg.ButtonClicked += Bg_ButtonClicked;
_bg.KeyboardType = EKeyboardType.ReplyKeyboard;
AddControl(_bg);
return Task.CompletedTask;
} }
private async Task Bg_ButtonClicked(object sender, TelegramBotBase.Args.ButtonClickedEventArgs e) private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e)
{ {
switch(e.Button.Value) switch(e.Button.Value)
{ {

View File

@ -1,40 +1,38 @@
using System; using System.Threading.Tasks;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Args; using TelegramBotBase.Args;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Controls.Hybrid;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Controls.Subclass namespace TelegramBotBaseTest.Tests.Controls.Subclass
{ {
public class MultiViewTest : TelegramBotBase.Controls.Hybrid.MultiView public class MultiViewTest : MultiView
{ {
public override async Task Action(MessageResult result, string value = null) public override Task Action(MessageResult result, string value = null)
{ {
switch (result.RawData) switch (result.RawData)
{ {
case "back": case "back":
this.SelectedViewIndex--; SelectedViewIndex--;
break; break;
case "next": case "next":
this.SelectedViewIndex++; SelectedViewIndex++;
break; break;
} }
return Task.CompletedTask;
} }
public override async Task RenderView(RenderViewEventArgs e) public override async Task RenderView(RenderViewEventArgs e)
{ {
ButtonForm bf = new ButtonForm(); var bf = new ButtonForm();
bf.AddButtonRow(new ButtonBase("Back", "back"), new ButtonBase("Next", "next")); bf.AddButtonRow(new ButtonBase("Back", "back"), new ButtonBase("Next", "next"));
switch (e.CurrentView) switch (e.CurrentView)

View File

@ -1,11 +1,8 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using TelegramBotBase.Args; using TelegramBotBase.Args;
using TelegramBotBase.Controls;
using TelegramBotBase.Controls.Inline; using TelegramBotBase.Controls.Inline;
using TelegramBotBase.Enums;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Controls namespace TelegramBotBaseTest.Tests.Controls
@ -14,38 +11,44 @@ namespace TelegramBotBaseTest.Tests.Controls
{ {
public ToggleButtons() public ToggleButtons()
{ {
this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; DeleteMode = EDeleteMode.OnLeavingForm;
this.Init += ToggleButtons_Init; Init += ToggleButtons_Init;
} }
private async Task ToggleButtons_Init(object sender, InitEventArgs e) private Task ToggleButtons_Init(object sender, InitEventArgs e)
{ {
var tb = new ToggleButton(); var tb = new ToggleButton
tb.Checked = true; {
Checked = true
};
tb.Toggled += Tb_Toggled; tb.Toggled += Tb_Toggled;
this.AddControl(tb); AddControl(tb);
tb = new ToggleButton(); tb = new ToggleButton
tb.Checked = false; {
Checked = false
};
tb.Toggled += Tb_Toggled; tb.Toggled += Tb_Toggled;
this.AddControl(tb); AddControl(tb);
tb = new ToggleButton(); tb = new ToggleButton
tb.Checked = true; {
Checked = true
};
tb.Toggled += Tb_Toggled; tb.Toggled += Tb_Toggled;
this.AddControl(tb); AddControl(tb);
return Task.CompletedTask;
} }
private void Tb_Toggled(object sender, EventArgs e) private void Tb_Toggled(object sender, EventArgs e)
{ {
var tb = sender as ToggleButton; var tb = sender as ToggleButton;
Console.WriteLine(tb.ID.ToString() + " was pressed, and toggled to " + (tb.Checked ? "Checked" : "Unchecked")); Console.WriteLine(tb.Id + " was pressed, and toggled to " + (tb.Checked ? "Checked" : "Unchecked"));
} }
} }
} }

View File

@ -1,31 +1,27 @@
using System; using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Form;
using TelegramBotBase.Controls;
using TelegramBotBase.Base;
using TelegramBotBase.Args; using TelegramBotBase.Args;
using TelegramBotBase.Base;
using TelegramBotBase.Controls.Inline; using TelegramBotBase.Controls.Inline;
using TelegramBotBase.Enums;
using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Controls namespace TelegramBotBaseTest.Tests.Controls
{ {
public class TreeViewForms : AutoCleanForm public class TreeViewForms : AutoCleanForm
{ {
public TreeView view { get; set; } public TreeView View { get; set; }
private int? MessageId { get; set; } private int? MessageId { get; set; }
public TreeViewForms() public TreeViewForms()
{ {
this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; DeleteMode = EDeleteMode.OnLeavingForm;
this.Init += TreeViewForms_Init; Init += TreeViewForms_Init;
} }
private async Task TreeViewForms_Init(object sender, InitEventArgs e) private Task TreeViewForms_Init(object sender, InitEventArgs e)
{ {
view = new TreeView(); View = new TreeView();
var tvn = new TreeViewNode("Cars", "cars"); var tvn = new TreeViewNode("Cars", "cars");
@ -35,7 +31,7 @@ namespace TelegramBotBaseTest.Tests.Controls
tvn.AddNode(new TreeViewNode("VW", "vw")); tvn.AddNode(new TreeViewNode("VW", "vw"));
tvn.AddNode(new TreeViewNode("Lamborghini", "lamborghini")); tvn.AddNode(new TreeViewNode("Lamborghini", "lamborghini"));
view.Nodes.Add(tvn); View.Nodes.Add(tvn);
tvn = new TreeViewNode("Fruits", "fruits"); tvn = new TreeViewNode("Fruits", "fruits");
@ -43,10 +39,10 @@ namespace TelegramBotBaseTest.Tests.Controls
tvn.AddNode(new TreeViewNode("Orange", "orange")); tvn.AddNode(new TreeViewNode("Orange", "orange"));
tvn.AddNode(new TreeViewNode("Lemon", "lemon")); tvn.AddNode(new TreeViewNode("Lemon", "lemon"));
view.Nodes.Add(tvn); View.Nodes.Add(tvn);
this.AddControl(view);
AddControl(View);
return Task.CompletedTask;
} }
public override async Task Action(MessageResult message) public override async Task Action(MessageResult message)
@ -64,7 +60,7 @@ namespace TelegramBotBaseTest.Tests.Controls
var start = new Menu(); var start = new Menu();
await this.NavigateTo(start); await NavigateTo(start);
break; break;
@ -74,26 +70,26 @@ namespace TelegramBotBaseTest.Tests.Controls
public override async Task Render(MessageResult message) public override async Task Render(MessageResult message)
{ {
String s = ""; var s = "";
s += "Selected Node: " + (this.view.SelectedNode?.Text ?? "(null)") + "\r\n"; s += "Selected Node: " + (View.SelectedNode?.Text ?? "(null)") + "\r\n";
s += "Visible Node: " + (this.view.VisibleNode?.Text ?? "(top)") + "\r\n"; s += "Visible Node: " + (View.VisibleNode?.Text ?? "(top)") + "\r\n";
s += "Visible Path: " + this.view.GetPath() + "\r\n"; s += "Visible Path: " + View.GetPath() + "\r\n";
s += "Selected Path: " + (this.view.SelectedNode?.GetPath() ?? "(null)") + "\r\n"; s += "Selected Path: " + (View.SelectedNode?.GetPath() ?? "(null)") + "\r\n";
ButtonForm bf = new ButtonForm(); var bf = new ButtonForm();
bf.AddButtonRow(new ButtonBase("Back", "back")); bf.AddButtonRow(new ButtonBase("Back", "back"));
if (MessageId != null) if (MessageId != null)
{ {
await this.Device.Edit(this.MessageId.Value, s, bf); await Device.Edit(MessageId.Value, s, bf);
} }
else else
{ {
var m = await this.Device.Send(s, bf); var m = await Device.Send(s, bf);
this.MessageId = m.MessageId; MessageId = m.MessageId;
} }
} }

View File

@ -1,10 +1,7 @@
using System; using System.Linq;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Telegram.Bot; using Telegram.Bot;
using Telegram.Bot.Types; using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types.InputFiles; using Telegram.Bot.Types.InputFiles;
using Telegram.Bot.Types.ReplyMarkups; using Telegram.Bot.Types.ReplyMarkups;
using TelegramBotBase.Base; using TelegramBotBase.Base;
@ -18,68 +15,68 @@ namespace TelegramBotBaseTest.Tests
public override async Task SentData(DataResult data) public override async Task SentData(DataResult data)
{ {
String tmp = ""; var tmp = "";
InputOnlineFile file; InputOnlineFile file;
switch (data.Type) switch (data.Type)
{ {
case Telegram.Bot.Types.Enums.MessageType.Contact: case MessageType.Contact:
tmp += "Firstname: " + data.Contact.FirstName + "\r\n"; tmp += "Firstname: " + data.Contact.FirstName + "\r\n";
tmp += "Lastname: " + data.Contact.LastName + "\r\n"; tmp += "Lastname: " + data.Contact.LastName + "\r\n";
tmp += "Phonenumber: " + data.Contact.PhoneNumber + "\r\n"; tmp += "Phonenumber: " + data.Contact.PhoneNumber + "\r\n";
tmp += "UserId: " + data.Contact.UserId + "\r\n"; tmp += "UserId: " + data.Contact.UserId + "\r\n";
await this.Device.Send("Your contact: \r\n" + tmp, replyTo: data.MessageId); await Device.Send("Your contact: \r\n" + tmp, replyTo: data.MessageId);
break; break;
case Telegram.Bot.Types.Enums.MessageType.Document: case MessageType.Document:
file = new InputOnlineFile(data.Document.FileId); file = new InputOnlineFile(data.Document.FileId);
await this.Device.SendDocument(file, "Your uploaded document"); await Device.SendDocument(file, "Your uploaded document");
break; break;
case Telegram.Bot.Types.Enums.MessageType.Video: case MessageType.Video:
file = new InputOnlineFile(data.Document.FileId); file = new InputOnlineFile(data.Document.FileId);
await this.Device.SendDocument(file, "Your uploaded video"); await Device.SendDocument(file, "Your uploaded video");
break; break;
case Telegram.Bot.Types.Enums.MessageType.Audio: case MessageType.Audio:
file = new InputOnlineFile(data.Document.FileId); file = new InputOnlineFile(data.Document.FileId);
await this.Device.SendDocument(file, "Your uploaded audio"); await Device.SendDocument(file, "Your uploaded audio");
break; break;
case Telegram.Bot.Types.Enums.MessageType.Location: case MessageType.Location:
tmp += "Lat: " + data.Location.Latitude + "\r\n"; tmp += "Lat: " + data.Location.Latitude + "\r\n";
tmp += "Lng: " + data.Location.Longitude + "\r\n"; tmp += "Lng: " + data.Location.Longitude + "\r\n";
await this.Device.Send("Your location: \r\n" + tmp, replyTo: data.MessageId); await Device.Send("Your location: \r\n" + tmp, replyTo: data.MessageId);
break; break;
case Telegram.Bot.Types.Enums.MessageType.Photo: case MessageType.Photo:
InputOnlineFile photo = new InputOnlineFile(data.Photos.Last().FileId); var photo = new InputOnlineFile(data.Photos.Last().FileId);
await this.Device.Send("Your image: ", replyTo: data.MessageId); await Device.Send("Your image: ", replyTo: data.MessageId);
await this.Client.TelegramClient.SendPhotoAsync(this.Device.DeviceId, photo); await Client.TelegramClient.SendPhotoAsync(Device.DeviceId, photo);
break; break;
default: default:
await this.Device.Send("Unknown response"); await Device.Send("Unknown response");
break; break;
} }
@ -97,13 +94,13 @@ namespace TelegramBotBaseTest.Tests
{ {
case "contact": case "contact":
await this.Device.RequestContact(); await Device.RequestContact();
break; break;
case "location": case "location":
await this.Device.RequestLocation(); await Device.RequestLocation();
break; break;
@ -113,7 +110,7 @@ namespace TelegramBotBaseTest.Tests
var start = new Menu(); var start = new Menu();
await this.NavigateTo(start); await NavigateTo(start);
break; break;
} }
@ -123,7 +120,7 @@ namespace TelegramBotBaseTest.Tests
public override async Task Render(MessageResult message) public override async Task Render(MessageResult message)
{ {
ButtonForm bf = new ButtonForm(); var bf = new ButtonForm();
bf.AddButtonRow(new ButtonBase("Request User contact", "contact")); bf.AddButtonRow(new ButtonBase("Request User contact", "contact"));
@ -133,7 +130,7 @@ namespace TelegramBotBaseTest.Tests
InlineKeyboardMarkup ikv = bf; InlineKeyboardMarkup ikv = bf;
await this.Device.Send("Please upload a contact, photo, video, audio, document or location.", bf); await Device.Send("Please upload a contact, photo, video, audio, document or location.", bf);

View File

@ -3,9 +3,9 @@ using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Text; using Newtonsoft.Json;
using TelegramBotBase.Controls.Hybrid; using TelegramBotBase.Controls.Hybrid;
using TelegramBotBase.Datasources; using TelegramBotBase.DataSources;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Datasources namespace TelegramBotBaseTest.Tests.Datasources
@ -13,28 +13,28 @@ namespace TelegramBotBaseTest.Tests.Datasources
public class CustomDataSource : ButtonFormDataSource public class CustomDataSource : ButtonFormDataSource
{ {
public List<String> Countries = new List<string>() { "Country 1", "Country 2", "Country 3" }; public List<string> Countries = new List<string> { "Country 1", "Country 2", "Country 3" };
public CustomDataSource() public CustomDataSource()
{ {
loadData(); LoadData();
} }
/// <summary> /// <summary>
/// This method has the example purpose of creating and loading some example data. /// This method has the example purpose of creating and loading some example data.
/// When using a database you do not need this kind of method. /// When using a database you do not need this kind of method.
/// </summary> /// </summary>
private void loadData() private void LoadData()
{ {
//Exists data source? Read it //Exists data source? Read it
if (File.Exists(AppContext.BaseDirectory + "countries.json")) if (File.Exists(AppContext.BaseDirectory + "countries.json"))
{ {
try try
{ {
var List = Newtonsoft.Json.JsonConvert.DeserializeObject<List<String>>(File.ReadAllText("countries.json")); var list = JsonConvert.DeserializeObject<List<string>>(File.ReadAllText("countries.json"));
Countries = List; Countries = list;
} }
catch catch
{ {
@ -52,7 +52,7 @@ namespace TelegramBotBaseTest.Tests.Datasources
Countries = countries; Countries = countries;
var tmp = Newtonsoft.Json.JsonConvert.SerializeObject(countries); var tmp = JsonConvert.SerializeObject(countries);
File.WriteAllText( AppContext.BaseDirectory + "countries.json", tmp); File.WriteAllText( AppContext.BaseDirectory + "countries.json", tmp);
} }
@ -76,7 +76,7 @@ namespace TelegramBotBaseTest.Tests.Datasources
{ {
var items = Countries.Skip(start).Take(count); var items = Countries.Skip(start).Take(count);
List<ButtonRow> lst = new List<ButtonRow>(); var lst = new List<ButtonRow>();
foreach (var c in items) foreach (var c in items)
{ {
lst.Add(Render(c)); lst.Add(Render(c));
@ -87,7 +87,7 @@ namespace TelegramBotBaseTest.Tests.Datasources
public override List<ButtonRow> AllItems() public override List<ButtonRow> AllItems()
{ {
List<ButtonRow> lst = new List<ButtonRow>(); var lst = new List<ButtonRow>();
foreach (var c in Countries) foreach (var c in Countries)
{ {
lst.Add(Render(c)); lst.Add(Render(c));
@ -97,9 +97,9 @@ namespace TelegramBotBaseTest.Tests.Datasources
public override ButtonForm PickItems(int start, int count, string filter = null) public override ButtonForm PickItems(int start, int count, string filter = null)
{ {
List<ButtonRow> rows = ItemRange(start, count); var rows = ItemRange(start, count);
ButtonForm lst = new ButtonForm(); var lst = new ButtonForm();
foreach (var c in rows) foreach (var c in rows)
{ {
lst.AddButtonRow(c); lst.AddButtonRow(c);
@ -109,9 +109,9 @@ namespace TelegramBotBaseTest.Tests.Datasources
public override ButtonForm PickAllItems(string filter = null) public override ButtonForm PickAllItems(string filter = null)
{ {
List<ButtonRow> rows = AllItems(); var rows = AllItems();
ButtonForm bf = new ButtonForm(); var bf = new ButtonForm();
bf.AddButtonRows(rows); bf.AddButtonRows(rows);
@ -128,36 +128,16 @@ namespace TelegramBotBaseTest.Tests.Datasources
public override ButtonRow Render(object data) public override ButtonRow Render(object data)
{ {
var s = data as String; if (!(data is string s))
if (s == null)
return new ButtonRow(new ButtonBase("Empty", "zero")); return new ButtonRow(new ButtonBase("Empty", "zero"));
return new ButtonRow(new ButtonBase(s, s)); return new ButtonRow(new ButtonBase(s, s));
} }
public override int Count public override int Count => Countries.Count;
{
get
{
return Countries.Count;
}
}
public override int ColumnCount public override int ColumnCount => 1;
{
get
{
return 1;
}
}
public override int RowCount
{
get
{
return this.Count;
}
}
public override int RowCount => Count;
} }
} }

View File

@ -1,42 +1,43 @@
using System; using System.Threading.Tasks;
using System.Collections.Generic; using TelegramBotBase.Args;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Base;
using TelegramBotBase.Controls.Hybrid; using TelegramBotBase.Controls.Hybrid;
using TelegramBotBase.Enums;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Datasources namespace TelegramBotBaseTest.Tests.Datasources
{ {
public class List : FormBase public class List : FormBase
{ {
ButtonGrid __buttons = null; private ButtonGrid _buttons;
public List() public List()
{ {
this.Init += List_Init; Init += List_Init;
} }
private async Task List_Init(object sender, TelegramBotBase.Args.InitEventArgs e) private Task List_Init(object sender, InitEventArgs e)
{ {
__buttons = new ButtonGrid(); _buttons = new ButtonGrid
{
EnablePaging = true,
EnableSearch = false
};
__buttons.EnablePaging = true; _buttons.ButtonClicked += __buttons_ButtonClicked;
__buttons.EnableSearch = false; _buttons.KeyboardType = EKeyboardType.ReplyKeyboard;
__buttons.ButtonClicked += __buttons_ButtonClicked; _buttons.DeleteReplyMessage = true;
__buttons.KeyboardType = TelegramBotBase.Enums.eKeyboardType.ReplyKeyboard;
__buttons.DeleteReplyMessage = true;
__buttons.HeadLayoutButtonRow = new ButtonRow(new ButtonBase("Back", "back")); _buttons.HeadLayoutButtonRow = new ButtonRow(new ButtonBase("Back", "back"));
var cds = new CustomDataSource(); var cds = new CustomDataSource();
__buttons.DataSource = cds; _buttons.DataSource = cds;
AddControl(__buttons); AddControl(_buttons);
return Task.CompletedTask;
} }
private async Task __buttons_ButtonClicked(object sender, TelegramBotBase.Args.ButtonClickedEventArgs e) private async Task __buttons_ButtonClicked(object sender, ButtonClickedEventArgs e)
{ {
switch(e.Button.Value) switch(e.Button.Value)
{ {

View File

@ -1,6 +1,4 @@
using System; using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using TelegramBotBase.Args; using TelegramBotBase.Args;
using TelegramBotBase.Base; using TelegramBotBase.Base;
@ -8,24 +6,24 @@ using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Groups namespace TelegramBotBaseTest.Tests.Groups
{ {
public class GroupChange : TelegramBotBase.Form.GroupForm public class GroupChange : GroupForm
{ {
public GroupChange() public GroupChange()
{ {
this.Opened += GroupChange_Opened; Opened += GroupChange_Opened;
} }
private async Task GroupChange_Opened(object sender, EventArgs e) private async Task GroupChange_Opened(object sender, EventArgs e)
{ {
ButtonForm bf = new ButtonForm(); var bf = new ButtonForm();
bf.AddButtonRow(new ButtonBase("Open GroupChange Test", "groupchange")); bf.AddButtonRow(new ButtonBase("Open GroupChange Test", "groupchange"));
bf.AddButtonRow(new ButtonBase("Open WelcomeUser Test", "welcomeuser")); bf.AddButtonRow(new ButtonBase("Open WelcomeUser Test", "welcomeuser"));
bf.AddButtonRow(new ButtonBase("Open LinkReplace Test", "linkreplace")); bf.AddButtonRow(new ButtonBase("Open LinkReplace Test", "linkreplace"));
await this.Device.Send("GroupChange started, click to switch", bf); await Device.Send("GroupChange started, click to switch", bf);
} }
@ -46,21 +44,21 @@ namespace TelegramBotBaseTest.Tests.Groups
var gc = new GroupChange(); var gc = new GroupChange();
await this.NavigateTo(gc); await NavigateTo(gc);
break; break;
case "welcomeuser": case "welcomeuser":
var wu = new WelcomeUser(); var wu = new WelcomeUser();
await this.NavigateTo(wu); await NavigateTo(wu);
break; break;
case "linkreplace": case "linkreplace":
var lr = new LinkReplaceTest(); var lr = new LinkReplaceTest();
await this.NavigateTo(lr); await NavigateTo(lr);
break; break;
} }
@ -69,7 +67,7 @@ namespace TelegramBotBaseTest.Tests.Groups
public override async Task OnGroupChanged(GroupChangedEventArgs e) public override async Task OnGroupChanged(GroupChangedEventArgs e)
{ {
await this.Device.Send("Group has been changed by " + e.OriginalMessage.Message.From.FirstName + " " + e.OriginalMessage.Message.From.LastName); await Device.Send("Group has been changed by " + e.OriginalMessage.Message.From.FirstName + " " + e.OriginalMessage.Message.From.LastName);
} }
} }

View File

@ -1,37 +1,36 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading.Tasks; using System.Threading.Tasks;
using Telegram.Bot.Types; using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Groups namespace TelegramBotBaseTest.Tests.Groups
{ {
public class LinkReplaceTest : TelegramBotBase.Form.GroupForm public class LinkReplaceTest : GroupForm
{ {
private Dictionary<long, int> Counter { get; set; } = new Dictionary<long, int>();
Dictionary<long, int> Counter { get; set; } = new Dictionary<long, int>();
private const int Maximum = 3; private const int Maximum = 3;
public LinkReplaceTest() public LinkReplaceTest()
{ {
this.Opened += LinkReplaceTest_Opened; Opened += LinkReplaceTest_Opened;
} }
private async Task LinkReplaceTest_Opened(object sender, EventArgs e) private async Task LinkReplaceTest_Opened(object sender, EventArgs e)
{ {
ButtonForm bf = new ButtonForm(); var bf = new ButtonForm();
bf.AddButtonRow(new ButtonBase("Open GroupChange Test", "groupchange")); bf.AddButtonRow(new ButtonBase("Open GroupChange Test", "groupchange"));
bf.AddButtonRow(new ButtonBase("Open WelcomeUser Test", "welcomeuser")); bf.AddButtonRow(new ButtonBase("Open WelcomeUser Test", "welcomeuser"));
bf.AddButtonRow(new ButtonBase("Open LinkReplace Test", "linkreplace")); bf.AddButtonRow(new ButtonBase("Open LinkReplace Test", "linkreplace"));
await this.Device.Send("LinkReplaceTest started, click to switch", bf); await Device.Send("LinkReplaceTest started, click to switch", bf);
} }
@ -51,21 +50,21 @@ namespace TelegramBotBaseTest.Tests.Groups
var gc = new GroupChange(); var gc = new GroupChange();
await this.NavigateTo(gc); await NavigateTo(gc);
break; break;
case "welcomeuser": case "welcomeuser":
var wu = new WelcomeUser(); var wu = new WelcomeUser();
await this.NavigateTo(wu); await NavigateTo(wu);
break; break;
case "linkreplace": case "linkreplace":
var lr = new LinkReplaceTest(); var lr = new LinkReplaceTest();
await this.NavigateTo(lr); await NavigateTo(lr);
break; break;
} }
@ -86,23 +85,25 @@ namespace TelegramBotBaseTest.Tests.Groups
var u = await Device.GetChatUser(from); var u = await Device.GetChatUser(from);
//Don't kick Admins or Creators //Don't kick Admins or Creators
if (u.Status == Telegram.Bot.Types.Enums.ChatMemberStatus.Administrator | u.Status == Telegram.Bot.Types.Enums.ChatMemberStatus.Creator) if (u.Status == ChatMemberStatus.Administrator | u.Status == ChatMemberStatus.Creator)
{ {
await this.Device.Send("You won't get kicked,...not this time."); await Device.Send("You won't get kicked,...not this time.");
return; return;
} }
await e.Device.DeleteMessage(e.MessageId); await e.Device.DeleteMessage(e.MessageId);
var cp = new ChatPermissions(); var cp = new ChatPermissions
cp.CanAddWebPagePreviews = false; {
cp.CanChangeInfo = false; CanAddWebPagePreviews = false,
cp.CanInviteUsers = false; CanChangeInfo = false,
cp.CanPinMessages = false; CanInviteUsers = false,
cp.CanSendMediaMessages = false; CanPinMessages = false,
cp.CanSendMessages = false; CanSendMediaMessages = false,
cp.CanSendOtherMessages = false; CanSendMessages = false,
cp.CanSendPolls = false; CanSendOtherMessages = false,
CanSendPolls = false
};
//Collect user "mistakes" with sending url, after 3 he gets kicked out. //Collect user "mistakes" with sending url, after 3 he gets kicked out.
if (Counter.ContainsKey(from)) if (Counter.ContainsKey(from))
@ -147,12 +148,12 @@ namespace TelegramBotBaseTest.Tests.Groups
/// </summary> /// </summary>
/// <param name="str"></param> /// <param name="str"></param>
/// <returns></returns> /// <returns></returns>
private bool HasLinks(String str) private bool HasLinks(string str)
{ {
var tmp = str; var tmp = str;
var pattern = @"^(http|https|ftp|)\://|[a-zA-Z0-9\-\.]+\.[a-zA-Z](:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&amp;%\$#\=~])*[^\.\,\)\(\s]$"; var pattern = @"^(http|https|ftp|)\://|[a-zA-Z0-9\-\.]+\.[a-zA-Z](:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&amp;%\$#\=~])*[^\.\,\)\(\s]$";
Regex r = new Regex(pattern); var r = new Regex(pattern);
var matches = r.Matches(tmp); var matches = r.Matches(tmp);

View File

@ -1,33 +1,32 @@
using System; using System;
using System.Collections.Generic;
using System.Text;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Telegram.Bot.Types.Enums;
using TelegramBotBase.Args;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Form; using TelegramBotBase.Form;
using TelegramBotBase.Args;
namespace TelegramBotBaseTest.Tests.Groups namespace TelegramBotBaseTest.Tests.Groups
{ {
public class WelcomeUser : TelegramBotBase.Form.GroupForm public class WelcomeUser : GroupForm
{ {
public WelcomeUser() public WelcomeUser()
{ {
this.Opened += WelcomeUser_Opened; Opened += WelcomeUser_Opened;
} }
private async Task WelcomeUser_Opened(object sender, EventArgs e) private async Task WelcomeUser_Opened(object sender, EventArgs e)
{ {
ButtonForm bf = new ButtonForm(); var bf = new ButtonForm();
bf.AddButtonRow(new ButtonBase("Open GroupChange Test", "groupchange")); bf.AddButtonRow(new ButtonBase("Open GroupChange Test", "groupchange"));
bf.AddButtonRow(new ButtonBase("Open WelcomeUser Test", "welcomeuser")); bf.AddButtonRow(new ButtonBase("Open WelcomeUser Test", "welcomeuser"));
bf.AddButtonRow(new ButtonBase("Open LinkReplace Test", "linkreplace")); bf.AddButtonRow(new ButtonBase("Open LinkReplace Test", "linkreplace"));
await this.Device.Send("WelcomeUser started, click to switch", bf); await Device.Send("WelcomeUser started, click to switch", bf);
} }
@ -47,21 +46,21 @@ namespace TelegramBotBaseTest.Tests.Groups
var gc = new GroupChange(); var gc = new GroupChange();
await this.NavigateTo(gc); await NavigateTo(gc);
break; break;
case "welcomeuser": case "welcomeuser":
var wu = new WelcomeUser(); var wu = new WelcomeUser();
await this.NavigateTo(wu); await NavigateTo(wu);
break; break;
case "linkreplace": case "linkreplace":
var lr = new LinkReplaceTest(); var lr = new LinkReplaceTest();
await this.NavigateTo(lr); await NavigateTo(lr);
break; break;
} }
@ -71,15 +70,15 @@ namespace TelegramBotBaseTest.Tests.Groups
public override async Task OnMemberChanges(MemberChangeEventArgs e) public override async Task OnMemberChanges(MemberChangeEventArgs e)
{ {
if (e.Type == Telegram.Bot.Types.Enums.MessageType.ChatMembersAdded) if (e.Type == MessageType.ChatMembersAdded)
{ {
await this.Device.Send("Welcome you new members!\r\n\r\n" + e.Members.Select(a => a.FirstName + " " + a.LastName).Aggregate((a, b) => a + "\r\n" + b)); await Device.Send("Welcome you new members!\r\n\r\n" + e.Members.Select(a => a.FirstName + " " + a.LastName).Aggregate((a, b) => a + "\r\n" + b));
} }
else if (e.Type == Telegram.Bot.Types.Enums.MessageType.ChatMemberLeft) else if (e.Type == MessageType.ChatMemberLeft)
{ {
await this.Device.Send(e.Members.Select(a => a.FirstName + " " + a.LastName).Aggregate((a, b) => a + " and " + b) + " has left the group"); await Device.Send(e.Members.Select(a => a.FirstName + " " + a.LastName).Aggregate((a, b) => a + " and " + b) + " has left the group");
} }

View File

@ -1,11 +1,11 @@
using System; using System.Threading.Tasks;
using System.Collections.Generic; using Telegram.Bot.Types.Enums;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Enums;
using TelegramBotBase.Form; using TelegramBotBase.Form;
using TelegramBotBaseTest.Tests.Controls; using TelegramBotBaseTest.Tests.Controls;
using TelegramBotBaseTest.Tests.Datasources;
using TelegramBotBaseTest.Tests.Groups;
namespace TelegramBotBaseTest.Tests namespace TelegramBotBaseTest.Tests
{ {
@ -13,18 +13,18 @@ namespace TelegramBotBaseTest.Tests
{ {
public Menu() public Menu()
{ {
this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; DeleteMode = EDeleteMode.OnLeavingForm;
} }
public override async Task Load(MessageResult message) public override async Task Load(MessageResult message)
{ {
if (message.Message.Chat.Type == Telegram.Bot.Types.Enums.ChatType.Group | message.Message.Chat.Type == Telegram.Bot.Types.Enums.ChatType.Supergroup) if (message.Message.Chat.Type == ChatType.Group | message.Message.Chat.Type == ChatType.Supergroup)
{ {
var sf = new TelegramBotBaseTest.Tests.Groups.WelcomeUser(); var sf = new WelcomeUser();
await this.NavigateTo(sf); await NavigateTo(sf);
} }
@ -49,7 +49,7 @@ namespace TelegramBotBaseTest.Tests
var sf = new SimpleForm(); var sf = new SimpleForm();
await this.NavigateTo(sf); await NavigateTo(sf);
break; break;
@ -57,7 +57,7 @@ namespace TelegramBotBaseTest.Tests
var bf = new ButtonTestForm(); var bf = new ButtonTestForm();
await this.NavigateTo(bf); await NavigateTo(bf);
break; break;
@ -65,7 +65,7 @@ namespace TelegramBotBaseTest.Tests
var pf = new ProgressTest(); var pf = new ProgressTest();
await this.NavigateTo(pf); await NavigateTo(pf);
break; break;
@ -73,7 +73,7 @@ namespace TelegramBotBaseTest.Tests
var reg = new Register.Start(); var reg = new Register.Start();
await this.NavigateTo(reg); await NavigateTo(reg);
break; break;
@ -81,7 +81,7 @@ namespace TelegramBotBaseTest.Tests
var form1 = new TestForm(); var form1 = new TestForm();
await this.NavigateTo(form1); await NavigateTo(form1);
break; break;
@ -89,7 +89,7 @@ namespace TelegramBotBaseTest.Tests
var form2 = new TestForm2(); var form2 = new TestForm2();
await this.NavigateTo(form2); await NavigateTo(form2);
break; break;
@ -97,71 +97,71 @@ namespace TelegramBotBaseTest.Tests
var data = new DataForm(); var data = new DataForm();
await this.NavigateTo(data); await NavigateTo(data);
break; break;
case "calendar": case "calendar":
var calendar = new Controls.CalendarPickerForm(); var calendar = new CalendarPickerForm();
await this.NavigateTo(calendar); await NavigateTo(calendar);
break; break;
case "month": case "month":
var month = new Controls.MonthPickerForm(); var month = new MonthPickerForm();
await this.NavigateTo(month); await NavigateTo(month);
break; break;
case "treeview": case "treeview":
var tree = new Controls.TreeViewForms(); var tree = new TreeViewForms();
await this.NavigateTo(tree); await NavigateTo(tree);
break; break;
case "togglebuttons": case "togglebuttons":
var tb = new Controls.ToggleButtons(); var tb = new ToggleButtons();
await this.NavigateTo(tb); await NavigateTo(tb);
break; break;
case "multitogglebuttons": case "multitogglebuttons":
var mtb = new Controls.MultiToggleButtons(); var mtb = new MultiToggleButtons();
await this.NavigateTo(mtb); await NavigateTo(mtb);
break; break;
case "buttongrid": case "buttongrid":
var bg = new Controls.ButtonGridForm(); var bg = new ButtonGridForm();
await this.NavigateTo(bg); await NavigateTo(bg);
break; break;
case "buttongridfilter": case "buttongridfilter":
var bg2 = new Controls.ButtonGridPagingForm(); var bg2 = new ButtonGridPagingForm();
await this.NavigateTo(bg2); await NavigateTo(bg2);
break; break;
case "buttongridtags": case "buttongridtags":
var bg3 = new Controls.ButtonGridTagForm(); var bg3 = new ButtonGridTagForm();
await this.NavigateTo(bg3); await NavigateTo(bg3);
break; break;
@ -194,7 +194,7 @@ namespace TelegramBotBaseTest.Tests
case "dynamicbuttongrid": case "dynamicbuttongrid":
var dg = new Datasources.List(); var dg = new List();
await NavigateTo(dg); await NavigateTo(dg);
@ -220,7 +220,7 @@ namespace TelegramBotBaseTest.Tests
public override async Task Render(MessageResult message) public override async Task Render(MessageResult message)
{ {
ButtonForm btn = new ButtonForm(); var btn = new ButtonForm();
btn.AddButtonRow(new ButtonBase("#1 Simple Text", new CallbackData("a", "text").Serialize()), new ButtonBase("#2 Button Test", new CallbackData("a", "buttons").Serialize())); btn.AddButtonRow(new ButtonBase("#1 Simple Text", new CallbackData("a", "text").Serialize()), new ButtonBase("#2 Button Test", new CallbackData("a", "buttons").Serialize()));
btn.AddButtonRow(new ButtonBase("#3 Progress Bar", new CallbackData("a", "progress").Serialize())); btn.AddButtonRow(new ButtonBase("#3 Progress Bar", new CallbackData("a", "progress").Serialize()));
@ -256,7 +256,7 @@ namespace TelegramBotBaseTest.Tests
btn.AddButtonRow(new ButtonBase("#19 Notifications", new CallbackData("a", "notifications").Serialize())); btn.AddButtonRow(new ButtonBase("#19 Notifications", new CallbackData("a", "notifications").Serialize()));
await this.Device.Send("Choose your test:", btn); await Device.Send("Choose your test:", btn);
} }

View File

@ -1,13 +1,11 @@
using System; using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using TelegramBotBase.Form; using TelegramBotBase.Form;
using TelegramBotBase.Form.Navigation; using TelegramBotBase.Form.Navigation;
namespace TelegramBotBaseTest.Tests.Navigation namespace TelegramBotBaseTest.Tests.Navigation
{ {
class CustomController : NavigationController internal class CustomController : NavigationController
{ {
public CustomController(FormBase form) : base(form) public CustomController(FormBase form) : base(form)
{ {
@ -17,7 +15,7 @@ namespace TelegramBotBaseTest.Tests.Navigation
public override Task PushAsync(FormBase form, params object[] args) public override Task PushAsync(FormBase form, params object[] args)
{ {
Console.WriteLine($"Pushes form (Count on stack {this.Index + 1})"); Console.WriteLine($"Pushes form (Count on stack {Index + 1})");
//Device.Send($"Pushes form (Count on stack {this.Index + 1})"); //Device.Send($"Pushes form (Count on stack {this.Index + 1})");
return base.PushAsync(form, args); return base.PushAsync(form, args);
@ -26,7 +24,7 @@ namespace TelegramBotBaseTest.Tests.Navigation
public override Task PopAsync() public override Task PopAsync()
{ {
Console.WriteLine($"Pops one form (Count on stack {this.Index + 1})"); Console.WriteLine($"Pops one form (Count on stack {Index + 1})");
//Device.Send($"Pops one form (Count on stack {this.Index + 1})"); //Device.Send($"Pops one form (Count on stack {this.Index + 1})");
return base.PopAsync(); return base.PopAsync();
@ -34,7 +32,7 @@ namespace TelegramBotBaseTest.Tests.Navigation
public override Task PopToRootAsync() public override Task PopToRootAsync()
{ {
Console.WriteLine($"Moved back to root (Count on stack {this.Index + 1})"); Console.WriteLine($"Moved back to root (Count on stack {Index + 1})");
//Device.Send($"Moved back to root (Count on stack {this.Index + 1})"); //Device.Send($"Moved back to root (Count on stack {this.Index + 1})");
return base.PopToRootAsync(); return base.PopToRootAsync();

View File

@ -1,6 +1,4 @@
using System; using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Telegram.Bot.Types; using Telegram.Bot.Types;
using TelegramBotBase.Base; using TelegramBotBase.Base;
@ -10,19 +8,19 @@ namespace TelegramBotBaseTest.Tests.Navigation
{ {
public class Form1 : FormBase public class Form1 : FormBase
{ {
Message msg = null; private Message _msg;
public Form1() public Form1()
{ {
this.Closed += Form1_Closed; Closed += Form1_Closed;
} }
private async Task Form1_Closed(object sender, EventArgs e) private async Task Form1_Closed(object sender, EventArgs e)
{ {
if (msg == null) if (_msg == null)
return; return;
await Device.DeleteMessage(msg); await Device.DeleteMessage(_msg);
} }
public override async Task Action(MessageResult message) public override async Task Action(MessageResult message)
@ -71,7 +69,7 @@ namespace TelegramBotBaseTest.Tests.Navigation
public override async Task Render(MessageResult message) public override async Task Render(MessageResult message)
{ {
if (msg != null) if (_msg != null)
return; return;
var bf = new ButtonForm(); var bf = new ButtonForm();
@ -79,7 +77,7 @@ namespace TelegramBotBaseTest.Tests.Navigation
bf.AddButtonRow("Previous page", "previous"); bf.AddButtonRow("Previous page", "previous");
bf.AddButtonRow("Back to root", "root"); bf.AddButtonRow("Back to root", "root");
msg = await Device.Send($"Choose your options (Count on stack {NavigationController.Index + 1})", bf); _msg = await Device.Send($"Choose your options (Count on stack {NavigationController.Index + 1})", bf);
} }

View File

@ -1,30 +1,18 @@
using System; using System.Threading.Tasks;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot.Types; using Telegram.Bot.Types;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Form; using TelegramBotBase.Form;
using TelegramBotBase.Form.Navigation;
namespace TelegramBotBaseTest.Tests.Navigation namespace TelegramBotBaseTest.Tests.Navigation
{ {
public class Start : FormBase public class Start : FormBase
{ {
private Message _msg;
Message msg = null;
public Start() public override Task Load(MessageResult message)
{ {
return Task.CompletedTask;
}
public override async Task Load(MessageResult message)
{
} }
public override async Task Action(MessageResult message) public override async Task Action(MessageResult message)
@ -50,10 +38,10 @@ namespace TelegramBotBaseTest.Tests.Navigation
await NavigateTo(nc); await NavigateTo(nc);
if (msg == null) if (_msg == null)
return; return;
await Device.DeleteMessage(msg); await Device.DeleteMessage(_msg);
break; break;
@ -65,10 +53,10 @@ namespace TelegramBotBaseTest.Tests.Navigation
await NavigateTo(mn); await NavigateTo(mn);
if (msg == null) if (_msg == null)
return; return;
await Device.DeleteMessage(msg); await Device.DeleteMessage(_msg);
break; break;
} }
@ -82,7 +70,7 @@ namespace TelegramBotBaseTest.Tests.Navigation
bf.AddButtonRow("Yes", "yes"); bf.AddButtonRow("Yes", "yes");
bf.AddButtonRow("No", "no"); bf.AddButtonRow("No", "no");
msg = await Device.Send("Open controller?", bf); _msg = await Device.Send("Open controller?", bf);
} }

View File

@ -1,19 +1,17 @@
using System; using System.Threading.Tasks;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Enums;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Notifications namespace TelegramBotBaseTest.Tests.Notifications
{ {
public class Start : AutoCleanForm public class Start : AutoCleanForm
{ {
bool sent = false; private bool _sent;
public Start() public Start()
{ {
this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; DeleteMode = EDeleteMode.OnLeavingForm;
} }
public override async Task Action(MessageResult message) public override async Task Action(MessageResult message)
@ -46,7 +44,7 @@ namespace TelegramBotBaseTest.Tests.Notifications
public override async Task Render(MessageResult message) public override async Task Render(MessageResult message)
{ {
if (sent) if (_sent)
return; return;
var bf = new ButtonForm(); var bf = new ButtonForm();
@ -56,7 +54,7 @@ namespace TelegramBotBaseTest.Tests.Notifications
await Device.Send("Choose your test", bf); await Device.Send("Choose your test", bf);
sent = true; _sent = true;
} }
} }

View File

@ -1,11 +1,9 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Controls.Inline; using TelegramBotBase.Controls.Inline;
using TelegramBotBase.Enums;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests namespace TelegramBotBaseTest.Tests
@ -15,15 +13,15 @@ namespace TelegramBotBaseTest.Tests
public ProgressTest() public ProgressTest()
{ {
this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; DeleteMode = EDeleteMode.OnLeavingForm;
this.Opened += ProgressTest_Opened; Opened += ProgressTest_Opened;
this.Closed += ProgressTest_Closed; Closed += ProgressTest_Closed;
} }
private async Task ProgressTest_Opened(object sender, EventArgs e) private async Task ProgressTest_Opened(object sender, EventArgs e)
{ {
await this.Device.Send("Welcome to ProgressTest"); await Device.Send("Welcome to ProgressTest");
} }
public override async Task Action(MessageResult message) public override async Task Action(MessageResult message)
@ -36,42 +34,52 @@ namespace TelegramBotBaseTest.Tests
if (call == null) if (call == null)
return; return;
ProgressBar Bar = null; ProgressBar bar = null;
switch (call.Value) switch (call.Value)
{ {
case "standard": case "standard":
Bar = new ProgressBar(0, 100, ProgressBar.eProgressStyle.standard); bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.standard)
Bar.Device = this.Device; {
Device = Device
};
break; break;
case "squares": case "squares":
Bar = new ProgressBar(0, 100, ProgressBar.eProgressStyle.squares); bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.squares)
Bar.Device = this.Device; {
Device = Device
};
break; break;
case "circles": case "circles":
Bar = new ProgressBar(0, 100, ProgressBar.eProgressStyle.circles); bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.circles)
Bar.Device = this.Device; {
Device = Device
};
break; break;
case "lines": case "lines":
Bar = new ProgressBar(0, 100, ProgressBar.eProgressStyle.lines); bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.lines)
Bar.Device = this.Device; {
Device = Device
};
break; break;
case "squaredlines": case "squaredlines":
Bar = new ProgressBar(0, 100, ProgressBar.eProgressStyle.squaredLines); bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.squaredLines)
Bar.Device = this.Device; {
Device = Device
};
break; break;
@ -79,7 +87,7 @@ namespace TelegramBotBaseTest.Tests
var sf = new Menu(); var sf = new Menu();
await this.NavigateTo(sf); await NavigateTo(sf);
return; return;
@ -91,14 +99,14 @@ namespace TelegramBotBaseTest.Tests
//Render Progress bar and show some "example" progress //Render Progress bar and show some "example" progress
await Bar.Render(message); await bar.Render(message);
this.Controls.Add(Bar); Controls.Add(bar);
for (int i = 0; i <= 100; i++) for (var i = 0; i <= 100; i++)
{ {
Bar.Value++; bar.Value++;
await Bar.Render(message); await bar.Render(message);
Thread.Sleep(250); Thread.Sleep(250);
} }
@ -109,7 +117,7 @@ namespace TelegramBotBaseTest.Tests
public override async Task Render(MessageResult message) public override async Task Render(MessageResult message)
{ {
ButtonForm btn = new ButtonForm(); var btn = new ButtonForm();
btn.AddButtonRow(new ButtonBase("Standard", new CallbackData("a", "standard").Serialize()), new ButtonBase("Squares", new CallbackData("a", "squares").Serialize())); btn.AddButtonRow(new ButtonBase("Standard", new CallbackData("a", "standard").Serialize()), new ButtonBase("Squares", new CallbackData("a", "squares").Serialize()));
btn.AddButtonRow(new ButtonBase("Circles", new CallbackData("a", "circles").Serialize()), new ButtonBase("Lines", new CallbackData("a", "lines").Serialize())); btn.AddButtonRow(new ButtonBase("Circles", new CallbackData("a", "circles").Serialize()), new ButtonBase("Lines", new CallbackData("a", "lines").Serialize()));
@ -118,12 +126,12 @@ namespace TelegramBotBaseTest.Tests
btn.AddButtonRow(new ButtonBase("Back to start", new CallbackData("a", "start").Serialize())); btn.AddButtonRow(new ButtonBase("Back to start", new CallbackData("a", "start").Serialize()));
await this.Device.Send("Choose your progress bar:", btn); await Device.Send("Choose your progress bar:", btn);
} }
private async Task ProgressTest_Closed(object sender, EventArgs e) private async Task ProgressTest_Closed(object sender, EventArgs e)
{ {
await this.Device.Send("Ciao from ProgressTest"); await Device.Send("Ciao from ProgressTest");
} }
} }

View File

@ -1,8 +1,4 @@
using System; using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Form; using TelegramBotBase.Form;
@ -10,38 +6,39 @@ namespace TelegramBotBaseTest.Tests.Register
{ {
public class PerForm : AutoCleanForm public class PerForm : AutoCleanForm
{ {
public String EMail { get; set; } public string EMail { get; set; }
public String Firstname { get; set; } public string Firstname { get; set; }
public String Lastname { get; set; } public string Lastname { get; set; }
public async override Task Load(MessageResult message) public override Task Load(MessageResult message)
{ {
if (message.MessageText.Trim() == "") if (message.MessageText.Trim() == "")
return; return Task.CompletedTask;
if (this.Firstname == null) if (Firstname == null)
{ {
this.Firstname = message.MessageText; Firstname = message.MessageText;
return; return Task.CompletedTask;
} }
if (this.Lastname == null) if (Lastname == null)
{ {
this.Lastname = message.MessageText; Lastname = message.MessageText;
return; return Task.CompletedTask;
} }
if (this.EMail == null) if (EMail == null)
{ {
this.EMail = message.MessageText; EMail = message.MessageText;
return; return Task.CompletedTask;
} }
return Task.CompletedTask;
} }
public async override Task Action(MessageResult message) public override async Task Action(MessageResult message)
{ {
var call = message.GetData<CallbackData>(); var call = message.GetData<CallbackData>();
@ -56,7 +53,7 @@ namespace TelegramBotBaseTest.Tests.Register
var start = new Start(); var start = new Start();
await this.NavigateTo(start); await NavigateTo(start);
break; break;
@ -65,37 +62,37 @@ namespace TelegramBotBaseTest.Tests.Register
} }
public async override Task Render(MessageResult message) public override async Task Render(MessageResult message)
{ {
if (this.Firstname == null) if (Firstname == null)
{ {
await this.Device.Send("Please sent your firstname:"); await Device.Send("Please sent your firstname:");
return; return;
} }
if (this.Lastname == null) if (Lastname == null)
{ {
await this.Device.Send("Please sent your lastname:"); await Device.Send("Please sent your lastname:");
return; return;
} }
if (this.EMail == null) if (EMail == null)
{ {
await this.Device.Send("Please sent your email address:"); await Device.Send("Please sent your email address:");
return; return;
} }
String s = ""; var s = "";
s += "Firstname: " + this.Firstname + "\r\n"; s += "Firstname: " + Firstname + "\r\n";
s += "Lastname: " + this.Lastname + "\r\n"; s += "Lastname: " + Lastname + "\r\n";
s += "E-Mail: " + this.EMail + "\r\n"; s += "E-Mail: " + EMail + "\r\n";
ButtonForm bf = new ButtonForm(); var bf = new ButtonForm();
bf.AddButtonRow(new ButtonBase("Back", new CallbackData("a", "back").Serialize())); bf.AddButtonRow(new ButtonBase("Back", new CallbackData("a", "back").Serialize()));
await this.Device.Send("Your details:\r\n" + s, bf); await Device.Send("Your details:\r\n" + s, bf);
} }

View File

@ -1,17 +1,14 @@
using System; using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Form; using TelegramBotBase.Form;
using TelegramBotBaseTest.Tests.Register.Steps;
namespace TelegramBotBaseTest.Tests.Register namespace TelegramBotBaseTest.Tests.Register
{ {
public class PerStep: AutoCleanForm public class PerStep: AutoCleanForm
{ {
public async override Task Action(MessageResult message) public override async Task Action(MessageResult message)
{ {
await message.ConfirmAction(); await message.ConfirmAction();
@ -19,29 +16,29 @@ namespace TelegramBotBaseTest.Tests.Register
{ {
case "start": case "start":
var step1 = new Steps.Step1(); var step1 = new Step1();
await this.NavigateTo(step1); await NavigateTo(step1);
break; break;
case "back": case "back":
var start = new Start(); var start = new Start();
await this.NavigateTo(start); await NavigateTo(start);
break; break;
} }
} }
public async override Task Render(MessageResult message) public override async Task Render(MessageResult message)
{ {
ButtonForm bf = new ButtonForm(); var bf = new ButtonForm();
bf.AddButtonRow(new ButtonBase("Goto Step 1", "start")); bf.AddButtonRow(new ButtonBase("Goto Step 1", "start"));
bf.AddButtonRow(new ButtonBase("Back", "back")); bf.AddButtonRow(new ButtonBase("Back", "back"));
await this.Device.Send("Register Steps", bf); await Device.Send("Register Steps", bf);
} }
} }
} }

View File

@ -1,8 +1,4 @@
using System; using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Form; using TelegramBotBase.Form;
@ -10,12 +6,7 @@ namespace TelegramBotBaseTest.Tests.Register
{ {
public class Start : AutoCleanForm public class Start : AutoCleanForm
{ {
public Start() public override async Task Action(MessageResult message)
{
}
public async override Task Action(MessageResult message)
{ {
var call = message.GetData<CallbackData>(); var call = message.GetData<CallbackData>();
@ -31,21 +22,21 @@ namespace TelegramBotBaseTest.Tests.Register
var form = new PerForm(); var form = new PerForm();
await this.NavigateTo(form); await NavigateTo(form);
break; break;
case "step": case "step":
var step = new PerStep(); var step = new PerStep();
await this.NavigateTo(step); await NavigateTo(step);
break; break;
case "backtodashboard": case "backtodashboard":
var start = new Tests.Menu(); var start = new Menu();
await this.NavigateTo(start); await NavigateTo(start);
break; break;
} }
@ -53,16 +44,16 @@ namespace TelegramBotBaseTest.Tests.Register
} }
public async override Task Render(MessageResult message) public override async Task Render(MessageResult message)
{ {
ButtonForm btn = new ButtonForm(); var btn = new ButtonForm();
btn.AddButtonRow(new ButtonBase("#4.1 Per Form", new CallbackData("a", "form").Serialize())); btn.AddButtonRow(new ButtonBase("#4.1 Per Form", new CallbackData("a", "form").Serialize()));
btn.AddButtonRow(new ButtonBase("#4.2 Per Step", new CallbackData("a", "step").Serialize())); btn.AddButtonRow(new ButtonBase("#4.2 Per Step", new CallbackData("a", "step").Serialize()));
btn.AddButtonRow(new ButtonBase("Back", new CallbackData("a", "backtodashboard").Serialize())); btn.AddButtonRow(new ButtonBase("Back", new CallbackData("a", "backtodashboard").Serialize()));
await this.Device.Send("Choose your test:", btn); await Device.Send("Choose your test:", btn);
} }

View File

@ -1,18 +1,12 @@
using System; namespace TelegramBotBaseTest.Tests.Register.Steps
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TelegramBotBaseTest.Tests.Register.Steps
{ {
public class Data public class Data
{ {
public String EMail { get; set; } public string EMail { get; set; }
public String Firstname { get; set; } public string Firstname { get; set; }
public String Lastname { get; set; } public string Lastname { get; set; }
} }
} }

View File

@ -1,8 +1,4 @@
using System; using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Args; using TelegramBotBase.Args;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Form; using TelegramBotBase.Form;
@ -15,35 +11,38 @@ namespace TelegramBotBaseTest.Tests.Register.Steps
public Step1() public Step1()
{ {
this.Init += Step1_Init; Init += Step1_Init;
} }
private async Task Step1_Init(object sender, InitEventArgs e) private Task Step1_Init(object sender, InitEventArgs e)
{ {
this.UserData = new Data(); UserData = new Data();
return Task.CompletedTask;
} }
public async override Task Load(MessageResult message) public override Task Load(MessageResult message)
{ {
if (message.Handled) if (message.Handled)
return; return Task.CompletedTask;
if (message.MessageText.Trim() == "") if (message.MessageText.Trim() == "")
return; return Task.CompletedTask;
if (this.UserData.Firstname == null) if (UserData.Firstname == null)
{ {
this.UserData.Firstname = message.MessageText; UserData.Firstname = message.MessageText;
return; return Task.CompletedTask;
} }
return Task.CompletedTask;
} }
public async override Task Render(MessageResult message) public override async Task Render(MessageResult message)
{ {
if (this.UserData.Firstname == null) if (UserData.Firstname == null)
{ {
await this.Device.Send("Please sent your firstname:"); await Device.Send("Please sent your firstname:");
return; return;
} }
@ -51,9 +50,9 @@ namespace TelegramBotBaseTest.Tests.Register.Steps
var step2 = new Step2(); var step2 = new Step2();
step2.UserData = this.UserData; step2.UserData = UserData;
await this.NavigateTo(step2); await NavigateTo(step2);
} }
} }

View File

@ -1,8 +1,4 @@
using System; using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Form; using TelegramBotBase.Form;
@ -13,27 +9,29 @@ namespace TelegramBotBaseTest.Tests.Register.Steps
public Data UserData { get; set; } public Data UserData { get; set; }
public async override Task Load(MessageResult message) public override Task Load(MessageResult message)
{ {
if (message.Handled) if (message.Handled)
return; return Task.CompletedTask;
if (message.MessageText.Trim() == "") if (message.MessageText.Trim() == "")
return; return Task.CompletedTask;
if (this.UserData.Lastname == null) if (UserData.Lastname == null)
{ {
this.UserData.Lastname = message.MessageText; UserData.Lastname = message.MessageText;
return; return Task.CompletedTask;
} }
return Task.CompletedTask;
} }
public async override Task Render(MessageResult message) public override async Task Render(MessageResult message)
{ {
if (this.UserData.Lastname == null) if (UserData.Lastname == null)
{ {
await this.Device.Send("Please sent your lastname:"); await Device.Send("Please sent your lastname:");
return; return;
} }
@ -41,9 +39,9 @@ namespace TelegramBotBaseTest.Tests.Register.Steps
var step3 = new Step3(); var step3 = new Step3();
step3.UserData = this.UserData; step3.UserData = UserData;
await this.NavigateTo(step3); await NavigateTo(step3);
} }
} }

View File

@ -1,8 +1,4 @@
using System; using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Form; using TelegramBotBase.Form;
@ -12,22 +8,24 @@ namespace TelegramBotBaseTest.Tests.Register.Steps
{ {
public Data UserData { get; set; } public Data UserData { get; set; }
public async override Task Load(MessageResult message) public override Task Load(MessageResult message)
{ {
if (message.Handled) if (message.Handled)
return; return Task.CompletedTask;
if (message.MessageText.Trim() == "") if (message.MessageText.Trim() == "")
return; return Task.CompletedTask;
if (this.UserData.EMail == null) if (UserData.EMail == null)
{ {
this.UserData.EMail = message.MessageText; UserData.EMail = message.MessageText;
return; return Task.CompletedTask;
} }
return Task.CompletedTask;
} }
public async override Task Action(MessageResult message) public override async Task Action(MessageResult message)
{ {
await message.ConfirmAction(); await message.ConfirmAction();
@ -37,7 +35,7 @@ namespace TelegramBotBaseTest.Tests.Register.Steps
var start = new Start(); var start = new Start();
await this.NavigateTo(start); await NavigateTo(start);
break; break;
@ -45,26 +43,26 @@ namespace TelegramBotBaseTest.Tests.Register.Steps
} }
public async override Task Render(MessageResult message) public override async Task Render(MessageResult message)
{ {
if (this.UserData.EMail == null) if (UserData.EMail == null)
{ {
await this.Device.Send("Please sent your email:"); await Device.Send("Please sent your email:");
return; return;
} }
message.Handled = true; message.Handled = true;
String s = ""; var s = "";
s += "Firstname: " + this.UserData.Firstname + "\r\n"; s += "Firstname: " + UserData.Firstname + "\r\n";
s += "Lastname: " + this.UserData.Lastname + "\r\n"; s += "Lastname: " + UserData.Lastname + "\r\n";
s += "E-Mail: " + this.UserData.EMail + "\r\n"; s += "E-Mail: " + UserData.EMail + "\r\n";
ButtonForm bf = new ButtonForm(); var bf = new ButtonForm();
bf.AddButtonRow(new ButtonBase("Back", "back")); bf.AddButtonRow(new ButtonBase("Back", "back"));
await this.Device.Send("Your details:\r\n" + s, bf); await Device.Send("Your details:\r\n" + s, bf);
} }
} }

View File

@ -1,9 +1,7 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Enums;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests namespace TelegramBotBaseTest.Tests
@ -13,15 +11,15 @@ namespace TelegramBotBaseTest.Tests
public SimpleForm() public SimpleForm()
{ {
this.DeleteSide = TelegramBotBase.Enums.eDeleteSide.Both; DeleteSide = EDeleteSide.Both;
this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; DeleteMode = EDeleteMode.OnLeavingForm;
this.Opened += SimpleForm_Opened; Opened += SimpleForm_Opened;
} }
private async Task SimpleForm_Opened(object sender, EventArgs e) private async Task SimpleForm_Opened(object sender, EventArgs e)
{ {
await this.Device.Send("Hello world! (send 'back' to get back to Start)\r\nOr\r\nhi, hello, maybe, bye and ciao"); await Device.Send("Hello world! (send 'back' to get back to Start)\r\nOr\r\nhi, hello, maybe, bye and ciao");
} }
public override async Task Load(MessageResult message) public override async Task Load(MessageResult message)
@ -36,13 +34,13 @@ namespace TelegramBotBaseTest.Tests
case "hi": case "hi":
//Send him a simple message //Send him a simple message
await this.Device.Send("Hello you there !"); await Device.Send("Hello you there !");
break; break;
case "maybe": case "maybe":
//Send him a simple message and reply to the one of himself //Send him a simple message and reply to the one of himself
await this.Device.Send("Maybe what?", replyTo: messageId); await Device.Send("Maybe what?", replyTo: messageId);
break; break;
@ -50,14 +48,14 @@ namespace TelegramBotBaseTest.Tests
case "ciao": case "ciao":
//Send him a simple message //Send him a simple message
await this.Device.Send("Ok, take care !"); await Device.Send("Ok, take care !");
break; break;
case "back": case "back":
var st = new Menu(); var st = new Menu();
await this.NavigateTo(st); await NavigateTo(st);
break; break;
} }

View File

@ -1,9 +1,7 @@
using System; using System.Threading.Tasks;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Form; using TelegramBotBase.Form;
using TelegramBotBaseTest.Tests.Groups;
namespace TelegramBotBaseTest.Tests namespace TelegramBotBaseTest.Tests
{ {
@ -12,7 +10,7 @@ namespace TelegramBotBaseTest.Tests
public override async Task<bool> Open(MessageResult e) public override async Task<bool> Open(MessageResult e)
{ {
var st = new Menu(); var st = new Menu();
await this.NavigateTo(st); await NavigateTo(st);
return true; return true;
} }
@ -20,8 +18,8 @@ namespace TelegramBotBaseTest.Tests
public override async Task<bool> OpenGroup(MessageResult e) public override async Task<bool> OpenGroup(MessageResult e)
{ {
var st = new Groups.LinkReplaceTest(); var st = new LinkReplaceTest();
await this.NavigateTo(st); await NavigateTo(st);
return true; return true;
} }

View File

@ -1,9 +1,5 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Telegram.Bot.Types;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Form; using TelegramBotBase.Form;
@ -11,24 +7,22 @@ namespace TelegramBotBaseTest.Tests
{ {
public class TestForm : FormBase public class TestForm : FormBase
{ {
private string LastMessage { get; set; }
String LastMessage { get; set; }
public TestForm() public TestForm()
{ {
this.Opened += TestForm_Opened; Opened += TestForm_Opened;
this.Closed += TestForm_Closed; Closed += TestForm_Closed;
} }
private async Task TestForm_Opened(object sender, EventArgs e) private async Task TestForm_Opened(object sender, EventArgs e)
{ {
await this.Device.Send("Welcome to Form 1"); await Device.Send("Welcome to Form 1");
} }
private async Task TestForm_Closed(object sender, EventArgs e) private async Task TestForm_Closed(object sender, EventArgs e)
{ {
await this.Device.Send("Ciao from Form 1"); await Device.Send("Ciao from Form 1");
} }
@ -45,7 +39,7 @@ namespace TelegramBotBaseTest.Tests
var tf = new TestForm2(); var tf = new TestForm2();
await this.NavigateTo(tf); await NavigateTo(tf);
break; break;
@ -54,7 +48,7 @@ namespace TelegramBotBaseTest.Tests
if (message.UpdateData == null) if (message.UpdateData == null)
return; return;
this.LastMessage = message.Message.Text; LastMessage = message.Message.Text;
break; break;
} }
@ -68,7 +62,7 @@ namespace TelegramBotBaseTest.Tests
if (message.Command == "reply") if (message.Command == "reply")
{ {
await this.Device.Send("Last message: " + this.LastMessage); await Device.Send("Last message: " + LastMessage);
} }

View File

@ -1,12 +1,7 @@
using System; using System;
using System.Collections.Generic;
using System.Drawing; using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Telegram.Bot.Types; using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types.ReplyMarkups;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Extensions.Images; using TelegramBotBase.Extensions.Images;
using TelegramBotBase.Form; using TelegramBotBase.Form;
@ -19,18 +14,18 @@ namespace TelegramBotBaseTest.Tests
public TestForm2() public TestForm2()
{ {
this.Opened += TestForm2_Opened; Opened += TestForm2_Opened;
this.Closed += TestForm2_Closed; Closed += TestForm2_Closed;
} }
private async Task TestForm2_Opened(object sender, EventArgs e) private async Task TestForm2_Opened(object sender, EventArgs e)
{ {
await this.Device.Send("Welcome to Form 2"); await Device.Send("Welcome to Form 2");
} }
private async Task TestForm2_Closed(object sender, EventArgs e) private async Task TestForm2_Closed(object sender, EventArgs e)
{ {
await this.Device.Send("Ciao from Form 2"); await Device.Send("Ciao from Form 2");
} }
@ -51,23 +46,23 @@ namespace TelegramBotBaseTest.Tests
var tf = new TestForm(); var tf = new TestForm();
await this.NavigateTo(tf); await NavigateTo(tf);
} }
else if (call.Value == "alert") else if (call.Value == "alert")
{ {
AlertDialog ad = new AlertDialog("This is a message", "Ok"); var ad = new AlertDialog("This is a message", "Ok");
ad.ButtonClicked += async (s, en) => ad.ButtonClicked += async (s, en) =>
{ {
var fto = new TestForm2(); var fto = new TestForm2();
await this.NavigateTo(fto); await NavigateTo(fto);
}; };
await this.NavigateTo(ad); await NavigateTo(ad);
} }
else if (call.Value == "confirm") else if (call.Value == "confirm")
{ {
ConfirmDialog pd = new ConfirmDialog("Please confirm", new ButtonBase("Ok", "ok"), new ButtonBase("Cancel", "cancel")); var pd = new ConfirmDialog("Please confirm", new ButtonBase("Ok", "ok"), new ButtonBase("Cancel", "cancel"));
pd.ButtonClicked += async (s, en) => pd.ButtonClicked += async (s, en) =>
{ {
@ -76,18 +71,18 @@ namespace TelegramBotBaseTest.Tests
await pd.NavigateTo(tf); await pd.NavigateTo(tf);
}; };
await this.NavigateTo(pd); await NavigateTo(pd);
} }
else if (call.Value == "prompt") else if (call.Value == "prompt")
{ {
PromptDialog pd = new PromptDialog("Please tell me your name ?"); var pd = new PromptDialog("Please tell me your name ?");
pd.Completed += async (s, en) => pd.Completed += async (s, en) =>
{ {
await this.Device.Send("Hello " + pd.Value); await Device.Send("Hello " + pd.Value);
}; };
await this.OpenModal(pd); await OpenModal(pd);
} }
@ -96,8 +91,8 @@ namespace TelegramBotBaseTest.Tests
public override async Task Render(MessageResult message) public override async Task Render(MessageResult message)
{ {
Bitmap bmp = new Bitmap(800, 600); var bmp = new Bitmap(800, 600);
using (Graphics g = Graphics.FromImage(bmp)) using (var g = Graphics.FromImage(bmp))
{ {
g.FillRectangle(Brushes.White, 0, 0, bmp.Width, bmp.Height); g.FillRectangle(Brushes.White, 0, 0, bmp.Width, bmp.Height);
@ -106,9 +101,9 @@ namespace TelegramBotBaseTest.Tests
} }
await this.Device.SetAction(Telegram.Bot.Types.Enums.ChatAction.UploadPhoto); await Device.SetAction(ChatAction.UploadPhoto);
ButtonForm btn = new ButtonForm(); var btn = new ButtonForm();
//btn.AddButtonRow(new ButtonBase("Zum Testformular 1", CallbackData.Create("navigate", "testform1")), new ButtonBase("Zum Testformular 1", CallbackData.Create("navigate", "testform1"))); //btn.AddButtonRow(new ButtonBase("Zum Testformular 1", CallbackData.Create("navigate", "testform1")), new ButtonBase("Zum Testformular 1", CallbackData.Create("navigate", "testform1")));
@ -119,7 +114,7 @@ namespace TelegramBotBaseTest.Tests
btn.AddButtonRow(new ButtonBase("Request Prompt", CallbackData.Create("navigate", "prompt"))); btn.AddButtonRow(new ButtonBase("Request Prompt", CallbackData.Create("navigate", "prompt")));
await this.Device.SendPhoto(bmp, "Test", "", btn); await Device.SendPhoto(bmp, "Test", "", btn);
} }

View File

@ -1,8 +1,5 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot.Types; using Telegram.Bot.Types;
using TelegramBotBase.Sessions; using TelegramBotBase.Sessions;
@ -13,9 +10,9 @@ namespace TelegramBotBase.Args
/// </summary> /// </summary>
public class BotCommandEventArgs : EventArgs public class BotCommandEventArgs : EventArgs
{ {
public String Command { get; set; } public string Command { get; set; }
public List<String> Parameters { get; set; } public List<string> Parameters { get; set; }
public long DeviceId { get; set; } public long DeviceId { get; set; }
@ -32,13 +29,13 @@ namespace TelegramBotBase.Args
} }
public BotCommandEventArgs(String Command, List<String> Parameters, Message Message, long DeviceId, DeviceSession Device) public BotCommandEventArgs(string command, List<string> parameters, Message message, long deviceId, DeviceSession device)
{ {
this.Command = Command; this.Command = command;
this.Parameters = Parameters; this.Parameters = parameters;
this.OriginalMessage = Message; OriginalMessage = message;
this.DeviceId = DeviceId; this.DeviceId = deviceId;
this.Device = Device; this.Device = device;
} }
} }

View File

@ -1,8 +1,4 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Controls.Hybrid; using TelegramBotBase.Controls.Hybrid;
using TelegramBotBase.Form; using TelegramBotBase.Form;
@ -29,21 +25,21 @@ namespace TelegramBotBase.Args
public ButtonClickedEventArgs(ButtonBase button) public ButtonClickedEventArgs(ButtonBase button)
{ {
this.Button = button; Button = button;
this.Index = -1; Index = -1;
} }
public ButtonClickedEventArgs(ButtonBase button, int Index) public ButtonClickedEventArgs(ButtonBase button, int index)
{ {
this.Button = button; Button = button;
this.Index = Index; this.Index = index;
} }
public ButtonClickedEventArgs(ButtonBase button, int Index, ButtonRow row) public ButtonClickedEventArgs(ButtonBase button, int index, ButtonRow row)
{ {
this.Button = button; Button = button;
this.Index = Index; this.Index = index;
this.Row = row; Row = row;
} }
} }
} }

View File

@ -1,15 +1,12 @@
using System; using System;
using System.Collections.Generic;
using System.Text;
using TelegramBotBase.Controls.Hybrid; using TelegramBotBase.Controls.Hybrid;
using TelegramBotBase.Form;
namespace TelegramBotBase.Args namespace TelegramBotBase.Args
{ {
public class CheckedChangedEventArgs : EventArgs public class CheckedChangedEventArgs : EventArgs
{ {
/// <summary> /// <summary>
/// Contains the index of the row where the button is inside. /// Contains the index of the row where the button is inside.
/// Contains -1 when it is a layout button or not found. /// Contains -1 when it is a layout button or not found.
/// </summary> /// </summary>
public int Index { get; set; } public int Index { get; set; }
@ -32,11 +29,11 @@ namespace TelegramBotBase.Args
} }
public CheckedChangedEventArgs(ButtonRow row, int Index, bool Checked) public CheckedChangedEventArgs(ButtonRow row, int index, bool @checked)
{ {
this.Row = row; Row = row;
this.Index = Index; this.Index = index;
this.Checked = Checked; this.Checked = @checked;
} }

View File

@ -1,6 +1,4 @@
using System; using System;
using System.Collections.Generic;
using System.Text;
using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.Enums;
using TelegramBotBase.Base; using TelegramBotBase.Base;
@ -14,8 +12,8 @@ namespace TelegramBotBase.Args
public GroupChangedEventArgs(MessageType type, MessageResult message) public GroupChangedEventArgs(MessageType type, MessageResult message)
{ {
this.Type = type; Type = type;
this.OriginalMessage = message; OriginalMessage = message;
} }

View File

@ -1,8 +1,4 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TelegramBotBase.Args namespace TelegramBotBase.Args
{ {
@ -12,7 +8,7 @@ namespace TelegramBotBase.Args
public InitEventArgs(params object[] args) public InitEventArgs(params object[] args)
{ {
this.Args = args; Args = args;
} }
} }
} }

View File

@ -1,42 +1,34 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text;
namespace TelegramBotBase.Args namespace TelegramBotBase.Args
{ {
public class LoadStateEventArgs public class LoadStateEventArgs
{ {
public Dictionary<String,object> Values { get; set; } public Dictionary<string,object> Values { get; set; }
public LoadStateEventArgs() public LoadStateEventArgs()
{ {
Values = new Dictionary<string, object>(); Values = new Dictionary<string, object>();
} }
public List<String> Keys public List<string> Keys => Values.Keys.ToList();
{
get
{
return Values.Keys.ToList();
}
}
public String Get(String key) public string Get(string key)
{ {
return Values[key].ToString(); return Values[key].ToString();
} }
public int GetInt(String key) public int GetInt(string key)
{ {
int i = 0; var i = 0;
if (int.TryParse(Values[key].ToString(), out i)) if (int.TryParse(Values[key].ToString(), out i))
return i; return i;
return 0; return 0;
} }
public double GetDouble(String key) public double GetDouble(string key)
{ {
double d = 0; double d = 0;
if (double.TryParse(Values[key].ToString(), out d)) if (double.TryParse(Values[key].ToString(), out d))
@ -45,16 +37,16 @@ namespace TelegramBotBase.Args
return 0; return 0;
} }
public bool GetBool(String key) public bool GetBool(string key)
{ {
bool b = false; var b = false;
if (bool.TryParse(Values[key].ToString(), out b)) if (bool.TryParse(Values[key].ToString(), out b))
return b; return b;
return false; return false;
} }
public object GetObject(String key) public object GetObject(string key)
{ {
return Values[key]; return Values[key];
} }

View File

@ -1,7 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text;
using Telegram.Bot.Types; using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.Enums;
using TelegramBotBase.Base; using TelegramBotBase.Base;
@ -18,15 +17,15 @@ namespace TelegramBotBase.Args
public MemberChangeEventArgs() public MemberChangeEventArgs()
{ {
this.Members = new List<User>(); Members = new List<User>();
} }
public MemberChangeEventArgs(MessageType type, MessageResult result, params User[] members) public MemberChangeEventArgs(MessageType type, MessageResult result, params User[] members)
{ {
this.Type = type; Type = type;
this.Result = result; Result = result;
this.Members = members.ToList(); Members = members.ToList();
} }

View File

@ -1,11 +1,4 @@
using System; namespace TelegramBotBase.Args
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot.Types;
namespace TelegramBotBase.Args
{ {
public class MessageDeletedEventArgs public class MessageDeletedEventArgs
{ {
@ -16,7 +9,7 @@ namespace TelegramBotBase.Args
public MessageDeletedEventArgs(int messageId) public MessageDeletedEventArgs(int messageId)
{ {
this.MessageId = messageId; MessageId = messageId;
} }
} }

View File

@ -1,8 +1,4 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Sessions; using TelegramBotBase.Sessions;
namespace TelegramBotBase.Base namespace TelegramBotBase.Base
@ -16,11 +12,11 @@ namespace TelegramBotBase.Base
public MessageResult Message { get; set; } public MessageResult Message { get; set; }
public MessageIncomeEventArgs(long DeviceId, DeviceSession Device, MessageResult message) public MessageIncomeEventArgs(long deviceId, DeviceSession device, MessageResult message)
{ {
this.DeviceId = DeviceId; this.DeviceId = deviceId;
this.Device = Device; this.Device = device;
this.Message = message; Message = message;
} }

View File

@ -1,27 +1,16 @@
using System; using Telegram.Bot.Types;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot.Types;
namespace TelegramBotBase.Args namespace TelegramBotBase.Args
{ {
public class MessageReceivedEventArgs public class MessageReceivedEventArgs
{ {
public int MessageId public int MessageId => Message.MessageId;
{
get
{
return this.Message.MessageId;
}
}
public Message Message { get; set; } public Message Message { get; set; }
public MessageReceivedEventArgs(Message m) public MessageReceivedEventArgs(Message m)
{ {
this.Message = m; Message = m;
} }
} }

View File

@ -1,21 +1,11 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot.Types; using Telegram.Bot.Types;
namespace TelegramBotBase.Args namespace TelegramBotBase.Args
{ {
public class MessageSentEventArgs : EventArgs public class MessageSentEventArgs : EventArgs
{ {
public int MessageId public int MessageId => Message.MessageId;
{
get
{
return this.Message.MessageId;
}
}
public Message Message { get; set; } public Message Message { get; set; }
@ -25,10 +15,10 @@ namespace TelegramBotBase.Args
public Type Origin { get; set; } public Type Origin { get; set; }
public MessageSentEventArgs(Message message, Type Origin) public MessageSentEventArgs(Message message, Type origin)
{ {
this.Message = message; Message = message;
this.Origin = Origin; this.Origin = origin;
} }

View File

@ -1,14 +1,10 @@
using System; namespace TelegramBotBase.Args
using System.Collections.Generic;
using System.Text;
namespace TelegramBotBase.Args
{ {
public class PromptDialogCompletedEventArgs public class PromptDialogCompletedEventArgs
{ {
public object Tag { get; set; } public object Tag { get; set; }
public String Value { get; set; } public string Value { get; set; }
} }
} }

View File

@ -1,6 +1,4 @@
using System; using System;
using System.Collections.Generic;
using System.Text;
namespace TelegramBotBase.Args namespace TelegramBotBase.Args
{ {
@ -9,10 +7,10 @@ namespace TelegramBotBase.Args
public int CurrentView { get; set; } public int CurrentView { get; set; }
public RenderViewEventArgs(int ViewIndex) public RenderViewEventArgs(int viewIndex)
{ {
CurrentView = ViewIndex; CurrentView = viewIndex;
} }

View File

@ -1,38 +1,36 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using System.Text;
namespace TelegramBotBase.Args namespace TelegramBotBase.Args
{ {
public class SaveStateEventArgs public class SaveStateEventArgs
{ {
public Dictionary<String, object> Values { get; set; } public Dictionary<string, object> Values { get; set; }
public SaveStateEventArgs() public SaveStateEventArgs()
{ {
Values = new Dictionary<string, object>(); Values = new Dictionary<string, object>();
} }
public void Set(String key, String value) public void Set(string key, string value)
{ {
Values[key] = value; Values[key] = value;
} }
public void SetInt(String key, int value) public void SetInt(string key, int value)
{ {
Values[key] = value; Values[key] = value;
} }
public void SetBool(String key, bool value) public void SetBool(string key, bool value)
{ {
Values[key] = value; Values[key] = value;
} }
public void SetDouble(String key, double value) public void SetDouble(string key, double value)
{ {
Values[key] = value; Values[key] = value;
} }
public void SetObject(String key, object value) public void SetObject(string key, object value)
{ {
Values[key] = value; Values[key] = value;
} }

View File

@ -1,9 +1,4 @@
using System; using TelegramBotBase.Base;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TelegramBotBase.Base;
using TelegramBotBase.Sessions;
namespace TelegramBotBase.Args namespace TelegramBotBase.Args
{ {
@ -14,7 +9,7 @@ namespace TelegramBotBase.Args
public SaveStatesEventArgs(StateContainer states) public SaveStatesEventArgs(StateContainer states)
{ {
this.States = states; States = states;
} }
} }
} }

View File

@ -1,8 +1,4 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Sessions; using TelegramBotBase.Sessions;
namespace TelegramBotBase.Base namespace TelegramBotBase.Base
@ -13,10 +9,10 @@ namespace TelegramBotBase.Base
public DeviceSession Device { get; set; } public DeviceSession Device { get; set; }
public SessionBeginEventArgs(long DeviceId, DeviceSession Device) public SessionBeginEventArgs(long deviceId, DeviceSession device)
{ {
this.DeviceId = DeviceId; this.DeviceId = deviceId;
this.Device = Device; this.Device = device;
} }
} }
} }

View File

@ -1,8 +1,4 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Sessions; using TelegramBotBase.Sessions;
namespace TelegramBotBase.Args namespace TelegramBotBase.Args
@ -10,7 +6,7 @@ namespace TelegramBotBase.Args
public class SystemExceptionEventArgs : EventArgs public class SystemExceptionEventArgs : EventArgs
{ {
public String Command { get; set; } public string Command { get; set; }
public long DeviceId { get; set; } public long DeviceId { get; set; }
@ -24,12 +20,12 @@ namespace TelegramBotBase.Args
} }
public SystemExceptionEventArgs(String Command, long DeviceId, DeviceSession Device, Exception error) public SystemExceptionEventArgs(string command, long deviceId, DeviceSession device, Exception error)
{ {
this.Command = Command; this.Command = command;
this.DeviceId = DeviceId; this.DeviceId = deviceId;
this.Device = Device; this.Device = device;
this.Error = error; Error = error;
} }
} }

View File

@ -1,8 +1,4 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot.Types; using Telegram.Bot.Types;
using TelegramBotBase.Sessions; using TelegramBotBase.Sessions;
@ -10,13 +6,13 @@ namespace TelegramBotBase.Args
{ {
public class UnhandledCallEventArgs : EventArgs public class UnhandledCallEventArgs : EventArgs
{ {
public String Command { get; set; } public string Command { get; set; }
public long DeviceId { get; set; } public long DeviceId { get; set; }
public DeviceSession Device {get;set;} public DeviceSession Device {get;set;}
public String RawData { get; set; } public string RawData { get; set; }
public int MessageId { get; set; } public int MessageId { get; set; }
@ -27,18 +23,18 @@ namespace TelegramBotBase.Args
public UnhandledCallEventArgs() public UnhandledCallEventArgs()
{ {
this.Handled = false; Handled = false;
} }
public UnhandledCallEventArgs(String Command,String RawData, long DeviceId, int MessageId, Message message, DeviceSession Device) : this() public UnhandledCallEventArgs(string command,string rawData, long deviceId, int messageId, Message message, DeviceSession device) : this()
{ {
this.Command = Command; this.Command = command;
this.RawData = RawData; this.RawData = rawData;
this.DeviceId = DeviceId; this.DeviceId = deviceId;
this.MessageId = MessageId; this.MessageId = messageId;
this.Message = message; Message = message;
this.Device = Device; this.Device = device;
} }
} }

View File

@ -1,6 +1,4 @@
using System; using System;
using System.Collections.Generic;
using System.Text;
namespace TelegramBotBase.Attributes namespace TelegramBotBase.Attributes
{ {

View File

@ -1,6 +1,4 @@
using System; using System;
using System.Collections.Generic;
using System.Text;
namespace TelegramBotBase.Attributes namespace TelegramBotBase.Attributes
{ {
@ -9,7 +7,7 @@ namespace TelegramBotBase.Attributes
/// </summary> /// </summary>
public class SaveState : Attribute public class SaveState : Attribute
{ {
public String Key { get; set; } public string Key { get; set; }
} }
} }

View File

@ -1,7 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace TelegramBotBase.Base namespace TelegramBotBase.Base

View File

@ -1,8 +1,5 @@
using System; using System.Threading.Tasks;
using System.Collections.Generic; using TelegramBotBase.Sessions;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TelegramBotBase.Base namespace TelegramBotBase.Base
{ {
@ -11,17 +8,11 @@ namespace TelegramBotBase.Base
/// </summary> /// </summary>
public class ControlBase public class ControlBase
{ {
public Sessions.DeviceSession Device { get; set; } public DeviceSession Device { get; set; }
public int ID { get; set; } public int Id { get; set; }
public String ControlID public string ControlId => "#c" + Id;
{
get
{
return "#c" + this.ID.ToString();
}
}
/// <summary> /// <summary>
/// Defines if the control should be rendered and invoked with actions /// Defines if the control should be rendered and invoked with actions
@ -37,43 +28,35 @@ namespace TelegramBotBase.Base
} }
public virtual async Task Load(MessageResult result) public virtual Task Load(MessageResult result)
{ {
return Task.CompletedTask;
} }
public virtual async Task Action(MessageResult result, String value = null) public virtual Task Action(MessageResult result, string value = null)
{ {
return Task.CompletedTask;
} }
public virtual async Task Render(MessageResult result) public virtual Task Render(MessageResult result)
{ {
return Task.CompletedTask;
} }
public virtual async Task Hidden(bool FormClose) public virtual Task Hidden(bool formClose)
{ {
return Task.CompletedTask;
} }
/// <summary> /// <summary>
/// Will be called on a cleanup. /// Will be called on a cleanup.
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public virtual async Task Cleanup() public virtual Task Cleanup()
{ {
return Task.CompletedTask;
} }
} }

View File

@ -1,11 +1,10 @@
using System; using System.IO;
using System.Collections.Generic;
using System.IO;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Telegram.Bot; using Telegram.Bot;
using Telegram.Bot.Types; using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types.InputFiles; using Telegram.Bot.Types.InputFiles;
namespace TelegramBotBase.Base namespace TelegramBotBase.Base
@ -21,98 +20,45 @@ namespace TelegramBotBase.Base
public UpdateResult UpdateData { get; set; } public UpdateResult UpdateData { get; set; }
public Contact Contact public Contact Contact => Message.Contact;
{
get
{
return this.Message.Contact;
}
}
public Location Location public Location Location => Message.Location;
{
get
{
return this.Message.Location;
}
}
public Document Document public Document Document => Message.Document;
{
get
{
return this.Message.Document;
}
}
public Audio Audio public Audio Audio => Message.Audio;
{
get
{
return this.Message.Audio;
}
}
public Video Video public Video Video => Message.Video;
{
get
{
return this.Message.Video;
}
}
public PhotoSize[] Photos public PhotoSize[] Photos => Message.Photo;
{
get
{
return this.Message.Photo;
}
}
public Telegram.Bot.Types.Enums.MessageType Type public MessageType Type => Message?.Type ?? MessageType.Unknown;
{
get
{
return this.Message?.Type ?? Telegram.Bot.Types.Enums.MessageType.Unknown;
}
}
public override Message Message public override Message Message => UpdateData?.Message;
{
get
{
return this.UpdateData?.Message;
}
}
/// <summary> /// <summary>
/// Returns the FileId of the first reachable element. /// Returns the FileId of the first reachable element.
/// </summary> /// </summary>
public String FileId public string FileId =>
{ (Document?.FileId ??
get Audio?.FileId ??
{ Video?.FileId ??
return (this.Document?.FileId ?? Photos.FirstOrDefault()?.FileId);
this.Audio?.FileId ??
this.Video?.FileId ??
this.Photos.FirstOrDefault()?.FileId);
}
}
public DataResult(UpdateResult update) public DataResult(UpdateResult update)
{ {
this.UpdateData = update; UpdateData = update;
} }
public async Task<InputOnlineFile> DownloadDocument() public async Task<InputOnlineFile> DownloadDocument()
{ {
var encryptedContent = new System.IO.MemoryStream(); var encryptedContent = new MemoryStream();
encryptedContent.SetLength(this.Document.FileSize.Value); encryptedContent.SetLength(Document.FileSize.Value);
var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(this.Document.FileId, encryptedContent); var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Document.FileId, encryptedContent);
return new InputOnlineFile(encryptedContent, this.Document.FileName); return new InputOnlineFile(encryptedContent, Document.FileName);
} }
@ -121,10 +67,10 @@ namespace TelegramBotBase.Base
/// </summary> /// </summary>
/// <param name="path"></param> /// <param name="path"></param>
/// <returns></returns> /// <returns></returns>
public async Task DownloadDocument(String path) public async Task DownloadDocument(string path)
{ {
var file = await Device.Client.TelegramClient.GetFileAsync(this.Document.FileId); var file = await Device.Client.TelegramClient.GetFileAsync(Document.FileId);
FileStream fs = new FileStream(path, FileMode.Create); var fs = new FileStream(path, FileMode.Create);
await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs); await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs);
fs.Close(); fs.Close();
fs.Dispose(); fs.Dispose();
@ -136,8 +82,8 @@ namespace TelegramBotBase.Base
/// <returns></returns> /// <returns></returns>
public async Task<byte[]> DownloadRawDocument() public async Task<byte[]> DownloadRawDocument()
{ {
MemoryStream ms = new MemoryStream(); var ms = new MemoryStream();
await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(this.Document.FileId, ms); await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Document.FileId, ms);
return ms.ToArray(); return ms.ToArray();
} }
@ -145,7 +91,7 @@ namespace TelegramBotBase.Base
/// Downloads a document and returns it as string. (txt,csv,etc) Default encoding ist UTF8. /// Downloads a document and returns it as string. (txt,csv,etc) Default encoding ist UTF8.
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public async Task<String> DownloadRawTextDocument() public async Task<string> DownloadRawTextDocument()
{ {
return await DownloadRawTextDocument(Encoding.UTF8); return await DownloadRawTextDocument(Encoding.UTF8);
} }
@ -154,10 +100,10 @@ namespace TelegramBotBase.Base
/// Downloads a document and returns it as string. (txt,csv,etc) /// Downloads a document and returns it as string. (txt,csv,etc)
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public async Task<String> DownloadRawTextDocument(Encoding encoding) public async Task<string> DownloadRawTextDocument(Encoding encoding)
{ {
MemoryStream ms = new MemoryStream(); var ms = new MemoryStream();
await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(this.Document.FileId, ms); await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Document.FileId, ms);
ms.Position = 0; ms.Position = 0;
@ -168,17 +114,17 @@ namespace TelegramBotBase.Base
public async Task<InputOnlineFile> DownloadVideo() public async Task<InputOnlineFile> DownloadVideo()
{ {
var encryptedContent = new System.IO.MemoryStream(); var encryptedContent = new MemoryStream();
encryptedContent.SetLength(this.Video.FileSize.Value); encryptedContent.SetLength(Video.FileSize.Value);
var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(this.Video.FileId, encryptedContent); var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Video.FileId, encryptedContent);
return new InputOnlineFile(encryptedContent, ""); return new InputOnlineFile(encryptedContent, "");
} }
public async Task DownloadVideo(String path) public async Task DownloadVideo(string path)
{ {
var file = await Device.Client.TelegramClient.GetFileAsync(this.Video.FileId); var file = await Device.Client.TelegramClient.GetFileAsync(Video.FileId);
FileStream fs = new FileStream(path, FileMode.Create); var fs = new FileStream(path, FileMode.Create);
await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs); await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs);
fs.Close(); fs.Close();
fs.Dispose(); fs.Dispose();
@ -186,17 +132,17 @@ namespace TelegramBotBase.Base
public async Task<InputOnlineFile> DownloadAudio() public async Task<InputOnlineFile> DownloadAudio()
{ {
var encryptedContent = new System.IO.MemoryStream(); var encryptedContent = new MemoryStream();
encryptedContent.SetLength(this.Audio.FileSize.Value); encryptedContent.SetLength(Audio.FileSize.Value);
var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(this.Audio.FileId, encryptedContent); var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Audio.FileId, encryptedContent);
return new InputOnlineFile(encryptedContent, ""); return new InputOnlineFile(encryptedContent, "");
} }
public async Task DownloadAudio(String path) public async Task DownloadAudio(string path)
{ {
var file = await Device.Client.TelegramClient.GetFileAsync(this.Audio.FileId); var file = await Device.Client.TelegramClient.GetFileAsync(Audio.FileId);
FileStream fs = new FileStream(path, FileMode.Create); var fs = new FileStream(path, FileMode.Create);
await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs); await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs);
fs.Close(); fs.Close();
fs.Dispose(); fs.Dispose();
@ -204,19 +150,19 @@ namespace TelegramBotBase.Base
public async Task<InputOnlineFile> DownloadPhoto(int index) public async Task<InputOnlineFile> DownloadPhoto(int index)
{ {
var photo = this.Photos[index]; var photo = Photos[index];
var encryptedContent = new System.IO.MemoryStream(); var encryptedContent = new MemoryStream();
encryptedContent.SetLength(photo.FileSize.Value); encryptedContent.SetLength(photo.FileSize.Value);
var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(photo.FileId, encryptedContent); var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(photo.FileId, encryptedContent);
return new InputOnlineFile(encryptedContent, ""); return new InputOnlineFile(encryptedContent, "");
} }
public async Task DownloadPhoto(int index, String path) public async Task DownloadPhoto(int index, string path)
{ {
var photo = this.Photos[index]; var photo = Photos[index];
var file = await Device.Client.TelegramClient.GetFileAsync(photo.FileId); var file = await Device.Client.TelegramClient.GetFileAsync(photo.FileId);
FileStream fs = new FileStream(path, FileMode.Create); var fs = new FileStream(path, FileMode.Create);
await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs); await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs);
fs.Close(); fs.Close();
fs.Dispose(); fs.Dispose();

View File

@ -2,7 +2,6 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Linq; using System.Linq;
using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using TelegramBotBase.Args; using TelegramBotBase.Args;
using TelegramBotBase.Base; using TelegramBotBase.Base;
@ -27,7 +26,7 @@ namespace TelegramBotBase.Form
/// <summary> /// <summary>
/// has this formular already been disposed ? /// has this formular already been disposed ?
/// </summary> /// </summary>
public bool IsDisposed { get; set; } = false; public bool IsDisposed { get; set; }
public List<ControlBase> Controls { get; set; } public List<ControlBase> Controls { get; set; }
@ -35,33 +34,33 @@ namespace TelegramBotBase.Form
public EventHandlerList Events = new EventHandlerList(); public EventHandlerList Events = new EventHandlerList();
private static object __evInit = new object(); private static readonly object EvInit = new object();
private static object __evOpened = new object(); private static readonly object EvOpened = new object();
private static object __evClosed = new object(); private static readonly object EvClosed = new object();
public FormBase() public FormBase()
{ {
this.Controls = new List<Base.ControlBase>(); Controls = new List<ControlBase>();
} }
public FormBase(MessageClient Client) : this() public FormBase(MessageClient client) : this()
{ {
this.Client = Client; this.Client = client;
} }
public async Task OnInit(InitEventArgs e) public async Task OnInit(InitEventArgs e)
{ {
var handler = this.Events[__evInit]?.GetInvocationList().Cast<AsyncEventHandler<InitEventArgs>>(); var handler = Events[EvInit]?.GetInvocationList().Cast<AsyncEventHandler<InitEventArgs>>();
if (handler == null) if (handler == null)
return; return;
foreach (var h in handler) foreach (var h in handler)
{ {
await Async.InvokeAllAsync<InitEventArgs>(h, this, e); await h.InvokeAllAsync(this, e);
} }
} }
@ -70,27 +69,21 @@ namespace TelegramBotBase.Form
///// </summary> ///// </summary>
public event AsyncEventHandler<InitEventArgs> Init public event AsyncEventHandler<InitEventArgs> Init
{ {
add add => Events.AddHandler(EvInit, value);
{ remove => Events.RemoveHandler(EvInit, value);
this.Events.AddHandler(__evInit, value);
}
remove
{
this.Events.RemoveHandler(__evInit, value);
}
} }
public async Task OnOpened(EventArgs e) public async Task OnOpened(EventArgs e)
{ {
var handler = this.Events[__evOpened]?.GetInvocationList().Cast<AsyncEventHandler<EventArgs>>(); var handler = Events[EvOpened]?.GetInvocationList().Cast<AsyncEventHandler<EventArgs>>();
if (handler == null) if (handler == null)
return; return;
foreach (var h in handler) foreach (var h in handler)
{ {
await Async.InvokeAllAsync<EventArgs>(h, this, e); await h.InvokeAllAsync(this, e);
} }
} }
@ -100,27 +93,21 @@ namespace TelegramBotBase.Form
/// <returns></returns> /// <returns></returns>
public event AsyncEventHandler<EventArgs> Opened public event AsyncEventHandler<EventArgs> Opened
{ {
add add => Events.AddHandler(EvOpened, value);
{ remove => Events.RemoveHandler(EvOpened, value);
this.Events.AddHandler(__evOpened, value);
}
remove
{
this.Events.RemoveHandler(__evOpened, value);
}
} }
public async Task OnClosed(EventArgs e) public async Task OnClosed(EventArgs e)
{ {
var handler = this.Events[__evClosed]?.GetInvocationList().Cast<AsyncEventHandler<EventArgs>>(); var handler = Events[EvClosed]?.GetInvocationList().Cast<AsyncEventHandler<EventArgs>>();
if (handler == null) if (handler == null)
return; return;
foreach (var h in handler) foreach (var h in handler)
{ {
await Async.InvokeAllAsync<EventArgs>(h, this, e); await h.InvokeAllAsync(this, e);
} }
} }
@ -131,14 +118,8 @@ namespace TelegramBotBase.Form
/// <returns></returns> /// <returns></returns>
public event AsyncEventHandler<EventArgs> Closed public event AsyncEventHandler<EventArgs> Closed
{ {
add add => Events.AddHandler(EvClosed, value);
{ remove => Events.RemoveHandler(EvClosed, value);
this.Events.AddHandler(__evClosed, value);
}
remove
{
this.Events.RemoveHandler(__evClosed, value);
}
} }
/// <summary> /// <summary>
@ -146,9 +127,9 @@ namespace TelegramBotBase.Form
/// </summary> /// </summary>
/// <param name="message"></param> /// <param name="message"></param>
/// <returns></returns> /// <returns></returns>
public virtual async Task ReturnFromModal(ModalDialog modal) public virtual Task ReturnFromModal(ModalDialog modal)
{ {
return Task.CompletedTask;
} }
@ -156,17 +137,19 @@ namespace TelegramBotBase.Form
/// Pre to form close, cleanup all controls /// Pre to form close, cleanup all controls
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public async Task CloseControls() public Task CloseControls()
{ {
foreach (var b in this.Controls) foreach (var b in Controls)
{ {
b.Cleanup().Wait(); b.Cleanup().Wait();
} }
return Task.CompletedTask;
} }
public virtual async Task PreLoad(MessageResult message) public virtual Task PreLoad(MessageResult message)
{ {
return Task.CompletedTask;
} }
/// <summary> /// <summary>
@ -179,7 +162,7 @@ namespace TelegramBotBase.Form
//Looking for the control by id, if not listened, raise event for all //Looking for the control by id, if not listened, raise event for all
if (message.RawData?.StartsWith("#c") ?? false) if (message.RawData?.StartsWith("#c") ?? false)
{ {
var c = this.Controls.FirstOrDefault(a => a.ControlID == message.RawData.Split('_')[0]); var c = Controls.FirstOrDefault(a => a.ControlId == message.RawData.Split('_')[0]);
if (c != null) if (c != null)
{ {
await c.Load(message); await c.Load(message);
@ -187,7 +170,7 @@ namespace TelegramBotBase.Form
} }
} }
foreach (var b in this.Controls) foreach (var b in Controls)
{ {
if (!b.Enabled) if (!b.Enabled)
continue; continue;
@ -201,9 +184,9 @@ namespace TelegramBotBase.Form
/// </summary> /// </summary>
/// <param name="message"></param> /// <param name="message"></param>
/// <returns></returns> /// <returns></returns>
public virtual async Task Load(MessageResult message) public virtual Task Load(MessageResult message)
{ {
return Task.CompletedTask;
} }
/// <summary> /// <summary>
@ -211,9 +194,9 @@ namespace TelegramBotBase.Form
/// </summary> /// </summary>
/// <param name="message"></param> /// <param name="message"></param>
/// <returns></returns> /// <returns></returns>
public virtual async Task Edited(MessageResult message) public virtual Task Edited(MessageResult message)
{ {
return Task.CompletedTask;
} }
@ -227,7 +210,7 @@ namespace TelegramBotBase.Form
//Looking for the control by id, if not listened, raise event for all //Looking for the control by id, if not listened, raise event for all
if (message.RawData.StartsWith("#c")) if (message.RawData.StartsWith("#c"))
{ {
var c = this.Controls.FirstOrDefault(a => a.ControlID == message.RawData.Split('_')[0]); var c = Controls.FirstOrDefault(a => a.ControlId == message.RawData.Split('_')[0]);
if (c != null) if (c != null)
{ {
await c.Action(message, message.RawData.Split('_')[1]); await c.Action(message, message.RawData.Split('_')[1]);
@ -235,7 +218,7 @@ namespace TelegramBotBase.Form
} }
} }
foreach (var b in this.Controls) foreach (var b in Controls)
{ {
if (!b.Enabled) if (!b.Enabled)
continue; continue;
@ -252,9 +235,9 @@ namespace TelegramBotBase.Form
/// </summary> /// </summary>
/// <param name="message"></param> /// <param name="message"></param>
/// <returns></returns> /// <returns></returns>
public virtual async Task Action(MessageResult message) public virtual Task Action(MessageResult message)
{ {
return Task.CompletedTask;
} }
/// <summary> /// <summary>
@ -262,9 +245,9 @@ namespace TelegramBotBase.Form
/// </summary> /// </summary>
/// <param name="message"></param> /// <param name="message"></param>
/// <returns></returns> /// <returns></returns>
public virtual async Task SentData(DataResult message) public virtual Task SentData(DataResult message)
{ {
return Task.CompletedTask;
} }
/// <summary> /// <summary>
@ -274,7 +257,7 @@ namespace TelegramBotBase.Form
/// <returns></returns> /// <returns></returns>
public virtual async Task RenderControls(MessageResult message) public virtual async Task RenderControls(MessageResult message)
{ {
foreach (var b in this.Controls) foreach (var b in Controls)
{ {
if (!b.Enabled) if (!b.Enabled)
continue; continue;
@ -288,9 +271,9 @@ namespace TelegramBotBase.Form
/// </summary> /// </summary>
/// <param name="message"></param> /// <param name="message"></param>
/// <returns></returns> /// <returns></returns>
public virtual async Task Render(MessageResult message) public virtual Task Render(MessageResult message)
{ {
return Task.CompletedTask;
} }
@ -302,7 +285,7 @@ namespace TelegramBotBase.Form
/// <returns></returns> /// <returns></returns>
public virtual async Task NavigateTo(FormBase newForm, params object[] args) public virtual async Task NavigateTo(FormBase newForm, params object[] args)
{ {
DeviceSession ds = this.Device; var ds = Device;
if (ds == null) if (ds == null)
return; return;
@ -311,11 +294,11 @@ namespace TelegramBotBase.Form
ds.PreviousForm = ds.ActiveForm; ds.PreviousForm = ds.ActiveForm;
ds.ActiveForm = newForm; ds.ActiveForm = newForm;
newForm.Client = this.Client; newForm.Client = Client;
newForm.Device = ds; newForm.Device = ds;
//Notify prior to close //Notify prior to close
foreach (var b in this.Controls) foreach (var b in Controls)
{ {
if (!b.Enabled) if (!b.Enabled)
continue; continue;
@ -323,13 +306,13 @@ namespace TelegramBotBase.Form
await b.Hidden(true); await b.Hidden(true);
} }
this.CloseControls().Wait(); CloseControls().Wait();
await this.OnClosed(new EventArgs()); await OnClosed(EventArgs.Empty);
await newForm.OnInit(new InitEventArgs(args)); await newForm.OnInit(new InitEventArgs(args));
await newForm.OnOpened(new EventArgs()); await newForm.OnOpened(EventArgs.Empty);
} }
/// <summary> /// <summary>
@ -339,7 +322,7 @@ namespace TelegramBotBase.Form
/// <returns></returns> /// <returns></returns>
public virtual async Task OpenModal(ModalDialog newForm, params object[] args) public virtual async Task OpenModal(ModalDialog newForm, params object[] args)
{ {
DeviceSession ds = this.Device; var ds = Device;
if (ds == null) if (ds == null)
return; return;
@ -359,7 +342,7 @@ namespace TelegramBotBase.Form
await CloseModal(newForm, parentForm); await CloseModal(newForm, parentForm);
}; };
foreach (var b in this.Controls) foreach (var b in Controls)
{ {
if (!b.Enabled) if (!b.Enabled)
continue; continue;
@ -369,14 +352,14 @@ namespace TelegramBotBase.Form
await newForm.OnInit(new InitEventArgs(args)); await newForm.OnInit(new InitEventArgs(args));
await newForm.OnOpened(new EventArgs()); await newForm.OnOpened(EventArgs.Empty);
} }
public async Task CloseModal(ModalDialog modalForm, FormBase oldForm) public Task CloseModal(ModalDialog modalForm, FormBase oldForm)
{ {
DeviceSession ds = this.Device; var ds = Device;
if (ds == null) if (ds == null)
return; return Task.CompletedTask;
if (modalForm == null) if (modalForm == null)
throw new Exception("No modal form"); throw new Exception("No modal form");
@ -386,6 +369,7 @@ namespace TelegramBotBase.Form
ds.PreviousForm = ds.ActiveForm; ds.PreviousForm = ds.ActiveForm;
ds.ActiveForm = oldForm; ds.ActiveForm = oldForm;
return Task.CompletedTask;
} }
/// <summary> /// <summary>
@ -395,12 +379,12 @@ namespace TelegramBotBase.Form
public void AddControl(ControlBase control) public void AddControl(ControlBase control)
{ {
//Duplicate check //Duplicate check
if (this.Controls.Contains(control)) if (Controls.Contains(control))
throw new ArgumentException("Control has been already added."); throw new ArgumentException("Control has been already added.");
control.ID = this.Controls.Count + 1; control.Id = Controls.Count + 1;
control.Device = this.Device; control.Device = Device;
this.Controls.Add(control); Controls.Add(control);
control.Init(); control.Init();
} }
@ -411,12 +395,12 @@ namespace TelegramBotBase.Form
/// <param name="control"></param> /// <param name="control"></param>
public void RemoveControl(ControlBase control) public void RemoveControl(ControlBase control)
{ {
if (!this.Controls.Contains(control)) if (!Controls.Contains(control))
return; return;
control.Cleanup().Wait(); control.Cleanup().Wait();
this.Controls.Remove(control); Controls.Remove(control);
} }
/// <summary> /// <summary>
@ -424,11 +408,11 @@ namespace TelegramBotBase.Form
/// </summary> /// </summary>
public void RemoveAllControls() public void RemoveAllControls()
{ {
foreach(var c in this.Controls) foreach(var c in Controls)
{ {
c.Cleanup().Wait(); c.Cleanup().Wait();
this.Controls.Remove(c); Controls.Remove(c);
} }
} }
@ -437,9 +421,9 @@ namespace TelegramBotBase.Form
/// </summary> /// </summary>
public void Dispose() public void Dispose()
{ {
this.Client = null; Client = null;
this.Device = null; Device = null;
this.IsDisposed = true; IsDisposed = true;
} }
} }
} }

View File

@ -1,17 +1,14 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Linq;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Telegram.Bot.Exceptions;
using Telegram.Bot; using Telegram.Bot;
using Telegram.Bot.Types; using Telegram.Bot.Exceptions;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Extensions.Polling; using Telegram.Bot.Extensions.Polling;
using Telegram.Bot.Types;
namespace TelegramBotBase.Base namespace TelegramBotBase.Base
{ {
@ -22,13 +19,13 @@ namespace TelegramBotBase.Base
{ {
public String APIKey { get; set; } public string ApiKey { get; set; }
public ITelegramBotClient TelegramClient { get; set; } public ITelegramBotClient TelegramClient { get; set; }
private EventHandlerList __Events { get; set; } = new EventHandlerList(); private EventHandlerList Events { get; set; } = new EventHandlerList();
private static object __evOnMessageLoop = new object(); private static readonly object EvOnMessageLoop = new object();
private static object __evOnMessage = new object(); private static object __evOnMessage = new object();
@ -36,21 +33,21 @@ namespace TelegramBotBase.Base
private static object __evCallbackQuery = new object(); private static object __evCallbackQuery = new object();
CancellationTokenSource __cancellationTokenSource; private CancellationTokenSource _cancellationTokenSource;
public MessageClient(String APIKey) public MessageClient(string apiKey)
{ {
this.APIKey = APIKey; this.ApiKey = apiKey;
this.TelegramClient = new Telegram.Bot.TelegramBotClient(APIKey); TelegramClient = new TelegramBotClient(apiKey);
Prepare(); Prepare();
} }
public MessageClient(String APIKey, HttpClient proxy) public MessageClient(string apiKey, HttpClient proxy)
{ {
this.APIKey = APIKey; this.ApiKey = apiKey;
this.TelegramClient = new Telegram.Bot.TelegramBotClient(APIKey, proxy); TelegramClient = new TelegramBotClient(apiKey, proxy);
Prepare(); Prepare();
@ -58,9 +55,9 @@ namespace TelegramBotBase.Base
public MessageClient(String APIKey, Uri proxyUrl, NetworkCredential credential = null) public MessageClient(string apiKey, Uri proxyUrl, NetworkCredential credential = null)
{ {
this.APIKey = APIKey; this.ApiKey = apiKey;
var proxy = new WebProxy(proxyUrl) var proxy = new WebProxy(proxyUrl)
{ {
@ -71,7 +68,7 @@ namespace TelegramBotBase.Base
new HttpClientHandler { Proxy = proxy, UseProxy = true } new HttpClientHandler { Proxy = proxy, UseProxy = true }
); );
this.TelegramClient = new Telegram.Bot.TelegramBotClient(APIKey, httpClient); TelegramClient = new TelegramBotClient(apiKey, httpClient);
Prepare(); Prepare();
} }
@ -79,12 +76,12 @@ namespace TelegramBotBase.Base
/// <summary> /// <summary>
/// Initializes the client with a proxy /// Initializes the client with a proxy
/// </summary> /// </summary>
/// <param name="APIKey"></param> /// <param name="apiKey"></param>
/// <param name="proxyHost">i.e. 127.0.0.1</param> /// <param name="proxyHost">i.e. 127.0.0.1</param>
/// <param name="proxyPort">i.e. 10000</param> /// <param name="proxyPort">i.e. 10000</param>
public MessageClient(String APIKey, String proxyHost, int proxyPort) public MessageClient(string apiKey, string proxyHost, int proxyPort)
{ {
this.APIKey = APIKey; this.ApiKey = apiKey;
var proxy = new WebProxy(proxyHost, proxyPort); var proxy = new WebProxy(proxyHost, proxyPort);
@ -92,17 +89,17 @@ namespace TelegramBotBase.Base
new HttpClientHandler { Proxy = proxy, UseProxy = true } new HttpClientHandler { Proxy = proxy, UseProxy = true }
); );
this.TelegramClient = new Telegram.Bot.TelegramBotClient(APIKey, httpClient); TelegramClient = new TelegramBotClient(apiKey, httpClient);
Prepare(); Prepare();
} }
public MessageClient(String APIKey, Telegram.Bot.TelegramBotClient Client) public MessageClient(string apiKey, TelegramBotClient client)
{ {
this.APIKey = APIKey; this.ApiKey = apiKey;
this.TelegramClient = Client; TelegramClient = client;
Prepare(); Prepare();
} }
@ -110,7 +107,7 @@ namespace TelegramBotBase.Base
public void Prepare() public void Prepare()
{ {
this.TelegramClient.Timeout = new TimeSpan(0, 0, 30); TelegramClient.Timeout = new TimeSpan(0, 0, 30);
} }
@ -118,19 +115,16 @@ namespace TelegramBotBase.Base
public void StartReceiving() public void StartReceiving()
{ {
__cancellationTokenSource = new CancellationTokenSource(); _cancellationTokenSource = new CancellationTokenSource();
var receiverOptions = new ReceiverOptions var receiverOptions = new ReceiverOptions();
{
AllowedUpdates = { } // receive all update types
};
this.TelegramClient.StartReceiving(HandleUpdateAsync, HandleErrorAsync, receiverOptions, __cancellationTokenSource.Token); TelegramClient.StartReceiving(HandleUpdateAsync, HandleErrorAsync, receiverOptions, _cancellationTokenSource.Token);
} }
public void StopReceiving() public void StopReceiving()
{ {
__cancellationTokenSource.Cancel(); _cancellationTokenSource.Cancel();
} }
@ -143,9 +137,9 @@ namespace TelegramBotBase.Base
public Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken) public Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken)
{ {
if (exception is ApiRequestException exAPI) if (exception is ApiRequestException exApi)
{ {
Console.WriteLine($"Telegram API Error:\n[{exAPI.ErrorCode}]\n{exAPI.Message}"); Console.WriteLine($"Telegram API Error:\n[{exApi.ErrorCode}]\n{exApi.Message}");
} }
else else
{ {
@ -159,9 +153,9 @@ namespace TelegramBotBase.Base
/// This will return the current list of bot commands. /// This will return the current list of bot commands.
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public async Task<BotCommand[]> GetBotCommands(BotCommandScope scope = null, String languageCode = null) public async Task<BotCommand[]> GetBotCommands(BotCommandScope scope = null, string languageCode = null)
{ {
return await this.TelegramClient.GetMyCommandsAsync(scope, languageCode); return await TelegramClient.GetMyCommandsAsync(scope, languageCode);
} }
@ -170,18 +164,18 @@ namespace TelegramBotBase.Base
/// </summary> /// </summary>
/// <param name="botcommands"></param> /// <param name="botcommands"></param>
/// <returns></returns> /// <returns></returns>
public async Task SetBotCommands(List<BotCommand> botcommands, BotCommandScope scope = null, String languageCode = null) public async Task SetBotCommands(List<BotCommand> botcommands, BotCommandScope scope = null, string languageCode = null)
{ {
await this.TelegramClient.SetMyCommandsAsync(botcommands, scope, languageCode); await TelegramClient.SetMyCommandsAsync(botcommands, scope, languageCode);
} }
/// <summary> /// <summary>
/// This will delete the current list of bot commands. /// This will delete the current list of bot commands.
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public async Task DeleteBotCommands(BotCommandScope scope = null, String languageCode = null) public async Task DeleteBotCommands(BotCommandScope scope = null, string languageCode = null)
{ {
await this.TelegramClient.DeleteMyCommandsAsync(scope, languageCode); await TelegramClient.DeleteMyCommandsAsync(scope, languageCode);
} }
@ -191,19 +185,13 @@ namespace TelegramBotBase.Base
public event Async.AsyncEventHandler<UpdateResult> MessageLoop public event Async.AsyncEventHandler<UpdateResult> MessageLoop
{ {
add add => Events.AddHandler(EvOnMessageLoop, value);
{ remove => Events.RemoveHandler(EvOnMessageLoop, value);
this.__Events.AddHandler(__evOnMessageLoop, value);
}
remove
{
this.__Events.RemoveHandler(__evOnMessageLoop, value);
}
} }
public void OnMessageLoop(UpdateResult update) public void OnMessageLoop(UpdateResult update)
{ {
(this.__Events[__evOnMessageLoop] as Async.AsyncEventHandler<UpdateResult>)?.Invoke(this, update); (Events[EvOnMessageLoop] as Async.AsyncEventHandler<UpdateResult>)?.Invoke(this, update);
} }

View File

@ -1,110 +1,56 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Telegram.Bot; using Newtonsoft.Json;
using Telegram.Bot.Types; using Telegram.Bot.Types;
using TelegramBotBase.Sessions; using Telegram.Bot.Types.Enums;
namespace TelegramBotBase.Base namespace TelegramBotBase.Base
{ {
public class MessageResult : ResultBase public class MessageResult : ResultBase
{ {
public Telegram.Bot.Types.Update UpdateData { get; set; } public Update UpdateData { get; set; }
/// <summary> /// <summary>
/// Returns the Device/ChatId /// Returns the Device/ChatId
/// </summary> /// </summary>
public override long DeviceId public override long DeviceId =>
{ UpdateData?.Message?.Chat?.Id
get ?? UpdateData?.EditedMessage?.Chat.Id
{ ?? UpdateData?.CallbackQuery.Message?.Chat.Id
return this.UpdateData?.Message?.Chat?.Id ?? Device?.DeviceId
?? this.UpdateData?.EditedMessage?.Chat.Id ?? 0;
?? this.UpdateData?.CallbackQuery.Message?.Chat.Id
?? Device?.DeviceId
?? 0;
}
}
/// <summary> /// <summary>
/// The message id /// The message id
/// </summary> /// </summary>
public new int MessageId public new int MessageId =>
{ UpdateData?.Message?.MessageId
get ?? Message?.MessageId
{ ?? UpdateData?.CallbackQuery?.Message?.MessageId
return this.UpdateData?.Message?.MessageId ?? 0;
?? this.Message?.MessageId
?? this.UpdateData?.CallbackQuery?.Message?.MessageId
?? 0;
}
}
public String Command public string Command => UpdateData?.Message?.Text ?? "";
{
get
{
return this.UpdateData?.Message?.Text ?? "";
}
}
public String MessageText public string MessageText => UpdateData?.Message?.Text ?? "";
{
get
{
return this.UpdateData?.Message?.Text ?? "";
}
}
public Telegram.Bot.Types.Enums.MessageType MessageType public MessageType MessageType => Message?.Type ?? MessageType.Unknown;
{
get
{
return Message?.Type ?? Telegram.Bot.Types.Enums.MessageType.Unknown;
}
}
public Message Message
{
get
{
return this.UpdateData?.Message
?? this.UpdateData?.EditedMessage
?? this.UpdateData?.ChannelPost
?? this.UpdateData?.EditedChannelPost
?? this.UpdateData?.CallbackQuery?.Message;
}
}
/// <summary> /// <summary>
/// Is this an action ? (i.e. button click) /// Is this an action ? (i.e. button click)
/// </summary> /// </summary>
public bool IsAction public bool IsAction => (UpdateData.CallbackQuery != null);
{
get
{
return (this.UpdateData.CallbackQuery != null);
}
}
/// <summary> /// <summary>
/// Is this a command ? Starts with a slash '/' and a command /// Is this a command ? Starts with a slash '/' and a command
/// </summary> /// </summary>
public bool IsBotCommand public bool IsBotCommand => (MessageText.StartsWith("/"));
{
get
{
return (this.MessageText.StartsWith("/"));
}
}
/// <summary> /// <summary>
/// Returns a List of all parameters which has been sent with the command itself (i.e. /start 123 456 789 => 123,456,789) /// Returns a List of all parameters which has been sent with the command itself (i.e. /start 123 456 789 => 123,456,789)
/// </summary> /// </summary>
public List<String> BotCommandParameters public List<string> BotCommandParameters
{ {
get get
{ {
@ -112,21 +58,21 @@ namespace TelegramBotBase.Base
return new List<string>(); return new List<string>();
//Split by empty space and skip first entry (command itself), return as list //Split by empty space and skip first entry (command itself), return as list
return this.MessageText.Split(' ').Skip(1).ToList(); return MessageText.Split(' ').Skip(1).ToList();
} }
} }
/// <summary> /// <summary>
/// Returns just the command (i.e. /start 1 2 3 => /start) /// Returns just the command (i.e. /start 1 2 3 => /start)
/// </summary> /// </summary>
public String BotCommand public string BotCommand
{ {
get get
{ {
if (!IsBotCommand) if (!IsBotCommand)
return null; return null;
return this.MessageText.Split(' ')[0]; return MessageText.Split(' ')[0];
} }
} }
@ -137,13 +83,7 @@ namespace TelegramBotBase.Base
public bool Handled { get; set; } = false; public bool Handled { get; set; } = false;
public String RawData public string RawData => UpdateData?.CallbackQuery?.Data;
{
get
{
return this.UpdateData?.CallbackQuery?.Data;
}
}
public T GetData<T>() public T GetData<T>()
where T : class where T : class
@ -151,7 +91,7 @@ namespace TelegramBotBase.Base
T cd = null; T cd = null;
try try
{ {
cd = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(this.RawData); cd = JsonConvert.DeserializeObject<T>(RawData);
return cd; return cd;
} }
@ -168,16 +108,16 @@ namespace TelegramBotBase.Base
/// </summary> /// </summary>
/// <param name="message"></param> /// <param name="message"></param>
/// <returns></returns> /// <returns></returns>
public async Task ConfirmAction(String message = "", bool showAlert = false, String urlToOpen = null) public async Task ConfirmAction(string message = "", bool showAlert = false, string urlToOpen = null)
{ {
await this.Device.ConfirmAction(this.UpdateData.CallbackQuery.Id, message, showAlert, urlToOpen); await Device.ConfirmAction(UpdateData.CallbackQuery.Id, message, showAlert, urlToOpen);
} }
public override async Task DeleteMessage() public override async Task DeleteMessage()
{ {
try try
{ {
await base.DeleteMessage(this.MessageId); await base.DeleteMessage(MessageId);
} }
catch catch
{ {
@ -190,9 +130,9 @@ namespace TelegramBotBase.Base
} }
public MessageResult(Telegram.Bot.Types.Update update) public MessageResult(Update update)
{ {
this.UpdateData = update; UpdateData = update;
} }

View File

@ -1,9 +1,7 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Telegram.Bot; using Telegram.Bot;
using Telegram.Bot.Types;
using TelegramBotBase.Sessions; using TelegramBotBase.Sessions;
namespace TelegramBotBase.Base namespace TelegramBotBase.Base
@ -18,15 +16,9 @@ namespace TelegramBotBase.Base
public virtual long DeviceId { get; set; } public virtual long DeviceId { get; set; }
public int MessageId public int MessageId => Message.MessageId;
{
get
{
return this.Message.MessageId;
}
}
public virtual Telegram.Bot.Types.Message Message { get; set; } public virtual Message Message { get; set; }
/// <summary> /// <summary>
/// Deletes the current message /// Deletes the current message
@ -35,7 +27,7 @@ namespace TelegramBotBase.Base
/// <returns></returns> /// <returns></returns>
public virtual async Task DeleteMessage() public virtual async Task DeleteMessage()
{ {
await DeleteMessage(this.MessageId); await DeleteMessage(MessageId);
} }
/// <summary> /// <summary>
@ -47,7 +39,7 @@ namespace TelegramBotBase.Base
{ {
try try
{ {
await Device.Client.TelegramClient.DeleteMessageAsync(this.DeviceId, (messageId == -1 ? this.MessageId : messageId)); await Device.Client.TelegramClient.DeleteMessageAsync(DeviceId, (messageId == -1 ? MessageId : messageId));
} }
catch catch
{ {

View File

@ -1,11 +1,9 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text;
namespace TelegramBotBase.Base namespace TelegramBotBase.Base
{ {
public partial class StateContainer public class StateContainer
{ {
public List<StateEntry> States { get; set; } public List<StateEntry> States { get; set; }
@ -27,7 +25,7 @@ namespace TelegramBotBase.Base
public StateContainer() public StateContainer()
{ {
this.States = new List<StateEntry>(); States = new List<StateEntry>();
} }
} }

View File

@ -1,8 +1,5 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Runtime.Serialization;
using System.Text;
namespace TelegramBotBase.Base namespace TelegramBotBase.Base
{ {
@ -18,26 +15,26 @@ namespace TelegramBotBase.Base
/// <summary> /// <summary>
/// Contains the Username (on privat chats) or Group title on groups/channels. /// Contains the Username (on privat chats) or Group title on groups/channels.
/// </summary> /// </summary>
public String ChatTitle { get; set; } public string ChatTitle { get; set; }
/// <summary> /// <summary>
/// Contains additional values to save. /// Contains additional values to save.
/// </summary> /// </summary>
public Dictionary<String, object> Values { get; set; } public Dictionary<string, object> Values { get; set; }
/// <summary> /// <summary>
/// Contains the full qualified namespace of the form to used for reload it via reflection. /// Contains the full qualified namespace of the form to used for reload it via reflection.
/// </summary> /// </summary>
public String FormUri {get;set;} public string FormUri {get;set;}
/// <summary> /// <summary>
/// Contains the assembly, where to find that form. /// Contains the assembly, where to find that form.
/// </summary> /// </summary>
public String QualifiedName { get; set; } public string QualifiedName { get; set; }
public StateEntry() public StateEntry()
{ {
this.Values = new Dictionary<string, object>(); Values = new Dictionary<string, object>();
} }
} }

View File

@ -1,8 +1,4 @@
using System; using Telegram.Bot.Types;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Telegram.Bot.Types;
using TelegramBotBase.Sessions; using TelegramBotBase.Sessions;
namespace TelegramBotBase.Base namespace TelegramBotBase.Base
@ -14,46 +10,26 @@ namespace TelegramBotBase.Base
RawData = rawData; RawData = rawData;
Device = device; Device = device;
} }
/// <summary> /// <summary>
/// Returns the Device/ChatId /// Returns the Device/ChatId
/// </summary> /// </summary>
public override long DeviceId public override long DeviceId =>
{ RawData?.Message?.Chat?.Id
get ?? RawData?.CallbackQuery?.Message?.Chat?.Id
{ ?? Device?.DeviceId
return this.RawData?.Message?.Chat?.Id ?? 0;
?? this.RawData?.CallbackQuery?.Message?.Chat?.Id
?? Device?.DeviceId
?? 0;
}
}
public Update RawData { get; set; } public Update RawData { get; set; }
public override Message Message public override Message Message =>
{ RawData?.Message
get ?? RawData?.EditedMessage
{ ?? RawData?.ChannelPost
return RawData?.Message ?? RawData?.EditedChannelPost
?? RawData?.EditedMessage ?? RawData?.CallbackQuery?.Message;
?? RawData?.ChannelPost
?? RawData?.EditedChannelPost
?? RawData?.CallbackQuery?.Message;
}
}
public DeviceSession Device
{
get;
set;
}
} }
} }

View File

@ -31,7 +31,7 @@ namespace TelegramBotBase
/// <summary> /// <summary>
/// Your TelegramBot APIKey /// Your TelegramBot APIKey
/// </summary> /// </summary>
public String APIKey { get; set; } = ""; public string ApiKey { get; set; } = "";
/// <summary> /// <summary>
/// List of all running/active sessions /// List of all running/active sessions
@ -46,19 +46,19 @@ namespace TelegramBotBase
#region "Events" #region "Events"
private EventHandlerList __Events = new EventHandlerList(); private readonly EventHandlerList _events = new EventHandlerList();
private static object __evSessionBegins = new object(); private static readonly object EvSessionBegins = new object();
private static object __evMessage = new object(); private static readonly object EvMessage = new object();
private static object __evSystemCall = new object(); private static object __evSystemCall = new object();
public delegate Task BotCommandEventHandler(object sender, BotCommandEventArgs e); public delegate Task BotCommandEventHandler(object sender, BotCommandEventArgs e);
private static object __evException = new object(); private static readonly object EvException = new object();
private static object __evUnhandledCall = new object(); private static readonly object EvUnhandledCall = new object();
#endregion #endregion
@ -81,22 +81,24 @@ namespace TelegramBotBase
/// <summary> /// <summary>
/// All internal used settings. /// All internal used settings.
/// </summary> /// </summary>
public Dictionary<eSettings, uint> SystemSettings { get; private set; } public Dictionary<ESettings, uint> SystemSettings { get; private set; }
public BotBase() public BotBase()
{ {
this.SystemSettings = new Dictionary<eSettings, uint>(); SystemSettings = new Dictionary<ESettings, uint>();
SetSetting(eSettings.MaxNumberOfRetries, 5); SetSetting(ESettings.MaxNumberOfRetries, 5);
SetSetting(eSettings.NavigationMaximum, 10); SetSetting(ESettings.NavigationMaximum, 10);
SetSetting(eSettings.LogAllMessages, false); SetSetting(ESettings.LogAllMessages, false);
SetSetting(eSettings.SkipAllMessages, false); SetSetting(ESettings.SkipAllMessages, false);
SetSetting(eSettings.SaveSessionsOnConsoleExit, false); SetSetting(ESettings.SaveSessionsOnConsoleExit, false);
this.BotCommandScopes = new Dictionary<BotCommandScope, List<BotCommand>>(); BotCommandScopes = new Dictionary<BotCommandScope, List<BotCommand>>();
this.Sessions = new SessionBase(); Sessions = new SessionBase
this.Sessions.BotBase = this; {
BotBase = this
};
} }
@ -106,38 +108,38 @@ namespace TelegramBotBase
/// </summary> /// </summary>
public void Start() public void Start()
{ {
if (this.Client == null) if (Client == null)
return; return;
this.Client.MessageLoop += Client_MessageLoop; Client.MessageLoop += Client_MessageLoop;
if (this.StateMachine != null) if (StateMachine != null)
{ {
this.Sessions.LoadSessionStates(this.StateMachine); Sessions.LoadSessionStates(StateMachine);
} }
//Enable auto session saving //Enable auto session saving
if (this.GetSetting(eSettings.SaveSessionsOnConsoleExit, false)) if (GetSetting(ESettings.SaveSessionsOnConsoleExit, false))
{ {
TelegramBotBase.Tools.Console.SetHandler(() => Tools.Console.SetHandler(() =>
{ {
this.Sessions.SaveSessionStates(); Sessions.SaveSessionStates();
}); });
} }
DeviceSession.MaxNumberOfRetries = this.GetSetting(eSettings.MaxNumberOfRetries, 5); DeviceSession.MaxNumberOfRetries = GetSetting(ESettings.MaxNumberOfRetries, 5);
this.Client.StartReceiving(); Client.StartReceiving();
} }
private async Task Client_MessageLoop(object sender, UpdateResult e) private async Task Client_MessageLoop(object sender, UpdateResult e)
{ {
DeviceSession ds = this.Sessions.GetSession(e.DeviceId); var ds = Sessions.GetSession(e.DeviceId);
if (ds == null) if (ds == null)
{ {
ds = this.Sessions.StartSession(e.DeviceId).GetAwaiter().GetResult(); ds = Sessions.StartSession(e.DeviceId).GetAwaiter().GetResult();
e.Device = ds; e.Device = ds;
ds.LastMessage = e.RawData.Message; ds.LastMessage = e.RawData.Message;
@ -146,7 +148,7 @@ namespace TelegramBotBase
var mr = new MessageResult(e.RawData); var mr = new MessageResult(e.RawData);
int i = 0; var i = 0;
//Should formulars get navigated (allow maximum of 10, to dont get loops) //Should formulars get navigated (allow maximum of 10, to dont get loops)
do do
@ -160,7 +162,7 @@ namespace TelegramBotBase
mr.IsFirstHandler = false; mr.IsFirstHandler = false;
} while (ds.FormSwitched && i < this.GetSetting(eSettings.NavigationMaximum, 10)); } while (ds.FormSwitched && i < GetSetting(ESettings.NavigationMaximum, 10));
} }
@ -169,15 +171,15 @@ namespace TelegramBotBase
/// </summary> /// </summary>
public void Stop() public void Stop()
{ {
if (this.Client == null) if (Client == null)
return; return;
this.Client.MessageLoop -= Client_MessageLoop; Client.MessageLoop -= Client_MessageLoop;
this.Client.StopReceiving(); Client.StopReceiving();
this.Sessions.SaveSessionStates(); Sessions.SaveSessionStates();
} }
/// <summary> /// <summary>
@ -185,14 +187,14 @@ namespace TelegramBotBase
/// </summary> /// </summary>
/// <param name="message"></param> /// <param name="message"></param>
/// <returns></returns> /// <returns></returns>
public async Task SentToAll(String message) public async Task SentToAll(string message)
{ {
if (this.Client == null) if (Client == null)
return; return;
foreach (var s in this.Sessions.SessionList) foreach (var s in Sessions.SessionList)
{ {
await this.Client.TelegramClient.SendTextMessageAsync(s.Key, message); await Client.TelegramClient.SendTextMessageAsync(s.Key, message);
} }
} }
@ -201,29 +203,30 @@ namespace TelegramBotBase
/// <summary> /// <summary>
/// This will invoke the full message loop for the device even when no "userevent" like message or action has been raised. /// This will invoke the full message loop for the device even when no "userevent" like message or action has been raised.
/// </summary> /// </summary>
/// <param name="DeviceId">Contains the device/chat id of the device to update.</param> /// <param name="deviceId">Contains the device/chat id of the device to update.</param>
public async Task InvokeMessageLoop(long DeviceId) public async Task InvokeMessageLoop(long deviceId)
{ {
var mr = new MessageResult(); var mr = new MessageResult
mr.UpdateData = new Update()
{ {
Message = new Message() UpdateData = new Update()
{
Message = new Message()
}
}; };
await InvokeMessageLoop(DeviceId, mr); await InvokeMessageLoop(deviceId, mr);
} }
/// <summary> /// <summary>
/// This will invoke the full message loop for the device even when no "userevent" like message or action has been raised. /// This will invoke the full message loop for the device even when no "userevent" like message or action has been raised.
/// </summary> /// </summary>
/// <param name="DeviceId">Contains the device/chat id of the device to update.</param> /// <param name="deviceId">Contains the device/chat id of the device to update.</param>
/// <param name="e"></param> /// <param name="e"></param>
public async Task InvokeMessageLoop(long DeviceId, MessageResult e) public async Task InvokeMessageLoop(long deviceId, MessageResult e)
{ {
try try
{ {
DeviceSession ds = this.Sessions.GetSession(DeviceId); var ds = Sessions.GetSession(deviceId);
e.Device = ds; e.Device = ds;
await MessageLoopFactory.MessageLoop(this, ds, new UpdateResult(e.UpdateData, ds), e); await MessageLoopFactory.MessageLoop(this, ds, new UpdateResult(e.UpdateData, ds), e);
@ -231,8 +234,8 @@ namespace TelegramBotBase
} }
catch (Exception ex) catch (Exception ex)
{ {
DeviceSession ds = this.Sessions.GetSession(DeviceId); var ds = Sessions.GetSession(deviceId);
OnException(new SystemExceptionEventArgs(e.Message.Text, DeviceId, ds, ex)); OnException(new SystemExceptionEventArgs(e.Message.Text, deviceId, ds, ex));
} }
} }
@ -252,17 +255,17 @@ namespace TelegramBotBase
/// </summary> /// </summary>
public async Task UploadBotCommands() public async Task UploadBotCommands()
{ {
foreach (var bs in this.BotCommandScopes) foreach (var bs in BotCommandScopes)
{ {
if(bs.Value !=null) if(bs.Value !=null)
{ {
await this.Client.SetBotCommands(bs.Value, bs.Key); await Client.SetBotCommands(bs.Value, bs.Key);
} }
else else
{ {
await this.Client.DeleteBotCommands(bs.Key); await Client.DeleteBotCommands(bs.Key);
} }
} }
} }
@ -271,9 +274,9 @@ namespace TelegramBotBase
/// </summary> /// </summary>
/// <param name="command"></param> /// <param name="command"></param>
/// <returns></returns> /// <returns></returns>
public bool IsKnownBotCommand(String command) public bool IsKnownBotCommand(string command)
{ {
foreach (var scope in this.BotCommandScopes) foreach (var scope in BotCommandScopes)
{ {
if (scope.Value.Any(a => "/" + a.Command == command)) if (scope.Value.Any(a => "/" + a.Command == command))
return true; return true;
@ -286,20 +289,20 @@ namespace TelegramBotBase
/// Could set a variety of settings to improve the bot handling. /// Could set a variety of settings to improve the bot handling.
/// </summary> /// </summary>
/// <param name="set"></param> /// <param name="set"></param>
/// <param name="Value"></param> /// <param name="value"></param>
public void SetSetting(eSettings set, uint Value) public void SetSetting(ESettings set, uint value)
{ {
this.SystemSettings[set] = Value; SystemSettings[set] = value;
} }
/// <summary> /// <summary>
/// Could set a variety of settings to improve the bot handling. /// Could set a variety of settings to improve the bot handling.
/// </summary> /// </summary>
/// <param name="set"></param> /// <param name="set"></param>
/// <param name="Value"></param> /// <param name="value"></param>
public void SetSetting(eSettings set, bool Value) public void SetSetting(ESettings set, bool value)
{ {
this.SystemSettings[set] = (Value ? 1u : 0u); SystemSettings[set] = (value ? 1u : 0u);
} }
/// <summary> /// <summary>
@ -308,12 +311,12 @@ namespace TelegramBotBase
/// <param name="set"></param> /// <param name="set"></param>
/// <param name="defaultValue"></param> /// <param name="defaultValue"></param>
/// <returns></returns> /// <returns></returns>
public uint GetSetting(eSettings set, uint defaultValue) public uint GetSetting(ESettings set, uint defaultValue)
{ {
if (!this.SystemSettings.ContainsKey(set)) if (!SystemSettings.ContainsKey(set))
return defaultValue; return defaultValue;
return this.SystemSettings[set]; return SystemSettings[set];
} }
/// <summary> /// <summary>
@ -322,12 +325,12 @@ namespace TelegramBotBase
/// <param name="set"></param> /// <param name="set"></param>
/// <param name="defaultValue"></param> /// <param name="defaultValue"></param>
/// <returns></returns> /// <returns></returns>
public bool GetSetting(eSettings set, bool defaultValue) public bool GetSetting(ESettings set, bool defaultValue)
{ {
if (!this.SystemSettings.ContainsKey(set)) if (!SystemSettings.ContainsKey(set))
return defaultValue; return defaultValue;
return this.SystemSettings[set] == 0u ? false : true; return SystemSettings[set] == 0u ? false : true;
} }
#region "Events" #region "Events"
@ -338,19 +341,13 @@ namespace TelegramBotBase
public event EventHandler<SessionBeginEventArgs> SessionBegins public event EventHandler<SessionBeginEventArgs> SessionBegins
{ {
add add => _events.AddHandler(EvSessionBegins, value);
{ remove => _events.RemoveHandler(EvSessionBegins, value);
this.__Events.AddHandler(__evSessionBegins, value);
}
remove
{
this.__Events.RemoveHandler(__evSessionBegins, value);
}
} }
public void OnSessionBegins(SessionBeginEventArgs e) public void OnSessionBegins(SessionBeginEventArgs e)
{ {
(this.__Events[__evSessionBegins] as EventHandler<SessionBeginEventArgs>)?.Invoke(this, e); (_events[EvSessionBegins] as EventHandler<SessionBeginEventArgs>)?.Invoke(this, e);
} }
@ -359,19 +356,13 @@ namespace TelegramBotBase
/// </summary> /// </summary>
public event EventHandler<MessageIncomeEventArgs> Message public event EventHandler<MessageIncomeEventArgs> Message
{ {
add add => _events.AddHandler(EvMessage, value);
{ remove => _events.RemoveHandler(EvMessage, value);
this.__Events.AddHandler(__evMessage, value);
}
remove
{
this.__Events.RemoveHandler(__evMessage, value);
}
} }
public void OnMessage(MessageIncomeEventArgs e) public void OnMessage(MessageIncomeEventArgs e)
{ {
(this.__Events[__evMessage] as EventHandler<MessageIncomeEventArgs>)?.Invoke(this, e); (_events[EvMessage] as EventHandler<MessageIncomeEventArgs>)?.Invoke(this, e);
} }
@ -383,7 +374,7 @@ namespace TelegramBotBase
public async Task OnBotCommand(BotCommandEventArgs e) public async Task OnBotCommand(BotCommandEventArgs e)
{ {
if (this.BotCommand != null) if (BotCommand != null)
await BotCommand(this, e); await BotCommand(this, e);
} }
@ -392,19 +383,13 @@ namespace TelegramBotBase
/// </summary> /// </summary>
public event EventHandler<SystemExceptionEventArgs> Exception public event EventHandler<SystemExceptionEventArgs> Exception
{ {
add add => _events.AddHandler(EvException, value);
{ remove => _events.RemoveHandler(EvException, value);
this.__Events.AddHandler(__evException, value);
}
remove
{
this.__Events.RemoveHandler(__evException, value);
}
} }
public void OnException(SystemExceptionEventArgs e) public void OnException(SystemExceptionEventArgs e)
{ {
(this.__Events[__evException] as EventHandler<SystemExceptionEventArgs>)?.Invoke(this, e); (_events[EvException] as EventHandler<SystemExceptionEventArgs>)?.Invoke(this, e);
} }
@ -413,19 +398,13 @@ namespace TelegramBotBase
/// </summary> /// </summary>
public event EventHandler<UnhandledCallEventArgs> UnhandledCall public event EventHandler<UnhandledCallEventArgs> UnhandledCall
{ {
add add => _events.AddHandler(EvUnhandledCall, value);
{ remove => _events.RemoveHandler(EvUnhandledCall, value);
this.__Events.AddHandler(__evUnhandledCall, value);
}
remove
{
this.__Events.RemoveHandler(__evUnhandledCall, value);
}
} }
public void OnUnhandledCall(UnhandledCallEventArgs e) public void OnUnhandledCall(UnhandledCallEventArgs e)
{ {
(this.__Events[__evUnhandledCall] as EventHandler<UnhandledCallEventArgs>)?.Invoke(this, e); (_events[EvUnhandledCall] as EventHandler<UnhandledCallEventArgs>)?.Invoke(this, e);
} }

View File

@ -1,7 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net.Http; using System.Net.Http;
using System.Text;
using Telegram.Bot; using Telegram.Bot;
using Telegram.Bot.Types; using Telegram.Bot.Types;
using TelegramBotBase.Base; using TelegramBotBase.Base;
@ -11,29 +10,27 @@ using TelegramBotBase.Factories;
using TelegramBotBase.Form; using TelegramBotBase.Form;
using TelegramBotBase.Interfaces; using TelegramBotBase.Interfaces;
using TelegramBotBase.Localizations; using TelegramBotBase.Localizations;
using TelegramBotBase.MessageLoops;
using TelegramBotBase.States; using TelegramBotBase.States;
namespace TelegramBotBase.Builder namespace TelegramBotBase.Builder
{ {
public class BotBaseBuilder : IAPIKeySelectionStage, IMessageLoopSelectionStage, IStartFormSelectionStage, IBuildingStage, INetworkingSelectionStage, IBotCommandsStage, ISessionSerializationStage, ILanguageSelectionStage public class BotBaseBuilder : IAPIKeySelectionStage, IMessageLoopSelectionStage, IStartFormSelectionStage, IBuildingStage, INetworkingSelectionStage, IBotCommandsStage, ISessionSerializationStage, ILanguageSelectionStage
{ {
private string _apiKey;
String _apiKey = null; private IStartFormFactory _factory;
IStartFormFactory _factory = null; private MessageClient _client;
MessageClient _client = null;
/// <summary> /// <summary>
/// Contains different Botcommands for different areas. /// Contains different Botcommands for different areas.
/// </summary> /// </summary>
Dictionary<BotCommandScope, List<BotCommand>> _BotCommandScopes { get; set; } = new Dictionary<BotCommandScope, List<BotCommand>>(); private Dictionary<BotCommandScope, List<BotCommand>> BotCommandScopes { get; set; } = new Dictionary<BotCommandScope, List<BotCommand>>();
//List<BotCommand> _botcommands = new List<BotCommand>(); private IStateMachine _statemachine;
IStateMachine _statemachine = null; private IMessageLoopFactory _messageLoopFactory;
IMessageLoopFactory _messageloopfactory = null;
private BotBaseBuilder() private BotBaseBuilder()
{ {
@ -49,15 +46,15 @@ namespace TelegramBotBase.Builder
public IMessageLoopSelectionStage WithAPIKey(string apiKey) public IMessageLoopSelectionStage WithAPIKey(string apiKey)
{ {
this._apiKey = apiKey; _apiKey = apiKey;
return this; return this;
} }
public IBuildingStage QuickStart(string apiKey, Type StartForm) public IBuildingStage QuickStart(string apiKey, Type StartForm)
{ {
this._apiKey = apiKey; _apiKey = apiKey;
this._factory = new Factories.DefaultStartFormFactory(StartForm); _factory = new DefaultStartFormFactory(StartForm);
DefaultMessageLoop(); DefaultMessageLoop();
@ -76,8 +73,8 @@ namespace TelegramBotBase.Builder
public IBuildingStage QuickStart<T>(string apiKey) public IBuildingStage QuickStart<T>(string apiKey)
where T : FormBase where T : FormBase
{ {
this._apiKey = apiKey; _apiKey = apiKey;
this._factory = new Factories.DefaultStartFormFactory(typeof(T)); _factory = new DefaultStartFormFactory(typeof(T));
DefaultMessageLoop(); DefaultMessageLoop();
@ -94,8 +91,8 @@ namespace TelegramBotBase.Builder
public IBuildingStage QuickStart(string apiKey, IStartFormFactory StartFormFactory) public IBuildingStage QuickStart(string apiKey, IStartFormFactory StartFormFactory)
{ {
this._apiKey = apiKey; _apiKey = apiKey;
this._factory = StartFormFactory; _factory = StartFormFactory;
DefaultMessageLoop(); DefaultMessageLoop();
@ -117,7 +114,7 @@ namespace TelegramBotBase.Builder
public IStartFormSelectionStage DefaultMessageLoop() public IStartFormSelectionStage DefaultMessageLoop()
{ {
_messageloopfactory = new MessageLoops.FormBaseMessageLoop(); _messageLoopFactory = new FormBaseMessageLoop();
return this; return this;
} }
@ -125,7 +122,7 @@ namespace TelegramBotBase.Builder
public IStartFormSelectionStage MinimalMessageLoop() public IStartFormSelectionStage MinimalMessageLoop()
{ {
_messageloopfactory = new MessageLoops.MinimalMessageLoop(); _messageLoopFactory = new MinimalMessageLoop();
return this; return this;
} }
@ -133,7 +130,7 @@ namespace TelegramBotBase.Builder
public IStartFormSelectionStage CustomMessageLoop(IMessageLoopFactory messageLoopClass) public IStartFormSelectionStage CustomMessageLoop(IMessageLoopFactory messageLoopClass)
{ {
_messageloopfactory = messageLoopClass; _messageLoopFactory = messageLoopClass;
return this; return this;
} }
@ -141,7 +138,7 @@ namespace TelegramBotBase.Builder
public IStartFormSelectionStage CustomMessageLoop<T>() public IStartFormSelectionStage CustomMessageLoop<T>()
where T : class, new() where T : class, new()
{ {
_messageloopfactory = typeof(T).GetConstructor(new Type[] { })?.Invoke(new object[] { }) as IMessageLoopFactory; _messageLoopFactory = typeof(T).GetConstructor(new Type[] { })?.Invoke(new object[] { }) as IMessageLoopFactory;
return this; return this;
} }
@ -153,33 +150,33 @@ namespace TelegramBotBase.Builder
public INetworkingSelectionStage WithStartForm(Type startFormClass) public INetworkingSelectionStage WithStartForm(Type startFormClass)
{ {
this._factory = new Factories.DefaultStartFormFactory(startFormClass); _factory = new DefaultStartFormFactory(startFormClass);
return this; return this;
} }
public INetworkingSelectionStage WithStartForm<T>() public INetworkingSelectionStage WithStartForm<T>()
where T : FormBase, new() where T : FormBase, new()
{ {
this._factory = new Factories.DefaultStartFormFactory(typeof(T)); _factory = new DefaultStartFormFactory(typeof(T));
return this; return this;
} }
public INetworkingSelectionStage WithServiceProvider(Type startFormClass, IServiceProvider serviceProvider) public INetworkingSelectionStage WithServiceProvider(Type startFormClass, IServiceProvider serviceProvider)
{ {
this._factory = new ServiceProviderStartFormFactory(startFormClass, serviceProvider); _factory = new ServiceProviderStartFormFactory(startFormClass, serviceProvider);
return this; return this;
} }
public INetworkingSelectionStage WithServiceProvider<T>(IServiceProvider serviceProvider) public INetworkingSelectionStage WithServiceProvider<T>(IServiceProvider serviceProvider)
where T : FormBase where T : FormBase
{ {
this._factory = new ServiceProviderStartFormFactory<T>(serviceProvider); _factory = new ServiceProviderStartFormFactory<T>(serviceProvider);
return this; return this;
} }
public INetworkingSelectionStage WithStartFormFactory(IStartFormFactory factory) public INetworkingSelectionStage WithStartFormFactory(IStartFormFactory factory)
{ {
this._factory = factory; _factory = factory;
return this; return this;
} }
@ -191,39 +188,64 @@ namespace TelegramBotBase.Builder
public IBotCommandsStage WithProxy(string proxyAddress) public IBotCommandsStage WithProxy(string proxyAddress)
{ {
var url = new Uri(proxyAddress); var url = new Uri(proxyAddress);
_client = new MessageClient(_apiKey, url); _client = new MessageClient(_apiKey, url)
_client.TelegramClient.Timeout = new TimeSpan(0, 1, 0); {
TelegramClient =
{
Timeout = new TimeSpan(0, 1, 0)
}
};
return this; return this;
} }
public IBotCommandsStage NoProxy() public IBotCommandsStage NoProxy()
{ {
_client = new MessageClient(_apiKey); _client = new MessageClient(_apiKey)
_client.TelegramClient.Timeout = new TimeSpan(0, 1, 0); {
TelegramClient =
{
Timeout = new TimeSpan(0, 1, 0)
}
};
return this; return this;
} }
public IBotCommandsStage WithBotClient(TelegramBotClient tgclient) public IBotCommandsStage WithBotClient(TelegramBotClient tgclient)
{ {
_client = new MessageClient(_apiKey, tgclient); _client = new MessageClient(_apiKey, tgclient)
_client.TelegramClient.Timeout = new TimeSpan(0, 1, 0); {
TelegramClient =
{
Timeout = new TimeSpan(0, 1, 0)
}
};
return this; return this;
} }
public IBotCommandsStage WithHostAndPort(string proxyHost, int proxyPort) public IBotCommandsStage WithHostAndPort(string proxyHost, int proxyPort)
{ {
_client = new MessageClient(_apiKey, proxyHost, proxyPort); _client = new MessageClient(_apiKey, proxyHost, proxyPort)
_client.TelegramClient.Timeout = new TimeSpan(0, 1, 0); {
TelegramClient =
{
Timeout = new TimeSpan(0, 1, 0)
}
};
return this; return this;
} }
public IBotCommandsStage WithHttpClient(HttpClient tgclient) public IBotCommandsStage WithHttpClient(HttpClient tgclient)
{ {
_client = new MessageClient(_apiKey, tgclient); _client = new MessageClient(_apiKey, tgclient)
_client.TelegramClient.Timeout = new TimeSpan(0, 1, 0); {
TelegramClient =
{
Timeout = new TimeSpan(0, 1, 0)
}
};
return this; return this;
} }
@ -240,7 +262,7 @@ namespace TelegramBotBase.Builder
public ISessionSerializationStage OnlyStart() public ISessionSerializationStage OnlyStart()
{ {
_BotCommandScopes.Start("Starts the bot"); BotCommandScopes.Start("Starts the bot");
return this; return this;
@ -248,15 +270,15 @@ namespace TelegramBotBase.Builder
public ISessionSerializationStage DefaultCommands() public ISessionSerializationStage DefaultCommands()
{ {
_BotCommandScopes.Start("Starts the bot"); BotCommandScopes.Start("Starts the bot");
_BotCommandScopes.Help("Should show you some help"); BotCommandScopes.Help("Should show you some help");
_BotCommandScopes.Settings("Should show you some settings"); BotCommandScopes.Settings("Should show you some settings");
return this; return this;
} }
public ISessionSerializationStage CustomCommands(Action<Dictionary<BotCommandScope, List<BotCommand>>> action) public ISessionSerializationStage CustomCommands(Action<Dictionary<BotCommandScope, List<BotCommand>>> action)
{ {
action?.Invoke(_BotCommandScopes); action?.Invoke(BotCommandScopes);
return this; return this;
} }
@ -272,26 +294,26 @@ namespace TelegramBotBase.Builder
public ILanguageSelectionStage UseSerialization(IStateMachine machine) public ILanguageSelectionStage UseSerialization(IStateMachine machine)
{ {
this._statemachine = machine; _statemachine = machine;
return this; return this;
} }
public ILanguageSelectionStage UseJSON(string path) public ILanguageSelectionStage UseJSON(string path)
{ {
this._statemachine = new JSONStateMachine(path); _statemachine = new JsonStateMachine(path);
return this; return this;
} }
public ILanguageSelectionStage UseSimpleJSON(string path) public ILanguageSelectionStage UseSimpleJSON(string path)
{ {
this._statemachine = new SimpleJSONStateMachine(path); _statemachine = new SimpleJsonStateMachine(path);
return this; return this;
} }
public ILanguageSelectionStage UseXML(string path) public ILanguageSelectionStage UseXML(string path)
{ {
this._statemachine = new XMLStateMachine(path); _statemachine = new XmlStateMachine(path);
return this; return this;
} }
@ -307,19 +329,19 @@ namespace TelegramBotBase.Builder
public IBuildingStage UseEnglish() public IBuildingStage UseEnglish()
{ {
Localizations.Default.Language = new Localizations.English(); Default.Language = new English();
return this; return this;
} }
public IBuildingStage UseGerman() public IBuildingStage UseGerman()
{ {
Localizations.Default.Language = new Localizations.German(); Default.Language = new German();
return this; return this;
} }
public IBuildingStage Custom(Localization language) public IBuildingStage Custom(Localization language)
{ {
Localizations.Default.Language = language; Default.Language = language;
return this; return this;
} }
@ -328,20 +350,20 @@ namespace TelegramBotBase.Builder
public BotBase Build() public BotBase Build()
{ {
var bb = new BotBase(); var bb = new BotBase
{
bb.APIKey = _apiKey; ApiKey = _apiKey,
bb.StartFormFactory = _factory; StartFormFactory = _factory,
Client = _client
bb.Client = _client; };
bb.Sessions.Client = bb.Client; bb.Sessions.Client = bb.Client;
bb.BotCommandScopes = _BotCommandScopes; bb.BotCommandScopes = BotCommandScopes;
bb.StateMachine = _statemachine; bb.StateMachine = _statemachine;
bb.MessageLoopFactory = _messageloopfactory; bb.MessageLoopFactory = _messageLoopFactory;
bb.MessageLoopFactory.UnhandledCall += bb.MessageLoopFactory_UnhandledCall; bb.MessageLoopFactory.UnhandledCall += bb.MessageLoopFactory_UnhandledCall;

View File

@ -1,6 +1,4 @@
using System; using System;
using System.Collections.Generic;
using System.Text;
using TelegramBotBase.Form; using TelegramBotBase.Form;
using TelegramBotBase.Interfaces; using TelegramBotBase.Interfaces;
@ -13,7 +11,7 @@ namespace TelegramBotBase.Builder.Interfaces
/// </summary> /// </summary>
/// <param name="apiKey"></param> /// <param name="apiKey"></param>
/// <returns></returns> /// <returns></returns>
IMessageLoopSelectionStage WithAPIKey(String apiKey); IMessageLoopSelectionStage WithAPIKey(string apiKey);
/// <summary> /// <summary>
@ -23,7 +21,7 @@ namespace TelegramBotBase.Builder.Interfaces
/// <param name="apiKey"></param> /// <param name="apiKey"></param>
/// <param name="StartForm"></param> /// <param name="StartForm"></param>
/// <returns></returns> /// <returns></returns>
IBuildingStage QuickStart(String apiKey, Type StartForm); IBuildingStage QuickStart(string apiKey, Type StartForm);
/// <summary> /// <summary>
/// Quick and easy way to create a BotBase instance. /// Quick and easy way to create a BotBase instance.
@ -31,7 +29,7 @@ namespace TelegramBotBase.Builder.Interfaces
/// </summary> /// </summary>
/// <param name="apiKey"></param> /// <param name="apiKey"></param>
/// <returns></returns> /// <returns></returns>
IBuildingStage QuickStart<T>(String apiKey) where T : FormBase; IBuildingStage QuickStart<T>(string apiKey) where T : FormBase;
/// <summary> /// <summary>
/// Quick and easy way to create a BotBase instance. /// Quick and easy way to create a BotBase instance.
@ -40,6 +38,6 @@ namespace TelegramBotBase.Builder.Interfaces
/// <param name="apiKey"></param> /// <param name="apiKey"></param>
/// <param name="StartFormFactory"></param> /// <param name="StartFormFactory"></param>
/// <returns></returns> /// <returns></returns>
IBuildingStage QuickStart(String apiKey, IStartFormFactory StartFormFactory); IBuildingStage QuickStart(string apiKey, IStartFormFactory StartFormFactory);
} }
} }

View File

@ -1,6 +1,5 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text;
using Telegram.Bot.Types; using Telegram.Bot.Types;
namespace TelegramBotBase.Builder.Interfaces namespace TelegramBotBase.Builder.Interfaces

View File

@ -1,8 +1,4 @@
using System; namespace TelegramBotBase.Builder.Interfaces
using System.Collections.Generic;
using System.Text;
namespace TelegramBotBase.Builder.Interfaces
{ {
public interface IBuildingStage public interface IBuildingStage
{ {

View File

@ -1,7 +1,4 @@
using System; using TelegramBotBase.Localizations;
using System.Collections.Generic;
using System.Text;
using TelegramBotBase.Localizations;
namespace TelegramBotBase.Builder.Interfaces namespace TelegramBotBase.Builder.Interfaces
{ {

View File

@ -1,8 +1,4 @@
using System; using TelegramBotBase.Interfaces;
using System.Collections.Generic;
using System.Text;
using TelegramBotBase.Form;
using TelegramBotBase.Interfaces;
namespace TelegramBotBase.Builder.Interfaces namespace TelegramBotBase.Builder.Interfaces
{ {

View File

@ -1,7 +1,4 @@
using System; using System.Net.Http;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using Telegram.Bot; using Telegram.Bot;
namespace TelegramBotBase.Builder.Interfaces namespace TelegramBotBase.Builder.Interfaces
@ -14,7 +11,7 @@ namespace TelegramBotBase.Builder.Interfaces
/// </summary> /// </summary>
/// <param name="proxyAddress"></param> /// <param name="proxyAddress"></param>
/// <returns></returns> /// <returns></returns>
IBotCommandsStage WithProxy(String proxyAddress); IBotCommandsStage WithProxy(string proxyAddress);
/// <summary> /// <summary>
/// Do not choose a proxy as network configuration. /// Do not choose a proxy as network configuration.
@ -37,7 +34,7 @@ namespace TelegramBotBase.Builder.Interfaces
/// <param name="proxyHost"></param> /// <param name="proxyHost"></param>
/// <param name="Port"></param> /// <param name="Port"></param>
/// <returns></returns> /// <returns></returns>
IBotCommandsStage WithHostAndPort(String proxyHost, int Port); IBotCommandsStage WithHostAndPort(string proxyHost, int Port);
/// <summary> /// <summary>
/// Uses a custom http client. /// Uses a custom http client.

View File

@ -1,7 +1,4 @@
using System; using TelegramBotBase.Interfaces;
using System.Collections.Generic;
using System.Text;
using TelegramBotBase.Interfaces;
namespace TelegramBotBase.Builder.Interfaces namespace TelegramBotBase.Builder.Interfaces
{ {
@ -27,7 +24,7 @@ namespace TelegramBotBase.Builder.Interfaces
/// </summary> /// </summary>
/// <param name="path"></param> /// <param name="path"></param>
/// <returns></returns> /// <returns></returns>
ILanguageSelectionStage UseJSON(String path); ILanguageSelectionStage UseJSON(string path);
/// <summary> /// <summary>
@ -35,7 +32,7 @@ namespace TelegramBotBase.Builder.Interfaces
/// </summary> /// </summary>
/// <param name="path"></param> /// <param name="path"></param>
/// <returns></returns> /// <returns></returns>
ILanguageSelectionStage UseSimpleJSON(String path); ILanguageSelectionStage UseSimpleJSON(string path);
/// <summary> /// <summary>
@ -43,7 +40,7 @@ namespace TelegramBotBase.Builder.Interfaces
/// </summary> /// </summary>
/// <param name="path"></param> /// <param name="path"></param>
/// <returns></returns> /// <returns></returns>
ILanguageSelectionStage UseXML(String path); ILanguageSelectionStage UseXML(string path);
} }
} }

View File

@ -1,6 +1,4 @@
using System; using System;
using System.Collections.Generic;
using System.Text;
using TelegramBotBase.Form; using TelegramBotBase.Form;
using TelegramBotBase.Interfaces; using TelegramBotBase.Interfaces;

View File

@ -1,8 +1,5 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using System.Data;
using System.Linq; using System.Linq;
using System.Text;
using Telegram.Bot.Types; using Telegram.Bot.Types;
namespace TelegramBotBase.Commands namespace TelegramBotBase.Commands
@ -15,7 +12,7 @@ namespace TelegramBotBase.Commands
/// <param name="cmds"></param> /// <param name="cmds"></param>
/// <param name="command"></param> /// <param name="command"></param>
/// <param name="description"></param> /// <param name="description"></param>
public static void Add(this Dictionary<BotCommandScope, List<BotCommand>> cmds, String command, String description, BotCommandScope scope = null) public static void Add(this Dictionary<BotCommandScope, List<BotCommand>> cmds, string command, string description, BotCommandScope scope = null)
{ {
if (scope == null) if (scope == null)
{ {
@ -26,11 +23,11 @@ namespace TelegramBotBase.Commands
if (item.Value != null) if (item.Value != null)
{ {
item.Value.Add(new BotCommand() { Command = command, Description = description }); item.Value.Add(new BotCommand { Command = command, Description = description });
} }
else else
{ {
cmds.Add(scope, new List<BotCommand> { new BotCommand() { Command = command, Description = description } }); cmds.Add(scope, new List<BotCommand> { new BotCommand { Command = command, Description = description } });
} }
} }
@ -64,33 +61,33 @@ namespace TelegramBotBase.Commands
/// </summary> /// </summary>
/// <param name="cmds"></param> /// <param name="cmds"></param>
/// <param name="description"></param> /// <param name="description"></param>
public static void Start(this Dictionary<BotCommandScope, List<BotCommand>> cmds, String description) => Add(cmds, "start", description, null); public static void Start(this Dictionary<BotCommandScope, List<BotCommand>> cmds, string description) => Add(cmds, "start", description);
/// <summary> /// <summary>
/// Adding the default /help command with a description. /// Adding the default /help command with a description.
/// </summary> /// </summary>
/// <param name="cmds"></param> /// <param name="cmds"></param>
/// <param name="description"></param> /// <param name="description"></param>
public static void Help(this Dictionary<BotCommandScope, List<BotCommand>> cmds, String description) => Add(cmds, "help", description, null); public static void Help(this Dictionary<BotCommandScope, List<BotCommand>> cmds, string description) => Add(cmds, "help", description);
/// <summary> /// <summary>
/// Adding the default /settings command with a description. /// Adding the default /settings command with a description.
/// </summary> /// </summary>
/// <param name="cmds"></param> /// <param name="cmds"></param>
/// <param name="description"></param> /// <param name="description"></param>
public static void Settings(this Dictionary<BotCommandScope, List<BotCommand>> cmds, String description) => Add(cmds, "settings", description, null); public static void Settings(this Dictionary<BotCommandScope, List<BotCommand>> cmds, string description) => Add(cmds, "settings", description);
/// <summary> /// <summary>
/// Clears all default commands. /// Clears all default commands.
/// </summary> /// </summary>
/// <param name="cmds"></param> /// <param name="cmds"></param>
public static void ClearDefaultCommands(this Dictionary<BotCommandScope, List<BotCommand>> cmds) => Clear(cmds, null); public static void ClearDefaultCommands(this Dictionary<BotCommandScope, List<BotCommand>> cmds) => Clear(cmds);
/// <summary> /// <summary>
/// Clears all commands of a specific device. /// Clears all commands of a specific device.
/// </summary> /// </summary>
/// <param name="cmds"></param> /// <param name="cmds"></param>
public static void ClearChatCommands(this Dictionary<BotCommandScope, List<BotCommand>> cmds, long DeviceId) => Clear(cmds, new BotCommandScopeChat() { ChatId = DeviceId }); public static void ClearChatCommands(this Dictionary<BotCommandScope, List<BotCommand>> cmds, long deviceId) => Clear(cmds, new BotCommandScopeChat { ChatId = deviceId });
/// <summary> /// <summary>
/// Adding a chat command with a description. /// Adding a chat command with a description.
@ -98,7 +95,7 @@ namespace TelegramBotBase.Commands
/// <param name="cmds"></param> /// <param name="cmds"></param>
/// <param name="command"></param> /// <param name="command"></param>
/// <param name="description"></param> /// <param name="description"></param>
public static void AddChatCommand(this Dictionary<BotCommandScope, List<BotCommand>> cmds, long DeviceId, String command, String description) => Add(cmds, command, description, new BotCommandScopeChat() { ChatId = DeviceId }); public static void AddChatCommand(this Dictionary<BotCommandScope, List<BotCommand>> cmds, long deviceId, string command, string description) => Add(cmds, command, description, new BotCommandScopeChat { ChatId = deviceId });
/// <summary> /// <summary>
/// Adding a group command with a description. /// Adding a group command with a description.
@ -106,7 +103,7 @@ namespace TelegramBotBase.Commands
/// <param name="cmds"></param> /// <param name="cmds"></param>
/// <param name="command"></param> /// <param name="command"></param>
/// <param name="description"></param> /// <param name="description"></param>
public static void AddGroupCommand(this Dictionary<BotCommandScope, List<BotCommand>> cmds, String command, String description) => Add(cmds, command, description, new BotCommandScopeAllGroupChats()); public static void AddGroupCommand(this Dictionary<BotCommandScope, List<BotCommand>> cmds, string command, string description) => Add(cmds, command, description, new BotCommandScopeAllGroupChats());
/// <summary> /// <summary>
/// Clears all group commands. /// Clears all group commands.
@ -120,7 +117,7 @@ namespace TelegramBotBase.Commands
/// <param name="cmds"></param> /// <param name="cmds"></param>
/// <param name="command"></param> /// <param name="command"></param>
/// <param name="description"></param> /// <param name="description"></param>
public static void AddGroupAdminCommand(this Dictionary<BotCommandScope, List<BotCommand>> cmds, String command, String description) => Add(cmds, command, description, new BotCommandScopeAllChatAdministrators()); public static void AddGroupAdminCommand(this Dictionary<BotCommandScope, List<BotCommand>> cmds, string command, string description) => Add(cmds, command, description, new BotCommandScopeAllChatAdministrators());
/// <summary> /// <summary>
/// Clears all group admin commands. /// Clears all group admin commands.
@ -134,7 +131,7 @@ namespace TelegramBotBase.Commands
/// <param name="cmds"></param> /// <param name="cmds"></param>
/// <param name="command"></param> /// <param name="command"></param>
/// <param name="description"></param> /// <param name="description"></param>
public static void AddPrivateChatCommand(this Dictionary<BotCommandScope, List<BotCommand>> cmds, String command, String description) => Add(cmds, command, description, new BotCommandScopeAllPrivateChats()); public static void AddPrivateChatCommand(this Dictionary<BotCommandScope, List<BotCommand>> cmds, string command, string description) => Add(cmds, command, description, new BotCommandScopeAllPrivateChats());
/// <summary> /// <summary>
/// Clears all private commands. /// Clears all private commands.

View File

@ -1,10 +1,4 @@
using System; namespace TelegramBotBase.Constants
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TelegramBotBase.Constants
{ {
public static class Telegram public static class Telegram
{ {

View File

@ -1,50 +1,43 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Diagnostics.SymbolStore;
using System.Linq; using System.Linq;
using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Telegram.Bot.Types; using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types.ReplyMarkups; using Telegram.Bot.Types.ReplyMarkups;
using TelegramBotBase.Args; using TelegramBotBase.Args;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Datasources; using TelegramBotBase.DataSources;
using TelegramBotBase.Enums; using TelegramBotBase.Enums;
using TelegramBotBase.Exceptions; using TelegramBotBase.Exceptions;
using TelegramBotBase.Form; using TelegramBotBase.Form;
using TelegramBotBase.Localizations;
using static TelegramBotBase.Base.Async; using static TelegramBotBase.Base.Async;
namespace TelegramBotBase.Controls.Hybrid namespace TelegramBotBase.Controls.Hybrid
{ {
public class ButtonGrid : Base.ControlBase public class ButtonGrid : ControlBase
{ {
public String Title { get; set; } = Localizations.Default.Language["ButtonGrid_Title"]; public string Title { get; set; } = Default.Language["ButtonGrid_Title"];
public String ConfirmationText { get; set; } = ""; public string ConfirmationText { get; set; } = "";
private bool RenderNecessary = true; private bool _renderNecessary = true;
private static readonly object __evButtonClicked = new object(); private static readonly object EvButtonClicked = new object();
private readonly EventHandlerList Events = new EventHandlerList(); private readonly EventHandlerList _events = new EventHandlerList();
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
[Obsolete("This property is obsolete. Please use the DataSource property instead.")] [Obsolete("This property is obsolete. Please use the DataSource property instead.")]
public ButtonForm ButtonsForm public ButtonForm ButtonsForm
{ {
get get => DataSource.ButtonForm;
{ set => DataSource = new ButtonFormDataSource(value);
return DataSource.ButtonForm;
}
set
{
DataSource = new ButtonFormDataSource(value);
}
} }
/// <summary> /// <summary>
@ -88,23 +81,23 @@ namespace TelegramBotBase.Controls.Hybrid
/// </summary> /// </summary>
public bool EnableSearch { get; set; } = false; public bool EnableSearch { get; set; } = false;
public String SearchQuery { get; set; } public string SearchQuery { get; set; }
public eNavigationBarVisibility NavigationBarVisibility { get; set; } = eNavigationBarVisibility.always; public ENavigationBarVisibility NavigationBarVisibility { get; set; } = ENavigationBarVisibility.always;
/// <summary> /// <summary>
/// Index of the current page /// Index of the current page
/// </summary> /// </summary>
public int CurrentPageIndex { get; set; } = 0; public int CurrentPageIndex { get; set; }
public String PreviousPageLabel = Localizations.Default.Language["ButtonGrid_PreviousPage"]; public string PreviousPageLabel = Default.Language["ButtonGrid_PreviousPage"];
public String NextPageLabel = Localizations.Default.Language["ButtonGrid_NextPage"]; public string NextPageLabel = Default.Language["ButtonGrid_NextPage"];
public String NoItemsLabel = Localizations.Default.Language["ButtonGrid_NoItems"]; public string NoItemsLabel = Default.Language["ButtonGrid_NoItems"];
public String SearchLabel = Localizations.Default.Language["ButtonGrid_SearchFeature"]; public string SearchLabel = Default.Language["ButtonGrid_SearchFeature"];
/// <summary> /// <summary>
/// Layout of the buttons which should be displayed always on top. /// Layout of the buttons which should be displayed always on top.
@ -119,89 +112,80 @@ namespace TelegramBotBase.Controls.Hybrid
/// <summary> /// <summary>
/// Defines which type of Button Keyboard should be rendered. /// Defines which type of Button Keyboard should be rendered.
/// </summary> /// </summary>
public eKeyboardType KeyboardType public EKeyboardType KeyboardType
{ {
get get => _mEKeyboardType;
{
return m_eKeyboardType;
}
set set
{ {
if (m_eKeyboardType != value) if (_mEKeyboardType != value)
{ {
this.RenderNecessary = true; _renderNecessary = true;
Cleanup().Wait(); Cleanup().Wait();
m_eKeyboardType = value; _mEKeyboardType = value;
} }
} }
} }
private eKeyboardType m_eKeyboardType = eKeyboardType.ReplyKeyboard; private EKeyboardType _mEKeyboardType = EKeyboardType.ReplyKeyboard;
public ButtonGrid() public ButtonGrid()
{ {
this.DataSource = new ButtonFormDataSource(); DataSource = new ButtonFormDataSource();
} }
public ButtonGrid(eKeyboardType type) : this() public ButtonGrid(EKeyboardType type) : this()
{ {
m_eKeyboardType = type; _mEKeyboardType = type;
} }
public ButtonGrid(ButtonForm form) public ButtonGrid(ButtonForm form)
{ {
this.DataSource = new ButtonFormDataSource(form); DataSource = new ButtonFormDataSource(form);
} }
public event AsyncEventHandler<ButtonClickedEventArgs> ButtonClicked public event AsyncEventHandler<ButtonClickedEventArgs> ButtonClicked
{ {
add add => _events.AddHandler(EvButtonClicked, value);
{ remove => _events.RemoveHandler(EvButtonClicked, value);
this.Events.AddHandler(__evButtonClicked, value);
}
remove
{
this.Events.RemoveHandler(__evButtonClicked, value);
}
} }
public async Task OnButtonClicked(ButtonClickedEventArgs e) public async Task OnButtonClicked(ButtonClickedEventArgs e)
{ {
var handler = this.Events[__evButtonClicked]?.GetInvocationList().Cast<AsyncEventHandler<ButtonClickedEventArgs>>(); var handler = _events[EvButtonClicked]?.GetInvocationList().Cast<AsyncEventHandler<ButtonClickedEventArgs>>();
if (handler == null) if (handler == null)
return; return;
foreach (var h in handler) foreach (var h in handler)
{ {
await Async.InvokeAllAsync<ButtonClickedEventArgs>(h, this, e); await h.InvokeAllAsync(this, e);
} }
} }
public override void Init() public override void Init()
{ {
this.Device.MessageDeleted += Device_MessageDeleted; Device.MessageDeleted += Device_MessageDeleted;
} }
private void Device_MessageDeleted(object sender, MessageDeletedEventArgs e) private void Device_MessageDeleted(object sender, MessageDeletedEventArgs e)
{ {
if (this.MessageId == null) if (MessageId == null)
return; return;
if (e.MessageId != this.MessageId) if (e.MessageId != MessageId)
return; return;
this.MessageId = null; MessageId = null;
} }
public async override Task Load(MessageResult result) public override async Task Load(MessageResult result)
{ {
if (this.KeyboardType != eKeyboardType.ReplyKeyboard) if (KeyboardType != EKeyboardType.ReplyKeyboard)
return; return;
if (!result.IsFirstHandler) if (!result.IsFirstHandler)
@ -212,7 +196,7 @@ namespace TelegramBotBase.Controls.Hybrid
var matches = new List<ButtonRow>(); var matches = new List<ButtonRow>();
ButtonRow match = null; ButtonRow match = null;
int index = -1; var index = -1;
if (HeadLayoutButtonRow?.Matches(result.MessageText) ?? false) if (HeadLayoutButtonRow?.Matches(result.MessageText) ?? false)
{ {
@ -244,7 +228,7 @@ namespace TelegramBotBase.Controls.Hybrid
check: check:
//Remove button click message //Remove button click message
if (this.DeleteReplyMessage) if (DeleteReplyMessage)
await Device.DeleteMessage(result.MessageId); await Device.DeleteMessage(result.MessageId);
if (match != null) if (match != null)
@ -258,39 +242,39 @@ namespace TelegramBotBase.Controls.Hybrid
if (result.MessageText == PreviousPageLabel) if (result.MessageText == PreviousPageLabel)
{ {
if (this.CurrentPageIndex > 0) if (CurrentPageIndex > 0)
this.CurrentPageIndex--; CurrentPageIndex--;
this.Updated(); Updated();
} }
else if (result.MessageText == NextPageLabel) else if (result.MessageText == NextPageLabel)
{ {
if (this.CurrentPageIndex < this.PageCount - 1) if (CurrentPageIndex < PageCount - 1)
this.CurrentPageIndex++; CurrentPageIndex++;
this.Updated(); Updated();
} }
else if (this.EnableSearch) else if (EnableSearch)
{ {
if (result.MessageText.StartsWith("🔍")) if (result.MessageText.StartsWith("🔍"))
{ {
//Sent note about searching //Sent note about searching
if (this.SearchQuery == null) if (SearchQuery == null)
{ {
await this.Device.Send(this.SearchLabel); await Device.Send(SearchLabel);
} }
this.SearchQuery = null; SearchQuery = null;
this.Updated(); Updated();
return; return;
} }
this.SearchQuery = result.MessageText; SearchQuery = result.MessageText;
if (this.SearchQuery != null && this.SearchQuery != "") if (SearchQuery != null && SearchQuery != "")
{ {
this.CurrentPageIndex = 0; CurrentPageIndex = 0;
this.Updated(); Updated();
} }
} }
@ -299,7 +283,7 @@ namespace TelegramBotBase.Controls.Hybrid
} }
public async override Task Action(MessageResult result, string value = null) public override async Task Action(MessageResult result, string value = null)
{ {
if (result.Handled) if (result.Handled)
return; return;
@ -308,13 +292,13 @@ namespace TelegramBotBase.Controls.Hybrid
return; return;
//Find clicked button depending on Text or Value (depending on markup type) //Find clicked button depending on Text or Value (depending on markup type)
if (this.KeyboardType != eKeyboardType.InlineKeyBoard) if (KeyboardType != EKeyboardType.InlineKeyBoard)
return; return;
await result.ConfirmAction(this.ConfirmationText ?? ""); await result.ConfirmAction(ConfirmationText ?? "");
ButtonRow match = null; ButtonRow match = null;
int index = -1; var index = -1;
if (HeadLayoutButtonRow?.Matches(result.RawData, false) ?? false) if (HeadLayoutButtonRow?.Matches(result.RawData, false) ?? false)
{ {
@ -358,18 +342,18 @@ namespace TelegramBotBase.Controls.Hybrid
{ {
case "$previous$": case "$previous$":
if (this.CurrentPageIndex > 0) if (CurrentPageIndex > 0)
this.CurrentPageIndex--; CurrentPageIndex--;
this.Updated(); Updated();
break; break;
case "$next$": case "$next$":
if (this.CurrentPageIndex < this.PageCount - 1) if (CurrentPageIndex < PageCount - 1)
this.CurrentPageIndex++; CurrentPageIndex++;
this.Updated(); Updated();
break; break;
} }
@ -381,49 +365,49 @@ namespace TelegramBotBase.Controls.Hybrid
/// </summary> /// </summary>
private void CheckGrid() private void CheckGrid()
{ {
switch (m_eKeyboardType) switch (_mEKeyboardType)
{ {
case eKeyboardType.InlineKeyBoard: case EKeyboardType.InlineKeyBoard:
if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !this.EnablePaging) if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !EnablePaging)
{ {
throw new MaximumRowsReachedException() { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows }; throw new MaximumRowsReachedException { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows };
} }
if (DataSource.ColumnCount > Constants.Telegram.MaxInlineKeyBoardCols) if (DataSource.ColumnCount > Constants.Telegram.MaxInlineKeyBoardCols)
{ {
throw new MaximumColsException() { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols }; throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols };
} }
break; break;
case eKeyboardType.ReplyKeyboard: case EKeyboardType.ReplyKeyboard:
if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !this.EnablePaging) if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !EnablePaging)
{ {
throw new MaximumRowsReachedException() { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows }; throw new MaximumRowsReachedException { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows };
} }
if (DataSource.ColumnCount > Constants.Telegram.MaxReplyKeyboardCols) if (DataSource.ColumnCount > Constants.Telegram.MaxReplyKeyboardCols)
{ {
throw new MaximumColsException() { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols }; throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols };
} }
break; break;
} }
} }
public async override Task Render(MessageResult result) public override async Task Render(MessageResult result)
{ {
if (!this.RenderNecessary) if (!_renderNecessary)
return; return;
//Check for rows and column limits //Check for rows and column limits
CheckGrid(); CheckGrid();
this.RenderNecessary = false; _renderNecessary = false;
ButtonForm form = this.DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage, (this.EnableSearch ? this.SearchQuery : null)); var form = DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage, (EnableSearch ? SearchQuery : null));
//if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "")
@ -435,42 +419,42 @@ namespace TelegramBotBase.Controls.Hybrid
// form = form.Duplicate(); // form = form.Duplicate();
//} //}
if (this.EnablePaging) if (EnablePaging)
{ {
IntegratePagingView(form); IntegratePagingView(form);
} }
if (this.HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0)
{ {
form.InsertButtonRow(0, this.HeadLayoutButtonRow); form.InsertButtonRow(0, HeadLayoutButtonRow);
} }
if (this.SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0)
{ {
if (this.IsNavigationBarVisible) if (IsNavigationBarVisible)
{ {
form.InsertButtonRow(2, this.SubHeadLayoutButtonRow); form.InsertButtonRow(2, SubHeadLayoutButtonRow);
} }
else else
{ {
form.InsertButtonRow(1, this.SubHeadLayoutButtonRow); form.InsertButtonRow(1, SubHeadLayoutButtonRow);
} }
} }
Message m = null; Message m = null;
switch (this.KeyboardType) switch (KeyboardType)
{ {
//Reply Keyboard could only be updated with a new keyboard. //Reply Keyboard could only be updated with a new keyboard.
case eKeyboardType.ReplyKeyboard: case EKeyboardType.ReplyKeyboard:
if (form.Count == 0) if (form.Count == 0)
{ {
if (this.MessageId != null) if (MessageId != null)
{ {
await this.Device.HideReplyKeyboard(); await Device.HideReplyKeyboard();
this.MessageId = null; MessageId = null;
} }
return; return;
@ -491,39 +475,39 @@ namespace TelegramBotBase.Controls.Hybrid
var rkm = (ReplyKeyboardMarkup)form; var rkm = (ReplyKeyboardMarkup)form;
rkm.ResizeKeyboard = this.ResizeKeyboard; rkm.ResizeKeyboard = ResizeKeyboard;
rkm.OneTimeKeyboard = this.OneTimeKeyboard; rkm.OneTimeKeyboard = OneTimeKeyboard;
m = await this.Device.Send(this.Title, rkm, disableNotification: true, parseMode: MessageParseMode, MarkdownV2AutoEscape: false); m = await Device.Send(Title, rkm, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false);
//Prevent flicker of keyboard //Prevent flicker of keyboard
if (this.DeletePreviousMessage && this.MessageId != null) if (DeletePreviousMessage && MessageId != null)
await this.Device.DeleteMessage(this.MessageId.Value); await Device.DeleteMessage(MessageId.Value);
break; break;
case eKeyboardType.InlineKeyBoard: case EKeyboardType.InlineKeyBoard:
//Try to edit message if message id is available //Try to edit message if message id is available
//When the returned message is null then the message has been already deleted, resend it //When the returned message is null then the message has been already deleted, resend it
if (this.MessageId != null) if (MessageId != null)
{ {
m = await this.Device.Edit(this.MessageId.Value, this.Title, (InlineKeyboardMarkup)form); m = await Device.Edit(MessageId.Value, Title, (InlineKeyboardMarkup)form);
if (m != null) if (m != null)
{ {
this.MessageId = m.MessageId; MessageId = m.MessageId;
return; return;
} }
} }
//When no message id is available or it has been deleted due the use of AutoCleanForm re-render automatically //When no message id is available or it has been deleted due the use of AutoCleanForm re-render automatically
m = await this.Device.Send(this.Title, (InlineKeyboardMarkup)form, disableNotification: true, parseMode: MessageParseMode, MarkdownV2AutoEscape: false); m = await Device.Send(Title, (InlineKeyboardMarkup)form, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false);
break; break;
} }
if (m != null) if (m != null)
{ {
this.MessageId = m.MessageId; MessageId = m.MessageId;
} }
@ -531,23 +515,23 @@ namespace TelegramBotBase.Controls.Hybrid
private void IntegratePagingView(ButtonForm dataForm) private void IntegratePagingView(ButtonForm dataForm)
{ {
//No Items //No Items
if (dataForm.Rows == 0) if (dataForm.Rows == 0)
{ {
dataForm.AddButtonRow(new ButtonBase(NoItemsLabel, "$")); dataForm.AddButtonRow(new ButtonBase(NoItemsLabel, "$"));
} }
if (this.IsNavigationBarVisible) if (IsNavigationBarVisible)
{ {
//🔍 //🔍
ButtonRow row = new ButtonRow(); var row = new ButtonRow();
row.Add(new ButtonBase(PreviousPageLabel, "$previous$")); row.Add(new ButtonBase(PreviousPageLabel, "$previous$"));
row.Add(new ButtonBase(String.Format(Localizations.Default.Language["ButtonGrid_CurrentPage"], this.CurrentPageIndex + 1, this.PageCount), "$site$")); row.Add(new ButtonBase(string.Format(Default.Language["ButtonGrid_CurrentPage"], CurrentPageIndex + 1, PageCount), "$site$"));
row.Add(new ButtonBase(NextPageLabel, "$next$")); row.Add(new ButtonBase(NextPageLabel, "$next$"));
if (this.EnableSearch) if (EnableSearch)
{ {
row.Insert(2, new ButtonBase("🔍 " + (this.SearchQuery ?? ""), "$search$")); row.Insert(2, new ButtonBase("🔍 " + (SearchQuery ?? ""), "$search$"));
} }
dataForm.InsertButtonRow(0, row); dataForm.InsertButtonRow(0, row);
@ -560,12 +544,12 @@ namespace TelegramBotBase.Controls.Hybrid
{ {
get get
{ {
if (this.KeyboardType == eKeyboardType.InlineKeyBoard && TotalRows > Constants.Telegram.MaxInlineKeyBoardRows) if (KeyboardType == EKeyboardType.InlineKeyBoard && TotalRows > Constants.Telegram.MaxInlineKeyBoardRows)
{ {
return true; return true;
} }
if (this.KeyboardType == eKeyboardType.ReplyKeyboard && TotalRows > Constants.Telegram.MaxReplyKeyboardRows) if (KeyboardType == EKeyboardType.ReplyKeyboard && TotalRows > Constants.Telegram.MaxReplyKeyboardRows)
{ {
return true; return true;
} }
@ -578,7 +562,7 @@ namespace TelegramBotBase.Controls.Hybrid
{ {
get get
{ {
if (this.NavigationBarVisibility == eNavigationBarVisibility.always | (this.NavigationBarVisibility == eNavigationBarVisibility.auto && PagingNecessary)) if (NavigationBarVisibility == ENavigationBarVisibility.always | (NavigationBarVisibility == ENavigationBarVisibility.auto && PagingNecessary))
{ {
return true; return true;
} }
@ -594,30 +578,19 @@ namespace TelegramBotBase.Controls.Hybrid
{ {
get get
{ {
switch (this.KeyboardType) return KeyboardType switch
{ {
case eKeyboardType.InlineKeyBoard: EKeyboardType.InlineKeyBoard => Constants.Telegram.MaxInlineKeyBoardRows,
return Constants.Telegram.MaxInlineKeyBoardRows; EKeyboardType.ReplyKeyboard => Constants.Telegram.MaxReplyKeyboardRows,
_ => 0
case eKeyboardType.ReplyKeyboard: };
return Constants.Telegram.MaxReplyKeyboardRows;
default:
return 0;
}
} }
} }
/// <summary> /// <summary>
/// Returns the number of all rows (layout + navigation + content); /// Returns the number of all rows (layout + navigation + content);
/// </summary> /// </summary>
public int TotalRows public int TotalRows => LayoutRows + DataSource.RowCount;
{
get
{
return this.LayoutRows + DataSource.RowCount;
}
}
/// <summary> /// <summary>
@ -627,15 +600,15 @@ namespace TelegramBotBase.Controls.Hybrid
{ {
get get
{ {
int layoutRows = 0; var layoutRows = 0;
if (this.NavigationBarVisibility == eNavigationBarVisibility.always | this.NavigationBarVisibility == eNavigationBarVisibility.auto) if (NavigationBarVisibility == ENavigationBarVisibility.always | NavigationBarVisibility == ENavigationBarVisibility.auto)
layoutRows += 2; layoutRows += 2;
if (this.HeadLayoutButtonRow != null && this.HeadLayoutButtonRow.Count > 0) if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0)
layoutRows++; layoutRows++;
if (this.SubHeadLayoutButtonRow != null && this.SubHeadLayoutButtonRow.Count > 0) if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0)
layoutRows++; layoutRows++;
return layoutRows; return layoutRows;
@ -645,13 +618,7 @@ namespace TelegramBotBase.Controls.Hybrid
/// <summary> /// <summary>
/// Returns the number of item rows per page. /// Returns the number of item rows per page.
/// </summary> /// </summary>
public int ItemRowsPerPage public int ItemRowsPerPage => MaximumRow - LayoutRows;
{
get
{
return this.MaximumRow - this.LayoutRows;
}
}
/// <summary> /// <summary>
/// Return the number of pages. /// Return the number of pages.
@ -665,7 +632,7 @@ namespace TelegramBotBase.Controls.Hybrid
//var bf = this.DataSource.PickAllItems(this.EnableSearch ? this.SearchQuery : null); //var bf = this.DataSource.PickAllItems(this.EnableSearch ? this.SearchQuery : null);
var max = this.DataSource.CalculateMax(this.EnableSearch ? this.SearchQuery : null); var max = DataSource.CalculateMax(EnableSearch ? SearchQuery : null);
//if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "")
//{ //{
@ -675,22 +642,24 @@ namespace TelegramBotBase.Controls.Hybrid
if (max == 0) if (max == 0)
return 1; return 1;
return (int)Math.Ceiling((decimal)((decimal)max / (decimal)ItemRowsPerPage)); return (int)Math.Ceiling(max / (decimal)ItemRowsPerPage);
} }
} }
public override async Task Hidden(bool FormClose) public override Task Hidden(bool formClose)
{ {
//Prepare for opening Modal, and comming back //Prepare for opening Modal, and comming back
if (!FormClose) if (!formClose)
{ {
this.Updated(); Updated();
} }
else else
{ {
//Remove event handler //Remove event handler
this.Device.MessageDeleted -= Device_MessageDeleted; Device.MessageDeleted -= Device_MessageDeleted;
} }
return Task.CompletedTask;
} }
/// <summary> /// <summary>
@ -698,31 +667,31 @@ namespace TelegramBotBase.Controls.Hybrid
/// </summary> /// </summary>
public void Updated() public void Updated()
{ {
this.RenderNecessary = true; _renderNecessary = true;
} }
public async override Task Cleanup() public override async Task Cleanup()
{ {
if (this.MessageId == null) if (MessageId == null)
return; return;
switch (this.KeyboardType) switch (KeyboardType)
{ {
case eKeyboardType.InlineKeyBoard: case EKeyboardType.InlineKeyBoard:
await this.Device.DeleteMessage(this.MessageId.Value); await Device.DeleteMessage(MessageId.Value);
this.MessageId = null; MessageId = null;
break; break;
case eKeyboardType.ReplyKeyboard: case EKeyboardType.ReplyKeyboard:
if (this.HideKeyboardOnCleanup) if (HideKeyboardOnCleanup)
{ {
await this.Device.HideReplyKeyboard(); await Device.HideReplyKeyboard();
} }
this.MessageId = null; MessageId = null;
break; break;
} }

View File

@ -1,10 +1,7 @@
using System; using System;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Linq; using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBase.Controls.Hybrid namespace TelegramBotBase.Controls.Hybrid
@ -12,8 +9,7 @@ namespace TelegramBotBase.Controls.Hybrid
[DebuggerDisplay("{Count} columns")] [DebuggerDisplay("{Count} columns")]
public class ButtonRow public class ButtonRow
{ {
private List<ButtonBase> _buttons = new List<ButtonBase>();
List<ButtonBase> __buttons = new List<ButtonBase>();
public ButtonRow() public ButtonRow()
{ {
@ -23,59 +19,47 @@ namespace TelegramBotBase.Controls.Hybrid
public ButtonRow(params ButtonBase[] buttons) public ButtonRow(params ButtonBase[] buttons)
{ {
__buttons = buttons.ToList(); _buttons = buttons.ToList();
} }
public ButtonBase this[int index] public ButtonBase this[int index] => _buttons[index];
{
get
{
return __buttons[index];
}
}
public int Count public int Count => _buttons.Count;
{
get
{
return __buttons.Count;
}
}
public void Add(ButtonBase button) public void Add(ButtonBase button)
{ {
__buttons.Add(button); _buttons.Add(button);
} }
public void AddRange(ButtonBase button) public void AddRange(ButtonBase button)
{ {
__buttons.Add(button); _buttons.Add(button);
} }
public void Insert(int index, ButtonBase button) public void Insert(int index, ButtonBase button)
{ {
__buttons.Insert(index, button); _buttons.Insert(index, button);
} }
public IEnumerator<ButtonBase> GetEnumerator() public IEnumerator<ButtonBase> GetEnumerator()
{ {
return __buttons.GetEnumerator(); return _buttons.GetEnumerator();
} }
public ButtonBase[] ToArray() public ButtonBase[] ToArray()
{ {
return __buttons.ToArray(); return _buttons.ToArray();
} }
public List<ButtonBase> ToList() public List<ButtonBase> ToList()
{ {
return __buttons.ToList(); return _buttons.ToList();
} }
public bool Matches(String text, bool useText = true) public bool Matches(string text, bool useText = true)
{ {
foreach (var b in __buttons) foreach (var b in _buttons)
{ {
if (useText && b.Text.Trim().Equals(text, StringComparison.InvariantCultureIgnoreCase)) if (useText && b.Text.Trim().Equals(text, StringComparison.InvariantCultureIgnoreCase))
return true; return true;
@ -92,9 +76,9 @@ namespace TelegramBotBase.Controls.Hybrid
/// <param name="text"></param> /// <param name="text"></param>
/// <param name="useText"></param> /// <param name="useText"></param>
/// <returns></returns> /// <returns></returns>
public ButtonBase GetButtonMatch(String text, bool useText = true) public ButtonBase GetButtonMatch(string text, bool useText = true)
{ {
foreach (var b in __buttons) foreach (var b in _buttons)
{ {
if (useText && b.Text.Trim().Equals(text, StringComparison.InvariantCultureIgnoreCase)) if (useText && b.Text.Trim().Equals(text, StringComparison.InvariantCultureIgnoreCase))
return b; return b;
@ -106,7 +90,7 @@ namespace TelegramBotBase.Controls.Hybrid
public static implicit operator ButtonRow(List<ButtonBase> list) public static implicit operator ButtonRow(List<ButtonBase> list)
{ {
return new ButtonRow() { __buttons = list }; return new ButtonRow { _buttons = list };
} }
} }
} }

View File

@ -1,49 +1,42 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Diagnostics.SymbolStore;
using System.Linq; using System.Linq;
using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Telegram.Bot.Types; using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types.ReplyMarkups; using Telegram.Bot.Types.ReplyMarkups;
using TelegramBotBase.Args; using TelegramBotBase.Args;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Datasources; using TelegramBotBase.DataSources;
using TelegramBotBase.Enums; using TelegramBotBase.Enums;
using TelegramBotBase.Exceptions; using TelegramBotBase.Exceptions;
using TelegramBotBase.Form; using TelegramBotBase.Form;
using TelegramBotBase.Localizations;
using static TelegramBotBase.Base.Async; using static TelegramBotBase.Base.Async;
namespace TelegramBotBase.Controls.Hybrid namespace TelegramBotBase.Controls.Hybrid
{ {
public class CheckedButtonList : Base.ControlBase public class CheckedButtonList : ControlBase
{ {
public String Title { get; set; } = Localizations.Default.Language["ButtonGrid_Title"]; public string Title { get; set; } = Default.Language["ButtonGrid_Title"];
public String ConfirmationText { get; set; } = ""; public string ConfirmationText { get; set; } = "";
private bool RenderNecessary = true; private bool _renderNecessary = true;
private static readonly object __evButtonClicked = new object(); private static readonly object EvButtonClicked = new object();
private static readonly object __evCheckedChanged = new object(); private static readonly object EvCheckedChanged = new object();
private readonly EventHandlerList Events = new EventHandlerList(); private readonly EventHandlerList _events = new EventHandlerList();
[Obsolete("This property is obsolete. Please use the DataSource property instead.")] [Obsolete("This property is obsolete. Please use the DataSource property instead.")]
public ButtonForm ButtonsForm public ButtonForm ButtonsForm
{ {
get get => DataSource.ButtonForm;
{ set => DataSource = new ButtonFormDataSource(value);
return DataSource.ButtonForm;
}
set
{
DataSource = new ButtonFormDataSource(value);
}
} }
/// <summary> /// <summary>
@ -51,7 +44,7 @@ namespace TelegramBotBase.Controls.Hybrid
/// </summary> /// </summary>
public ButtonFormDataSource DataSource { get; set; } public ButtonFormDataSource DataSource { get; set; }
List<int> CheckedRows { get; set; } = new List<int>(); private List<int> CheckedRows { get; set; } = new List<int>();
public int? MessageId { get; set; } public int? MessageId { get; set; }
@ -91,25 +84,25 @@ namespace TelegramBotBase.Controls.Hybrid
//public String SearchQuery { get; set; } //public String SearchQuery { get; set; }
public eNavigationBarVisibility NavigationBarVisibility { get; set; } = eNavigationBarVisibility.always; public ENavigationBarVisibility NavigationBarVisibility { get; set; } = ENavigationBarVisibility.always;
/// <summary> /// <summary>
/// Index of the current page /// Index of the current page
/// </summary> /// </summary>
public int CurrentPageIndex { get; set; } = 0; public int CurrentPageIndex { get; set; }
public String PreviousPageLabel = Localizations.Default.Language["ButtonGrid_PreviousPage"]; public string PreviousPageLabel = Default.Language["ButtonGrid_PreviousPage"];
public String NextPageLabel = Localizations.Default.Language["ButtonGrid_NextPage"]; public string NextPageLabel = Default.Language["ButtonGrid_NextPage"];
public String NoItemsLabel = Localizations.Default.Language["ButtonGrid_NoItems"]; public string NoItemsLabel = Default.Language["ButtonGrid_NoItems"];
//public String SearchLabel = Localizations.Default.Language["ButtonGrid_SearchFeature"]; //public String SearchLabel = Localizations.Default.Language["ButtonGrid_SearchFeature"];
public String CheckedIconLabel { get; set; } = "✅"; public string CheckedIconLabel { get; set; } = "✅";
public String UncheckedIconLabel { get; set; } = "◻️"; public string UncheckedIconLabel { get; set; } = "◻️";
/// <summary> /// <summary>
/// Layout of the buttons which should be displayed always on top. /// Layout of the buttons which should be displayed always on top.
@ -124,97 +117,82 @@ namespace TelegramBotBase.Controls.Hybrid
/// <summary> /// <summary>
/// Defines which type of Button Keyboard should be rendered. /// Defines which type of Button Keyboard should be rendered.
/// </summary> /// </summary>
public eKeyboardType KeyboardType public EKeyboardType KeyboardType
{ {
get get => _mEKeyboardType;
{
return m_eKeyboardType;
}
set set
{ {
if (m_eKeyboardType != value) if (_mEKeyboardType != value)
{ {
this.RenderNecessary = true; _renderNecessary = true;
Cleanup().Wait(); Cleanup().Wait();
m_eKeyboardType = value; _mEKeyboardType = value;
} }
} }
} }
private eKeyboardType m_eKeyboardType = eKeyboardType.ReplyKeyboard; private EKeyboardType _mEKeyboardType = EKeyboardType.ReplyKeyboard;
public CheckedButtonList() public CheckedButtonList()
{ {
this.DataSource = new ButtonFormDataSource(); DataSource = new ButtonFormDataSource();
} }
public CheckedButtonList(eKeyboardType type) : this() public CheckedButtonList(EKeyboardType type) : this()
{ {
m_eKeyboardType = type; _mEKeyboardType = type;
} }
public CheckedButtonList(ButtonForm form) public CheckedButtonList(ButtonForm form)
{ {
this.DataSource = new ButtonFormDataSource(form); DataSource = new ButtonFormDataSource(form);
} }
public event AsyncEventHandler<ButtonClickedEventArgs> ButtonClicked public event AsyncEventHandler<ButtonClickedEventArgs> ButtonClicked
{ {
add add => _events.AddHandler(EvButtonClicked, value);
{ remove => _events.RemoveHandler(EvButtonClicked, value);
this.Events.AddHandler(__evButtonClicked, value);
}
remove
{
this.Events.RemoveHandler(__evButtonClicked, value);
}
} }
public async Task OnButtonClicked(ButtonClickedEventArgs e) public async Task OnButtonClicked(ButtonClickedEventArgs e)
{ {
var handler = this.Events[__evButtonClicked]?.GetInvocationList().Cast<AsyncEventHandler<ButtonClickedEventArgs>>(); var handler = _events[EvButtonClicked]?.GetInvocationList().Cast<AsyncEventHandler<ButtonClickedEventArgs>>();
if (handler == null) if (handler == null)
return; return;
foreach (var h in handler) foreach (var h in handler)
{ {
await Async.InvokeAllAsync<ButtonClickedEventArgs>(h, this, e); await h.InvokeAllAsync(this, e);
} }
} }
public event AsyncEventHandler<CheckedChangedEventArgs> CheckedChanged public event AsyncEventHandler<CheckedChangedEventArgs> CheckedChanged
{ {
add add => _events.AddHandler(EvCheckedChanged, value);
{ remove => _events.RemoveHandler(EvCheckedChanged, value);
this.Events.AddHandler(__evCheckedChanged, value);
}
remove
{
this.Events.RemoveHandler(__evCheckedChanged, value);
}
} }
public async Task OnCheckedChanged(CheckedChangedEventArgs e) public async Task OnCheckedChanged(CheckedChangedEventArgs e)
{ {
var handler = this.Events[__evCheckedChanged]?.GetInvocationList().Cast<AsyncEventHandler<CheckedChangedEventArgs>>(); var handler = _events[EvCheckedChanged]?.GetInvocationList().Cast<AsyncEventHandler<CheckedChangedEventArgs>>();
if (handler == null) if (handler == null)
return; return;
foreach (var h in handler) foreach (var h in handler)
{ {
await Async.InvokeAllAsync<CheckedChangedEventArgs>(h, this, e); await h.InvokeAllAsync(this, e);
} }
} }
public async override Task Load(MessageResult result) public override async Task Load(MessageResult result)
{ {
if (this.KeyboardType != eKeyboardType.ReplyKeyboard) if (KeyboardType != EKeyboardType.ReplyKeyboard)
return; return;
if (!result.IsFirstHandler) if (!result.IsFirstHandler)
@ -225,7 +203,7 @@ namespace TelegramBotBase.Controls.Hybrid
var matches = new List<ButtonRow>(); var matches = new List<ButtonRow>();
ButtonRow match = null; ButtonRow match = null;
int index = -1; var index = -1;
if (HeadLayoutButtonRow?.Matches(result.MessageText) ?? false) if (HeadLayoutButtonRow?.Matches(result.MessageText) ?? false)
{ {
@ -260,36 +238,36 @@ namespace TelegramBotBase.Controls.Hybrid
//Remove button click message //Remove button click message
if (this.DeleteReplyMessage) if (DeleteReplyMessage)
await Device.DeleteMessage(result.MessageId); await Device.DeleteMessage(result.MessageId);
if (match == null) if (match == null)
{ {
if (result.MessageText == PreviousPageLabel) if (result.MessageText == PreviousPageLabel)
{ {
if (this.CurrentPageIndex > 0) if (CurrentPageIndex > 0)
this.CurrentPageIndex--; CurrentPageIndex--;
this.Updated(); Updated();
} }
else if (result.MessageText == NextPageLabel) else if (result.MessageText == NextPageLabel)
{ {
if (this.CurrentPageIndex < this.PageCount - 1) if (CurrentPageIndex < PageCount - 1)
this.CurrentPageIndex++; CurrentPageIndex++;
this.Updated(); Updated();
} }
else if (result.MessageText.EndsWith(CheckedIconLabel)) else if (result.MessageText.EndsWith(CheckedIconLabel))
{ {
var s = result.MessageText.Split(' ', '.'); var s = result.MessageText.Split(' ', '.');
index = int.Parse(s[0]) - 1; index = int.Parse(s[0]) - 1;
if (!this.CheckedRows.Contains(index)) if (!CheckedRows.Contains(index))
return; return;
this.CheckedRows.Remove(index); CheckedRows.Remove(index);
this.Updated(); Updated();
await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, false)); await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, false));
@ -299,13 +277,13 @@ namespace TelegramBotBase.Controls.Hybrid
var s = result.MessageText.Split(' ', '.'); var s = result.MessageText.Split(' ', '.');
index = int.Parse(s[0]) - 1; index = int.Parse(s[0]) - 1;
if (this.CheckedRows.Contains(index)) if (CheckedRows.Contains(index))
return; return;
this.CheckedRows.Add(index); CheckedRows.Add(index);
this.Updated(); Updated();
await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, true)); await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, true));
@ -355,7 +333,7 @@ namespace TelegramBotBase.Controls.Hybrid
} }
public async override Task Action(MessageResult result, string value = null) public override async Task Action(MessageResult result, string value = null)
{ {
if (result.Handled) if (result.Handled)
return; return;
@ -364,13 +342,13 @@ namespace TelegramBotBase.Controls.Hybrid
return; return;
//Find clicked button depending on Text or Value (depending on markup type) //Find clicked button depending on Text or Value (depending on markup type)
if (this.KeyboardType != eKeyboardType.InlineKeyBoard) if (KeyboardType != EKeyboardType.InlineKeyBoard)
return; return;
await result.ConfirmAction(this.ConfirmationText ?? ""); await result.ConfirmAction(ConfirmationText ?? "");
ButtonRow match = null; ButtonRow match = null;
int index = -1; var index = -1;
if (HeadLayoutButtonRow?.Matches(result.RawData, false) ?? false) if (HeadLayoutButtonRow?.Matches(result.RawData, false) ?? false)
{ {
@ -422,18 +400,18 @@ namespace TelegramBotBase.Controls.Hybrid
{ {
case "$previous$": case "$previous$":
if (this.CurrentPageIndex > 0) if (CurrentPageIndex > 0)
this.CurrentPageIndex--; CurrentPageIndex--;
this.Updated(); Updated();
break; break;
case "$next$": case "$next$":
if (this.CurrentPageIndex < this.PageCount - 1) if (CurrentPageIndex < PageCount - 1)
this.CurrentPageIndex++; CurrentPageIndex++;
this.Updated(); Updated();
break; break;
@ -448,11 +426,11 @@ namespace TelegramBotBase.Controls.Hybrid
index = int.Parse(s[1]); index = int.Parse(s[1]);
if (!this.CheckedRows.Contains(index)) if (!CheckedRows.Contains(index))
{ {
this.CheckedRows.Add(index); CheckedRows.Add(index);
this.Updated(); Updated();
await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, true)); await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, true));
} }
@ -463,11 +441,11 @@ namespace TelegramBotBase.Controls.Hybrid
index = int.Parse(s[1]); index = int.Parse(s[1]);
if (this.CheckedRows.Contains(index)) if (CheckedRows.Contains(index))
{ {
this.CheckedRows.Remove(index); CheckedRows.Remove(index);
this.Updated(); Updated();
await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, false)); await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, false));
} }
@ -487,51 +465,51 @@ namespace TelegramBotBase.Controls.Hybrid
/// </summary> /// </summary>
private void CheckGrid() private void CheckGrid()
{ {
switch (m_eKeyboardType) switch (_mEKeyboardType)
{ {
case eKeyboardType.InlineKeyBoard: case EKeyboardType.InlineKeyBoard:
if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !this.EnablePaging) if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !EnablePaging)
{ {
throw new MaximumRowsReachedException() { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows }; throw new MaximumRowsReachedException { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows };
} }
if (DataSource.ColumnCount > Constants.Telegram.MaxInlineKeyBoardCols) if (DataSource.ColumnCount > Constants.Telegram.MaxInlineKeyBoardCols)
{ {
throw new MaximumColsException() { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols }; throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols };
} }
break; break;
case eKeyboardType.ReplyKeyboard: case EKeyboardType.ReplyKeyboard:
if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !this.EnablePaging) if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !EnablePaging)
{ {
throw new MaximumRowsReachedException() { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows }; throw new MaximumRowsReachedException { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows };
} }
if (DataSource.ColumnCount > Constants.Telegram.MaxReplyKeyboardCols) if (DataSource.ColumnCount > Constants.Telegram.MaxReplyKeyboardCols)
{ {
throw new MaximumColsException() { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols }; throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols };
} }
break; break;
} }
} }
public async override Task Render(MessageResult result) public override async Task Render(MessageResult result)
{ {
if (!this.RenderNecessary) if (!_renderNecessary)
return; return;
//Check for rows and column limits //Check for rows and column limits
CheckGrid(); CheckGrid();
this.RenderNecessary = false; _renderNecessary = false;
Message m = null; Message m = null;
ButtonForm form = this.DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage, null); var form = DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage);
//if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "")
//{ //{
@ -542,7 +520,7 @@ namespace TelegramBotBase.Controls.Hybrid
//form = form.Duplicate(); //form = form.Duplicate();
//} //}
if (this.EnablePaging) if (EnablePaging)
{ {
IntegratePagingView(form); IntegratePagingView(form);
} }
@ -551,34 +529,34 @@ namespace TelegramBotBase.Controls.Hybrid
form = PrepareCheckableLayout(form); form = PrepareCheckableLayout(form);
} }
if (this.HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0)
{ {
form.InsertButtonRow(0, this.HeadLayoutButtonRow.ToArray()); form.InsertButtonRow(0, HeadLayoutButtonRow.ToArray());
} }
if (this.SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0)
{ {
if (this.IsNavigationBarVisible) if (IsNavigationBarVisible)
{ {
form.InsertButtonRow(2, this.SubHeadLayoutButtonRow.ToArray()); form.InsertButtonRow(2, SubHeadLayoutButtonRow.ToArray());
} }
else else
{ {
form.InsertButtonRow(1, this.SubHeadLayoutButtonRow.ToArray()); form.InsertButtonRow(1, SubHeadLayoutButtonRow.ToArray());
} }
} }
switch (this.KeyboardType) switch (KeyboardType)
{ {
//Reply Keyboard could only be updated with a new keyboard. //Reply Keyboard could only be updated with a new keyboard.
case eKeyboardType.ReplyKeyboard: case EKeyboardType.ReplyKeyboard:
if (form.Count == 0) if (form.Count == 0)
{ {
if (this.MessageId != null) if (MessageId != null)
{ {
await this.Device.HideReplyKeyboard(); await Device.HideReplyKeyboard();
this.MessageId = null; MessageId = null;
} }
return; return;
@ -589,25 +567,25 @@ namespace TelegramBotBase.Controls.Hybrid
var rkm = (ReplyKeyboardMarkup)form; var rkm = (ReplyKeyboardMarkup)form;
rkm.ResizeKeyboard = this.ResizeKeyboard; rkm.ResizeKeyboard = ResizeKeyboard;
rkm.OneTimeKeyboard = this.OneTimeKeyboard; rkm.OneTimeKeyboard = OneTimeKeyboard;
m = await this.Device.Send(this.Title, rkm, disableNotification: true, parseMode: MessageParseMode, MarkdownV2AutoEscape: false); m = await Device.Send(Title, rkm, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false);
//Prevent flicker of keyboard //Prevent flicker of keyboard
if (this.DeletePreviousMessage && this.MessageId != null) if (DeletePreviousMessage && MessageId != null)
await this.Device.DeleteMessage(this.MessageId.Value); await Device.DeleteMessage(MessageId.Value);
break; break;
case eKeyboardType.InlineKeyBoard: case EKeyboardType.InlineKeyBoard:
if (this.MessageId != null) if (MessageId != null)
{ {
m = await this.Device.Edit(this.MessageId.Value, this.Title, (InlineKeyboardMarkup)form); m = await Device.Edit(MessageId.Value, Title, (InlineKeyboardMarkup)form);
} }
else else
{ {
m = await this.Device.Send(this.Title, (InlineKeyboardMarkup)form, disableNotification: true, parseMode: MessageParseMode, MarkdownV2AutoEscape: false); m = await Device.Send(Title, (InlineKeyboardMarkup)form, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false);
} }
break; break;
@ -615,7 +593,7 @@ namespace TelegramBotBase.Controls.Hybrid
if (m != null) if (m != null)
{ {
this.MessageId = m.MessageId; MessageId = m.MessageId;
} }
@ -623,23 +601,23 @@ namespace TelegramBotBase.Controls.Hybrid
private void IntegratePagingView(ButtonForm dataForm) private void IntegratePagingView(ButtonForm dataForm)
{ {
//No Items //No Items
if (dataForm.Rows == 0) if (dataForm.Rows == 0)
{ {
dataForm.AddButtonRow(new ButtonBase(NoItemsLabel, "$")); dataForm.AddButtonRow(new ButtonBase(NoItemsLabel, "$"));
} }
ButtonForm bf = new ButtonForm(); var bf = new ButtonForm();
bf = PrepareCheckableLayout(dataForm); bf = PrepareCheckableLayout(dataForm);
if (this.IsNavigationBarVisible) if (IsNavigationBarVisible)
{ {
//🔍 //🔍
ButtonRow row = new ButtonRow(); var row = new ButtonRow();
row.Add(new ButtonBase(PreviousPageLabel, "$previous$")); row.Add(new ButtonBase(PreviousPageLabel, "$previous$"));
row.Add(new ButtonBase(String.Format(Localizations.Default.Language["ButtonGrid_CurrentPage"], this.CurrentPageIndex + 1, this.PageCount), "$site$")); row.Add(new ButtonBase(string.Format(Default.Language["ButtonGrid_CurrentPage"], CurrentPageIndex + 1, PageCount), "$site$"));
row.Add(new ButtonBase(NextPageLabel, "$next$")); row.Add(new ButtonBase(NextPageLabel, "$next$"));
@ -652,30 +630,30 @@ namespace TelegramBotBase.Controls.Hybrid
private ButtonForm PrepareCheckableLayout(ButtonForm dataForm) private ButtonForm PrepareCheckableLayout(ButtonForm dataForm)
{ {
var bf = new ButtonForm(); var bf = new ButtonForm();
for (int i = 0; i < dataForm.Rows; i++) for (var i = 0; i < dataForm.Rows; i++)
{ {
int it = (this.CurrentPageIndex * (this.MaximumRow - LayoutRows)) + i; var it = (CurrentPageIndex * (MaximumRow - LayoutRows)) + i;
//if (it > dataForm.Rows - 1) //if (it > dataForm.Rows - 1)
// break; // break;
var r = dataForm[i]; var r = dataForm[i];
String s = CheckedRows.Contains(it) ? this.CheckedIconLabel : this.UncheckedIconLabel; var s = CheckedRows.Contains(it) ? CheckedIconLabel : UncheckedIconLabel;
//On reply keyboards we need a unique text. //On reply keyboards we need a unique text.
if (this.KeyboardType == eKeyboardType.ReplyKeyboard) if (KeyboardType == EKeyboardType.ReplyKeyboard)
{ {
s = $"{it + 1}. " + s; s = $"{it + 1}. " + s;
} }
if (CheckedRows.Contains(it)) if (CheckedRows.Contains(it))
{ {
r.Insert(0, new ButtonBase(s, "uncheck$" + it.ToString())); r.Insert(0, new ButtonBase(s, "uncheck$" + it));
} }
else else
{ {
r.Insert(0, new ButtonBase(s, "check$" + it.ToString())); r.Insert(0, new ButtonBase(s, "check$" + it));
} }
bf.AddButtonRow(r); bf.AddButtonRow(r);
@ -688,12 +666,12 @@ namespace TelegramBotBase.Controls.Hybrid
{ {
get get
{ {
if (this.KeyboardType == eKeyboardType.InlineKeyBoard && TotalRows > Constants.Telegram.MaxInlineKeyBoardRows) if (KeyboardType == EKeyboardType.InlineKeyBoard && TotalRows > Constants.Telegram.MaxInlineKeyBoardRows)
{ {
return true; return true;
} }
if (this.KeyboardType == eKeyboardType.ReplyKeyboard && TotalRows > Constants.Telegram.MaxReplyKeyboardRows) if (KeyboardType == EKeyboardType.ReplyKeyboard && TotalRows > Constants.Telegram.MaxReplyKeyboardRows)
{ {
return true; return true;
} }
@ -706,7 +684,7 @@ namespace TelegramBotBase.Controls.Hybrid
{ {
get get
{ {
if (this.NavigationBarVisibility == eNavigationBarVisibility.always | (this.NavigationBarVisibility == eNavigationBarVisibility.auto && PagingNecessary)) if (NavigationBarVisibility == ENavigationBarVisibility.always | (NavigationBarVisibility == ENavigationBarVisibility.auto && PagingNecessary))
{ {
return true; return true;
} }
@ -722,30 +700,19 @@ namespace TelegramBotBase.Controls.Hybrid
{ {
get get
{ {
switch (this.KeyboardType) return KeyboardType switch
{ {
case eKeyboardType.InlineKeyBoard: EKeyboardType.InlineKeyBoard => Constants.Telegram.MaxInlineKeyBoardRows,
return Constants.Telegram.MaxInlineKeyBoardRows; EKeyboardType.ReplyKeyboard => Constants.Telegram.MaxReplyKeyboardRows,
_ => 0
case eKeyboardType.ReplyKeyboard: };
return Constants.Telegram.MaxReplyKeyboardRows;
default:
return 0;
}
} }
} }
/// <summary> /// <summary>
/// Returns the number of all rows (layout + navigation + content); /// Returns the number of all rows (layout + navigation + content);
/// </summary> /// </summary>
public int TotalRows public int TotalRows => LayoutRows + DataSource.RowCount;
{
get
{
return this.LayoutRows + DataSource.RowCount;
}
}
/// <summary> /// <summary>
@ -755,15 +722,15 @@ namespace TelegramBotBase.Controls.Hybrid
{ {
get get
{ {
int layoutRows = 0; var layoutRows = 0;
if (this.NavigationBarVisibility == eNavigationBarVisibility.always | this.NavigationBarVisibility == eNavigationBarVisibility.auto) if (NavigationBarVisibility == ENavigationBarVisibility.always | NavigationBarVisibility == ENavigationBarVisibility.auto)
layoutRows += 2; layoutRows += 2;
if (this.HeadLayoutButtonRow != null && this.HeadLayoutButtonRow.Count > 0) if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0)
layoutRows++; layoutRows++;
if (this.SubHeadLayoutButtonRow != null && this.SubHeadLayoutButtonRow.Count > 0) if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0)
layoutRows++; layoutRows++;
return layoutRows; return layoutRows;
@ -773,13 +740,7 @@ namespace TelegramBotBase.Controls.Hybrid
/// <summary> /// <summary>
/// Returns the number of item rows per page. /// Returns the number of item rows per page.
/// </summary> /// </summary>
public int ItemRowsPerPage public int ItemRowsPerPage => MaximumRow - LayoutRows;
{
get
{
return this.MaximumRow - this.LayoutRows;
}
}
public int PageCount public int PageCount
{ {
@ -790,7 +751,7 @@ namespace TelegramBotBase.Controls.Hybrid
//var bf = this.DataSource.PickAllItems(this.EnableSearch ? this.SearchQuery : null); //var bf = this.DataSource.PickAllItems(this.EnableSearch ? this.SearchQuery : null);
var max = this.DataSource.RowCount; var max = DataSource.RowCount;
//if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "")
//{ //{
@ -800,28 +761,30 @@ namespace TelegramBotBase.Controls.Hybrid
if (max == 0) if (max == 0)
return 1; return 1;
return (int)Math.Ceiling((decimal)((decimal)max / (decimal)ItemRowsPerPage)); return (int)Math.Ceiling(max / (decimal)ItemRowsPerPage);
} }
} }
public override async Task Hidden(bool FormClose) public override Task Hidden(bool formClose)
{ {
//Prepare for opening Modal, and comming back //Prepare for opening Modal, and comming back
if (!FormClose) if (!formClose)
{ {
this.Updated(); Updated();
} }
return Task.CompletedTask;
} }
public List<ButtonBase> CheckedItems public List<ButtonBase> CheckedItems
{ {
get get
{ {
List<ButtonBase> lst = new List<ButtonBase>(); var lst = new List<ButtonBase>();
foreach (var c in CheckedRows) foreach (var c in CheckedRows)
{ {
lst.Add(this.ButtonsForm[c][0]); lst.Add(ButtonsForm[c][0]);
} }
return lst; return lst;
@ -834,31 +797,31 @@ namespace TelegramBotBase.Controls.Hybrid
/// </summary> /// </summary>
public void Updated() public void Updated()
{ {
this.RenderNecessary = true; _renderNecessary = true;
} }
public async override Task Cleanup() public override async Task Cleanup()
{ {
if (this.MessageId == null) if (MessageId == null)
return; return;
switch (this.KeyboardType) switch (KeyboardType)
{ {
case eKeyboardType.InlineKeyBoard: case EKeyboardType.InlineKeyBoard:
await this.Device.DeleteMessage(this.MessageId.Value); await Device.DeleteMessage(MessageId.Value);
this.MessageId = null; MessageId = null;
break; break;
case eKeyboardType.ReplyKeyboard: case EKeyboardType.ReplyKeyboard:
if (this.HideKeyboardOnCleanup) if (HideKeyboardOnCleanup)
{ {
await this.Device.HideReplyKeyboard(); await Device.HideReplyKeyboard();
} }
this.MessageId = null; MessageId = null;
break; break;
} }

View File

@ -1,8 +1,4 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using TelegramBotBase.Args; using TelegramBotBase.Args;
using TelegramBotBase.Base; using TelegramBotBase.Base;
@ -13,33 +9,30 @@ namespace TelegramBotBase.Controls.Hybrid
/// <summary> /// <summary>
/// This Control is for having a basic form content switching control. /// This Control is for having a basic form content switching control.
/// </summary> /// </summary>
public abstract class MultiView : Base.ControlBase public abstract class MultiView : ControlBase
{ {
/// <summary> /// <summary>
/// Index of the current View. /// Index of the current View.
/// </summary> /// </summary>
public int SelectedViewIndex public int SelectedViewIndex
{ {
get get => _mISelectedViewIndex;
{
return m_iSelectedViewIndex;
}
set set
{ {
m_iSelectedViewIndex = value; _mISelectedViewIndex = value;
//Already rendered? Re-Render //Already rendered? Re-Render
if (_Rendered) if (_rendered)
ForceRender().Wait(); ForceRender().Wait();
} }
} }
private int m_iSelectedViewIndex = 0; private int _mISelectedViewIndex;
/// <summary> /// <summary>
/// Hold if the View has been rendered already. /// Hold if the View has been rendered already.
/// </summary> /// </summary>
private bool _Rendered = false; private bool _rendered;
private List<int> Messages { get; set; } private List<int> Messages { get; set; }
@ -50,12 +43,13 @@ namespace TelegramBotBase.Controls.Hybrid
} }
private async Task Device_MessageSent(object sender, MessageSentEventArgs e) private Task Device_MessageSent(object sender, MessageSentEventArgs e)
{ {
if (e.Origin == null || !e.Origin.IsSubclassOf(typeof(MultiView))) if (e.Origin == null || !e.Origin.IsSubclassOf(typeof(MultiView)))
return; return Task.CompletedTask;
this.Messages.Add(e.MessageId); Messages.Add(e.MessageId);
return Task.CompletedTask;
} }
public override void Init() public override void Init()
@ -63,23 +57,24 @@ namespace TelegramBotBase.Controls.Hybrid
Device.MessageSent += Device_MessageSent; Device.MessageSent += Device_MessageSent;
} }
public override async Task Load(MessageResult result) public override Task Load(MessageResult result)
{ {
_Rendered = false; _rendered = false;
return Task.CompletedTask;
} }
public override async Task Render(MessageResult result) public override async Task Render(MessageResult result)
{ {
//When already rendered, skip rendering //When already rendered, skip rendering
if (_Rendered) if (_rendered)
return; return;
await CleanUpView(); await CleanUpView();
await RenderView(new RenderViewEventArgs(this.SelectedViewIndex)); await RenderView(new RenderViewEventArgs(SelectedViewIndex));
_Rendered = true; _rendered = true;
} }
@ -87,25 +82,24 @@ namespace TelegramBotBase.Controls.Hybrid
/// Will get invoked on rendering the current controls view. /// Will get invoked on rendering the current controls view.
/// </summary> /// </summary>
/// <param name="e"></param> /// <param name="e"></param>
public virtual async Task RenderView(RenderViewEventArgs e) public virtual Task RenderView(RenderViewEventArgs e)
{ {
return Task.CompletedTask;
} }
async Task CleanUpView() private async Task CleanUpView()
{ {
var tasks = new List<Task>(); var tasks = new List<Task>();
foreach (var msg in this.Messages) foreach (var msg in Messages)
{ {
tasks.Add(this.Device.DeleteMessage(msg)); tasks.Add(Device.DeleteMessage(msg));
} }
await Task.WhenAll(tasks); await Task.WhenAll(tasks);
this.Messages.Clear(); Messages.Clear();
} }
@ -116,9 +110,9 @@ namespace TelegramBotBase.Controls.Hybrid
{ {
await CleanUpView(); await CleanUpView();
await RenderView(new RenderViewEventArgs(this.SelectedViewIndex)); await RenderView(new RenderViewEventArgs(SelectedViewIndex));
_Rendered = true; _rendered = true;
} }
public override async Task Cleanup() public override async Task Cleanup()

View File

@ -1,20 +1,18 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Diagnostics.SymbolStore;
using System.Linq; using System.Linq;
using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Telegram.Bot.Types; using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types.InlineQueryResults;
using Telegram.Bot.Types.ReplyMarkups; using Telegram.Bot.Types.ReplyMarkups;
using TelegramBotBase.Args; using TelegramBotBase.Args;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Datasources; using TelegramBotBase.DataSources;
using TelegramBotBase.Enums; using TelegramBotBase.Enums;
using TelegramBotBase.Exceptions; using TelegramBotBase.Exceptions;
using TelegramBotBase.Form; using TelegramBotBase.Form;
using TelegramBotBase.Localizations;
using static TelegramBotBase.Base.Async; using static TelegramBotBase.Base.Async;
namespace TelegramBotBase.Controls.Hybrid namespace TelegramBotBase.Controls.Hybrid
@ -22,27 +20,21 @@ namespace TelegramBotBase.Controls.Hybrid
public class TaggedButtonGrid : MultiView public class TaggedButtonGrid : MultiView
{ {
public String Title { get; set; } = Localizations.Default.Language["ButtonGrid_Title"]; public string Title { get; set; } = Default.Language["ButtonGrid_Title"];
public String ConfirmationText { get; set; } public string ConfirmationText { get; set; }
private bool RenderNecessary = true; private bool _renderNecessary = true;
private static readonly object __evButtonClicked = new object(); private static readonly object EvButtonClicked = new object();
private readonly EventHandlerList Events = new EventHandlerList(); private readonly EventHandlerList _events = new EventHandlerList();
[Obsolete("This property is obsolete. Please use the DataSource property instead.")] [Obsolete("This property is obsolete. Please use the DataSource property instead.")]
public ButtonForm ButtonsForm public ButtonForm ButtonsForm
{ {
get get => DataSource.ButtonForm;
{ set => DataSource = new ButtonFormDataSource(value);
return DataSource.ButtonForm;
}
set
{
DataSource = new ButtonFormDataSource(value);
}
} }
/// <summary> /// <summary>
@ -90,29 +82,29 @@ namespace TelegramBotBase.Controls.Hybrid
/// </summary> /// </summary>
public bool EnableSearch { get; set; } = false; public bool EnableSearch { get; set; } = false;
public String SearchQuery { get; set; } public string SearchQuery { get; set; }
public eNavigationBarVisibility NavigationBarVisibility { get; set; } = eNavigationBarVisibility.always; public ENavigationBarVisibility NavigationBarVisibility { get; set; } = ENavigationBarVisibility.always;
/// <summary> /// <summary>
/// Index of the current page /// Index of the current page
/// </summary> /// </summary>
public int CurrentPageIndex { get; set; } = 0; public int CurrentPageIndex { get; set; }
public String PreviousPageLabel = Localizations.Default.Language["ButtonGrid_PreviousPage"]; public string PreviousPageLabel = Default.Language["ButtonGrid_PreviousPage"];
public String NextPageLabel = Localizations.Default.Language["ButtonGrid_NextPage"]; public string NextPageLabel = Default.Language["ButtonGrid_NextPage"];
public String NoItemsLabel = Localizations.Default.Language["ButtonGrid_NoItems"]; public string NoItemsLabel = Default.Language["ButtonGrid_NoItems"];
public String SearchLabel = Localizations.Default.Language["ButtonGrid_SearchFeature"]; public string SearchLabel = Default.Language["ButtonGrid_SearchFeature"];
public String BackLabel = Localizations.Default.Language["ButtonGrid_Back"]; public string BackLabel = Default.Language["ButtonGrid_Back"];
public String CheckAllLabel = Localizations.Default.Language["ButtonGrid_CheckAll"]; public string CheckAllLabel = Default.Language["ButtonGrid_CheckAll"];
public String UncheckAllLabel = Localizations.Default.Language["ButtonGrid_UncheckAll"]; public string UncheckAllLabel = Default.Language["ButtonGrid_UncheckAll"];
/// <summary> /// <summary>
/// Layout of the buttons which should be displayed always on top. /// Layout of the buttons which should be displayed always on top.
@ -132,100 +124,91 @@ namespace TelegramBotBase.Controls.Hybrid
/// <summary> /// <summary>
/// List of Tags which will be allowed to filter by. /// List of Tags which will be allowed to filter by.
/// </summary> /// </summary>
public List<String> Tags { get; set; } public List<string> Tags { get; set; }
/// <summary> /// <summary>
/// List of Tags selected by the User. /// List of Tags selected by the User.
/// </summary> /// </summary>
public List<String> SelectedTags { get; set; } public List<string> SelectedTags { get; set; }
/// <summary> /// <summary>
/// Defines which type of Button Keyboard should be rendered. /// Defines which type of Button Keyboard should be rendered.
/// </summary> /// </summary>
public eKeyboardType KeyboardType public EKeyboardType KeyboardType
{ {
get get => _mEKeyboardType;
{
return m_eKeyboardType;
}
set set
{ {
if (m_eKeyboardType != value) if (_mEKeyboardType != value)
{ {
this.RenderNecessary = true; _renderNecessary = true;
Cleanup().Wait(); Cleanup().Wait();
m_eKeyboardType = value; _mEKeyboardType = value;
} }
} }
} }
private eKeyboardType m_eKeyboardType = eKeyboardType.ReplyKeyboard; private EKeyboardType _mEKeyboardType = EKeyboardType.ReplyKeyboard;
public TaggedButtonGrid() public TaggedButtonGrid()
{ {
this.DataSource = new ButtonFormDataSource(); DataSource = new ButtonFormDataSource();
this.SelectedViewIndex = 0; SelectedViewIndex = 0;
} }
public TaggedButtonGrid(eKeyboardType type) : this() public TaggedButtonGrid(EKeyboardType type) : this()
{ {
m_eKeyboardType = type; _mEKeyboardType = type;
} }
public TaggedButtonGrid(ButtonForm form) public TaggedButtonGrid(ButtonForm form)
{ {
this.DataSource = new ButtonFormDataSource(form); DataSource = new ButtonFormDataSource(form);
} }
public event AsyncEventHandler<ButtonClickedEventArgs> ButtonClicked public event AsyncEventHandler<ButtonClickedEventArgs> ButtonClicked
{ {
add add => _events.AddHandler(EvButtonClicked, value);
{ remove => _events.RemoveHandler(EvButtonClicked, value);
this.Events.AddHandler(__evButtonClicked, value);
}
remove
{
this.Events.RemoveHandler(__evButtonClicked, value);
}
} }
public async Task OnButtonClicked(ButtonClickedEventArgs e) public async Task OnButtonClicked(ButtonClickedEventArgs e)
{ {
var handler = this.Events[__evButtonClicked]?.GetInvocationList().Cast<AsyncEventHandler<ButtonClickedEventArgs>>(); var handler = _events[EvButtonClicked]?.GetInvocationList().Cast<AsyncEventHandler<ButtonClickedEventArgs>>();
if (handler == null) if (handler == null)
return; return;
foreach (var h in handler) foreach (var h in handler)
{ {
await Async.InvokeAllAsync<ButtonClickedEventArgs>(h, this, e); await h.InvokeAllAsync(this, e);
} }
} }
public override void Init() public override void Init()
{ {
this.Device.MessageDeleted += Device_MessageDeleted; Device.MessageDeleted += Device_MessageDeleted;
} }
private void Device_MessageDeleted(object sender, MessageDeletedEventArgs e) private void Device_MessageDeleted(object sender, MessageDeletedEventArgs e)
{ {
if (this.MessageId == null) if (MessageId == null)
return; return;
if (e.MessageId != this.MessageId) if (e.MessageId != MessageId)
return; return;
this.MessageId = null; MessageId = null;
} }
public async override Task Load(MessageResult result) public override async Task Load(MessageResult result)
{ {
if (this.KeyboardType != eKeyboardType.ReplyKeyboard) if (KeyboardType != EKeyboardType.ReplyKeyboard)
return; return;
if (!result.IsFirstHandler) if (!result.IsFirstHandler)
@ -236,7 +219,7 @@ namespace TelegramBotBase.Controls.Hybrid
var matches = new List<ButtonRow>(); var matches = new List<ButtonRow>();
ButtonRow match = null; ButtonRow match = null;
int index = -1; var index = -1;
if (HeadLayoutButtonRow?.Matches(result.MessageText) ?? false) if (HeadLayoutButtonRow?.Matches(result.MessageText) ?? false)
{ {
@ -275,12 +258,12 @@ namespace TelegramBotBase.Controls.Hybrid
switch (this.SelectedViewIndex) switch (SelectedViewIndex)
{ {
case 0: case 0:
//Remove button click message //Remove button click message
if (this.DeleteReplyMessage) if (DeleteReplyMessage)
await Device.DeleteMessage(result.MessageId); await Device.DeleteMessage(result.MessageId);
if (match != null) if (match != null)
@ -293,59 +276,57 @@ namespace TelegramBotBase.Controls.Hybrid
if (result.MessageText == PreviousPageLabel) if (result.MessageText == PreviousPageLabel)
{ {
if (this.CurrentPageIndex > 0) if (CurrentPageIndex > 0)
this.CurrentPageIndex--; CurrentPageIndex--;
this.Updated(); Updated();
result.Handled = true; result.Handled = true;
} }
else if (result.MessageText == NextPageLabel) else if (result.MessageText == NextPageLabel)
{ {
if (this.CurrentPageIndex < this.PageCount - 1) if (CurrentPageIndex < PageCount - 1)
this.CurrentPageIndex++; CurrentPageIndex++;
this.Updated(); Updated();
result.Handled = true; result.Handled = true;
} }
else if (this.EnableSearch) else if (EnableSearch)
{ {
if (result.MessageText.StartsWith("🔍")) if (result.MessageText.StartsWith("🔍"))
{ {
//Sent note about searching //Sent note about searching
if (this.SearchQuery == null) if (SearchQuery == null)
{ {
await this.Device.Send(this.SearchLabel); await Device.Send(SearchLabel);
} }
this.SearchQuery = null; SearchQuery = null;
this.Updated(); Updated();
result.Handled = true; result.Handled = true;
return; return;
} }
this.SearchQuery = result.MessageText; SearchQuery = result.MessageText;
if (this.SearchQuery != null && this.SearchQuery != "") if (SearchQuery != null && SearchQuery != "")
{ {
this.CurrentPageIndex = 0; CurrentPageIndex = 0;
this.Updated(); Updated();
result.Handled = true; result.Handled = true;
return;
} }
} }
else if (this.Tags != null) else if (Tags != null)
{ {
if (result.MessageText == "📁") if (result.MessageText == "📁")
{ {
//Remove button click message //Remove button click message
if (this.DeletePreviousMessage) if (DeletePreviousMessage)
await Device.DeleteMessage(result.MessageId); await Device.DeleteMessage(result.MessageId);
this.SelectedViewIndex = 1; SelectedViewIndex = 1;
this.Updated(); Updated();
result.Handled = true; result.Handled = true;
return;
} }
} }
@ -353,23 +334,24 @@ namespace TelegramBotBase.Controls.Hybrid
case 1: case 1:
//Remove button click message //Remove button click message
if (this.DeleteReplyMessage) if (DeleteReplyMessage)
await Device.DeleteMessage(result.MessageId); await Device.DeleteMessage(result.MessageId);
if (result.MessageText == this.BackLabel) if (result.MessageText == BackLabel)
{ {
this.SelectedViewIndex = 0; SelectedViewIndex = 0;
this.Updated(); Updated();
result.Handled = true; result.Handled = true;
return; return;
} }
else if (result.MessageText == this.CheckAllLabel)
if (result.MessageText == CheckAllLabel)
{ {
this.CheckAllTags(); CheckAllTags();
} }
else if (result.MessageText == this.UncheckAllLabel) else if (result.MessageText == UncheckAllLabel)
{ {
this.UncheckAllTags(); UncheckAllTags();
} }
var i = result.MessageText.LastIndexOf(" "); var i = result.MessageText.LastIndexOf(" ");
@ -378,16 +360,16 @@ namespace TelegramBotBase.Controls.Hybrid
var t = result.MessageText.Substring(0, i); var t = result.MessageText.Substring(0, i);
if (this.SelectedTags.Contains(t)) if (SelectedTags.Contains(t))
{ {
this.SelectedTags.Remove(t); SelectedTags.Remove(t);
} }
else else
{ {
this.SelectedTags.Add(t); SelectedTags.Add(t);
} }
this.Updated(); Updated();
result.Handled = true; result.Handled = true;
@ -399,7 +381,7 @@ namespace TelegramBotBase.Controls.Hybrid
} }
public async override Task Action(MessageResult result, string value = null) public override async Task Action(MessageResult result, string value = null)
{ {
if (result.Handled) if (result.Handled)
return; return;
@ -408,13 +390,13 @@ namespace TelegramBotBase.Controls.Hybrid
return; return;
//Find clicked button depending on Text or Value (depending on markup type) //Find clicked button depending on Text or Value (depending on markup type)
if (this.KeyboardType != eKeyboardType.InlineKeyBoard) if (KeyboardType != EKeyboardType.InlineKeyBoard)
return; return;
await result.ConfirmAction(this.ConfirmationText ?? ""); await result.ConfirmAction(ConfirmationText ?? "");
ButtonRow match = null; ButtonRow match = null;
int index = -1; var index = -1;
if (HeadLayoutButtonRow?.Matches(result.RawData, false) ?? false) if (HeadLayoutButtonRow?.Matches(result.RawData, false) ?? false)
{ {
@ -464,45 +446,45 @@ namespace TelegramBotBase.Controls.Hybrid
{ {
case "$previous$": case "$previous$":
if (this.CurrentPageIndex > 0) if (CurrentPageIndex > 0)
this.CurrentPageIndex--; CurrentPageIndex--;
this.Updated(); Updated();
break; break;
case "$next$": case "$next$":
if (this.CurrentPageIndex < this.PageCount - 1) if (CurrentPageIndex < PageCount - 1)
this.CurrentPageIndex++; CurrentPageIndex++;
this.Updated(); Updated();
break; break;
case "$filter$": case "$filter$":
this.SelectedViewIndex = 1; SelectedViewIndex = 1;
this.Updated(); Updated();
break; break;
case "$back$": case "$back$":
this.SelectedViewIndex = 0; SelectedViewIndex = 0;
this.Updated(); Updated();
break; break;
case "$checkall$": case "$checkall$":
this.CheckAllTags(); CheckAllTags();
break; break;
case "$uncheckall$": case "$uncheckall$":
this.UncheckAllTags(); UncheckAllTags();
break; break;
} }
@ -514,49 +496,49 @@ namespace TelegramBotBase.Controls.Hybrid
/// </summary> /// </summary>
private void CheckGrid() private void CheckGrid()
{ {
switch (m_eKeyboardType) switch (_mEKeyboardType)
{ {
case eKeyboardType.InlineKeyBoard: case EKeyboardType.InlineKeyBoard:
if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !this.EnablePaging) if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !EnablePaging)
{ {
throw new MaximumRowsReachedException() { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows }; throw new MaximumRowsReachedException { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows };
} }
if (DataSource.ColumnCount > Constants.Telegram.MaxInlineKeyBoardCols) if (DataSource.ColumnCount > Constants.Telegram.MaxInlineKeyBoardCols)
{ {
throw new MaximumColsException() { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols }; throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols };
} }
break; break;
case eKeyboardType.ReplyKeyboard: case EKeyboardType.ReplyKeyboard:
if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !this.EnablePaging) if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !EnablePaging)
{ {
throw new MaximumRowsReachedException() { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows }; throw new MaximumRowsReachedException { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows };
} }
if (DataSource.ColumnCount > Constants.Telegram.MaxReplyKeyboardCols) if (DataSource.ColumnCount > Constants.Telegram.MaxReplyKeyboardCols)
{ {
throw new MaximumColsException() { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols }; throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols };
} }
break; break;
} }
} }
public async override Task Render(MessageResult result) public override async Task Render(MessageResult result)
{ {
if (!this.RenderNecessary) if (!_renderNecessary)
return; return;
//Check for rows and column limits //Check for rows and column limits
CheckGrid(); CheckGrid();
this.RenderNecessary = false; _renderNecessary = false;
switch (this.SelectedViewIndex) switch (SelectedViewIndex)
{ {
case 0: case 0:
@ -586,7 +568,7 @@ namespace TelegramBotBase.Controls.Hybrid
{ {
Message m = null; Message m = null;
ButtonForm form = this.DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage, (this.EnableSearch ? this.SearchQuery : null)); var form = DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage, (EnableSearch ? SearchQuery : null));
//if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "")
//{ //{
@ -597,111 +579,111 @@ namespace TelegramBotBase.Controls.Hybrid
// form = form.Duplicate(); // form = form.Duplicate();
//} //}
if (this.Tags != null && this.SelectedTags != null) if (Tags != null && SelectedTags != null)
{ {
form = form.TagDuplicate(this.SelectedTags); form = form.TagDuplicate(SelectedTags);
} }
if (this.EnablePaging) if (EnablePaging)
{ {
IntegratePagingView(form); IntegratePagingView(form);
} }
if (this.HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0)
{ {
form.InsertButtonRow(0, this.HeadLayoutButtonRow.ToArray()); form.InsertButtonRow(0, HeadLayoutButtonRow.ToArray());
} }
if (this.SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0)
{ {
if (this.IsNavigationBarVisible) if (IsNavigationBarVisible)
{ {
form.InsertButtonRow(2, this.SubHeadLayoutButtonRow.ToArray()); form.InsertButtonRow(2, SubHeadLayoutButtonRow.ToArray());
} }
else else
{ {
form.InsertButtonRow(1, this.SubHeadLayoutButtonRow.ToArray()); form.InsertButtonRow(1, SubHeadLayoutButtonRow.ToArray());
} }
} }
switch (this.KeyboardType) switch (KeyboardType)
{ {
//Reply Keyboard could only be updated with a new keyboard. //Reply Keyboard could only be updated with a new keyboard.
case eKeyboardType.ReplyKeyboard: case EKeyboardType.ReplyKeyboard:
if (form.Count == 0) if (form.Count == 0)
{ {
if (this.MessageId != null) if (MessageId != null)
{ {
await this.Device.HideReplyKeyboard(); await Device.HideReplyKeyboard();
this.MessageId = null; MessageId = null;
} }
return; return;
} }
var rkm = (ReplyKeyboardMarkup)form; var rkm = (ReplyKeyboardMarkup)form;
rkm.ResizeKeyboard = this.ResizeKeyboard; rkm.ResizeKeyboard = ResizeKeyboard;
rkm.OneTimeKeyboard = this.OneTimeKeyboard; rkm.OneTimeKeyboard = OneTimeKeyboard;
m = await this.Device.Send(this.Title, rkm, disableNotification: true, parseMode: MessageParseMode, MarkdownV2AutoEscape: false); m = await Device.Send(Title, rkm, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false);
//Prevent flicker of keyboard //Prevent flicker of keyboard
if (this.DeletePreviousMessage && this.MessageId != null) if (DeletePreviousMessage && MessageId != null)
await this.Device.DeleteMessage(this.MessageId.Value); await Device.DeleteMessage(MessageId.Value);
break; break;
case eKeyboardType.InlineKeyBoard: case EKeyboardType.InlineKeyBoard:
//Try to edit message if message id is available //Try to edit message if message id is available
//When the returned message is null then the message has been already deleted, resend it //When the returned message is null then the message has been already deleted, resend it
if (this.MessageId != null) if (MessageId != null)
{ {
m = await this.Device.Edit(this.MessageId.Value, this.Title, (InlineKeyboardMarkup)form); m = await Device.Edit(MessageId.Value, Title, (InlineKeyboardMarkup)form);
if (m != null) if (m != null)
{ {
this.MessageId = m.MessageId; MessageId = m.MessageId;
return; return;
} }
} }
//When no message id is available or it has been deleted due the use of AutoCleanForm re-render automatically //When no message id is available or it has been deleted due the use of AutoCleanForm re-render automatically
m = await this.Device.Send(this.Title, (InlineKeyboardMarkup)form, disableNotification: true, parseMode: MessageParseMode, MarkdownV2AutoEscape: false); m = await Device.Send(Title, (InlineKeyboardMarkup)form, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false);
break; break;
} }
if (m != null) if (m != null)
{ {
this.MessageId = m.MessageId; MessageId = m.MessageId;
} }
} }
private void IntegratePagingView(ButtonForm dataForm) private void IntegratePagingView(ButtonForm dataForm)
{ {
//No Items //No Items
if (dataForm.Rows == 0) if (dataForm.Rows == 0)
{ {
dataForm.AddButtonRow(new ButtonBase(NoItemsLabel, "$")); dataForm.AddButtonRow(new ButtonBase(NoItemsLabel, "$"));
} }
if (this.IsNavigationBarVisible) if (IsNavigationBarVisible)
{ {
//🔍 //🔍
ButtonRow row = new ButtonRow(); var row = new ButtonRow();
row.Add(new ButtonBase(PreviousPageLabel, "$previous$")); row.Add(new ButtonBase(PreviousPageLabel, "$previous$"));
row.Add(new ButtonBase(String.Format(Localizations.Default.Language["ButtonGrid_CurrentPage"], this.CurrentPageIndex + 1, this.PageCount), "$site$")); row.Add(new ButtonBase(string.Format(Default.Language["ButtonGrid_CurrentPage"], CurrentPageIndex + 1, PageCount), "$site$"));
if (this.Tags != null && this.Tags.Count > 0) if (Tags != null && Tags.Count > 0)
{ {
row.Add(new ButtonBase("📁", "$filter$")); row.Add(new ButtonBase("📁", "$filter$"));
} }
row.Add(new ButtonBase(NextPageLabel, "$next$")); row.Add(new ButtonBase(NextPageLabel, "$next$"));
if (this.EnableSearch) if (EnableSearch)
{ {
row.Insert(2, new ButtonBase("🔍 " + (this.SearchQuery ?? ""), "$search$")); row.Insert(2, new ButtonBase("🔍 " + (SearchQuery ?? ""), "$search$"));
} }
dataForm.InsertButtonRow(0, row); dataForm.InsertButtonRow(0, row);
@ -719,22 +701,22 @@ namespace TelegramBotBase.Controls.Hybrid
private async Task RenderTagView() private async Task RenderTagView()
{ {
Message m = null; Message m = null;
ButtonForm bf = new ButtonForm(); var bf = new ButtonForm();
bf.AddButtonRow(this.BackLabel, "$back$"); bf.AddButtonRow(BackLabel, "$back$");
if (EnableCheckAllTools) if (EnableCheckAllTools)
{ {
this.TagsSubHeadLayoutButtonRow = new ButtonRow(new ButtonBase(CheckAllLabel, "$checkall$"), new ButtonBase(UncheckAllLabel, "$uncheckall$")); TagsSubHeadLayoutButtonRow = new ButtonRow(new ButtonBase(CheckAllLabel, "$checkall$"), new ButtonBase(UncheckAllLabel, "$uncheckall$"));
bf.AddButtonRow(TagsSubHeadLayoutButtonRow); bf.AddButtonRow(TagsSubHeadLayoutButtonRow);
} }
foreach (var t in this.Tags) foreach (var t in Tags)
{ {
String s = t; var s = t;
if (this.SelectedTags?.Contains(t) ?? false) if (SelectedTags?.Contains(t) ?? false)
{ {
s += " ✅"; s += " ✅";
} }
@ -743,17 +725,17 @@ namespace TelegramBotBase.Controls.Hybrid
} }
switch (this.KeyboardType) switch (KeyboardType)
{ {
//Reply Keyboard could only be updated with a new keyboard. //Reply Keyboard could only be updated with a new keyboard.
case eKeyboardType.ReplyKeyboard: case EKeyboardType.ReplyKeyboard:
if (bf.Count == 0) if (bf.Count == 0)
{ {
if (this.MessageId != null) if (MessageId != null)
{ {
await this.Device.HideReplyKeyboard(); await Device.HideReplyKeyboard();
this.MessageId = null; MessageId = null;
} }
return; return;
} }
@ -763,25 +745,25 @@ namespace TelegramBotBase.Controls.Hybrid
var rkm = (ReplyKeyboardMarkup)bf; var rkm = (ReplyKeyboardMarkup)bf;
rkm.ResizeKeyboard = this.ResizeKeyboard; rkm.ResizeKeyboard = ResizeKeyboard;
rkm.OneTimeKeyboard = this.OneTimeKeyboard; rkm.OneTimeKeyboard = OneTimeKeyboard;
m = await this.Device.Send("Choose category", rkm, disableNotification: true, parseMode: MessageParseMode, MarkdownV2AutoEscape: false); m = await Device.Send("Choose category", rkm, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false);
//Prevent flicker of keyboard //Prevent flicker of keyboard
if (this.DeletePreviousMessage && this.MessageId != null) if (DeletePreviousMessage && MessageId != null)
await this.Device.DeleteMessage(this.MessageId.Value); await Device.DeleteMessage(MessageId.Value);
break; break;
case eKeyboardType.InlineKeyBoard: case EKeyboardType.InlineKeyBoard:
if (this.MessageId != null) if (MessageId != null)
{ {
m = await this.Device.Edit(this.MessageId.Value, "Choose category", (InlineKeyboardMarkup)bf); m = await Device.Edit(MessageId.Value, "Choose category", (InlineKeyboardMarkup)bf);
} }
else else
{ {
m = await this.Device.Send("Choose category", (InlineKeyboardMarkup)bf, disableNotification: true, parseMode: MessageParseMode, MarkdownV2AutoEscape: false); m = await Device.Send("Choose category", (InlineKeyboardMarkup)bf, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false);
} }
break; break;
@ -790,7 +772,7 @@ namespace TelegramBotBase.Controls.Hybrid
if (m != null) if (m != null)
this.MessageId = m.MessageId; MessageId = m.MessageId;
} }
@ -802,12 +784,12 @@ namespace TelegramBotBase.Controls.Hybrid
{ {
get get
{ {
if (this.KeyboardType == eKeyboardType.InlineKeyBoard && TotalRows > Constants.Telegram.MaxInlineKeyBoardRows) if (KeyboardType == EKeyboardType.InlineKeyBoard && TotalRows > Constants.Telegram.MaxInlineKeyBoardRows)
{ {
return true; return true;
} }
if (this.KeyboardType == eKeyboardType.ReplyKeyboard && TotalRows > Constants.Telegram.MaxReplyKeyboardRows) if (KeyboardType == EKeyboardType.ReplyKeyboard && TotalRows > Constants.Telegram.MaxReplyKeyboardRows)
{ {
return true; return true;
} }
@ -820,7 +802,7 @@ namespace TelegramBotBase.Controls.Hybrid
{ {
get get
{ {
if (this.NavigationBarVisibility == eNavigationBarVisibility.always | (this.NavigationBarVisibility == eNavigationBarVisibility.auto && PagingNecessary)) if (NavigationBarVisibility == ENavigationBarVisibility.always | (NavigationBarVisibility == ENavigationBarVisibility.auto && PagingNecessary))
{ {
return true; return true;
} }
@ -836,30 +818,19 @@ namespace TelegramBotBase.Controls.Hybrid
{ {
get get
{ {
switch (this.KeyboardType) return KeyboardType switch
{ {
case eKeyboardType.InlineKeyBoard: EKeyboardType.InlineKeyBoard => Constants.Telegram.MaxInlineKeyBoardRows,
return Constants.Telegram.MaxInlineKeyBoardRows; EKeyboardType.ReplyKeyboard => Constants.Telegram.MaxReplyKeyboardRows,
_ => 0
case eKeyboardType.ReplyKeyboard: };
return Constants.Telegram.MaxReplyKeyboardRows;
default:
return 0;
}
} }
} }
/// <summary> /// <summary>
/// Returns the number of all rows (layout + navigation + content); /// Returns the number of all rows (layout + navigation + content);
/// </summary> /// </summary>
public int TotalRows public int TotalRows => LayoutRows + DataSource.RowCount;
{
get
{
return this.LayoutRows + DataSource.RowCount;
}
}
/// <summary> /// <summary>
@ -869,18 +840,18 @@ namespace TelegramBotBase.Controls.Hybrid
{ {
get get
{ {
int layoutRows = 0; var layoutRows = 0;
if (this.NavigationBarVisibility == eNavigationBarVisibility.always | this.NavigationBarVisibility == eNavigationBarVisibility.auto) if (NavigationBarVisibility == ENavigationBarVisibility.always | NavigationBarVisibility == ENavigationBarVisibility.auto)
layoutRows += 2; layoutRows += 2;
if (this.HeadLayoutButtonRow != null && this.HeadLayoutButtonRow.Count > 0) if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0)
layoutRows++; layoutRows++;
if (this.SubHeadLayoutButtonRow != null && this.SubHeadLayoutButtonRow.Count > 0) if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0)
layoutRows++; layoutRows++;
if (EnableCheckAllTools && this.SelectedViewIndex == 1) if (EnableCheckAllTools && SelectedViewIndex == 1)
{ {
layoutRows++; layoutRows++;
} }
@ -892,13 +863,7 @@ namespace TelegramBotBase.Controls.Hybrid
/// <summary> /// <summary>
/// Returns the number of item rows per page. /// Returns the number of item rows per page.
/// </summary> /// </summary>
public int ItemRowsPerPage public int ItemRowsPerPage => MaximumRow - LayoutRows;
{
get
{
return this.MaximumRow - this.LayoutRows;
}
}
public int PageCount public int PageCount
{ {
@ -909,7 +874,7 @@ namespace TelegramBotBase.Controls.Hybrid
//var bf = this.DataSource.PickAllItems(this.EnableSearch ? this.SearchQuery : null); //var bf = this.DataSource.PickAllItems(this.EnableSearch ? this.SearchQuery : null);
var max = this.DataSource.CalculateMax(this.EnableSearch ? this.SearchQuery : null); var max = DataSource.CalculateMax(EnableSearch ? SearchQuery : null);
//if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "")
//{ //{
@ -919,22 +884,24 @@ namespace TelegramBotBase.Controls.Hybrid
if (max == 0) if (max == 0)
return 1; return 1;
return (int)Math.Ceiling((decimal)((decimal)max / (decimal)ItemRowsPerPage)); return (int)Math.Ceiling(max / (decimal)ItemRowsPerPage);
} }
} }
public override async Task Hidden(bool FormClose) public override Task Hidden(bool formClose)
{ {
//Prepare for opening Modal, and comming back //Prepare for opening Modal, and comming back
if (!FormClose) if (!formClose)
{ {
this.Updated(); Updated();
} }
else else
{ {
//Remove event handler //Remove event handler
this.Device.MessageDeleted -= Device_MessageDeleted; Device.MessageDeleted -= Device_MessageDeleted;
} }
return Task.CompletedTask;
} }
/// <summary> /// <summary>
@ -942,31 +909,31 @@ namespace TelegramBotBase.Controls.Hybrid
/// </summary> /// </summary>
public void Updated() public void Updated()
{ {
this.RenderNecessary = true; _renderNecessary = true;
} }
public async override Task Cleanup() public override async Task Cleanup()
{ {
if (this.MessageId == null) if (MessageId == null)
return; return;
switch (this.KeyboardType) switch (KeyboardType)
{ {
case eKeyboardType.InlineKeyBoard: case EKeyboardType.InlineKeyBoard:
await this.Device.DeleteMessage(this.MessageId.Value); await Device.DeleteMessage(MessageId.Value);
this.MessageId = null; MessageId = null;
break; break;
case eKeyboardType.ReplyKeyboard: case EKeyboardType.ReplyKeyboard:
if (this.HideKeyboardOnCleanup) if (HideKeyboardOnCleanup)
{ {
await this.Device.HideReplyKeyboard(); await Device.HideReplyKeyboard();
} }
this.MessageId = null; MessageId = null;
break; break;
} }
@ -979,11 +946,11 @@ namespace TelegramBotBase.Controls.Hybrid
/// </summary> /// </summary>
public void CheckAllTags() public void CheckAllTags()
{ {
this.SelectedTags.Clear(); SelectedTags.Clear();
this.SelectedTags = this.Tags.Select(a => a).ToList(); SelectedTags = Tags.Select(a => a).ToList();
this.Updated(); Updated();
} }
@ -992,9 +959,9 @@ namespace TelegramBotBase.Controls.Hybrid
/// </summary> /// </summary>
public void UncheckAllTags() public void UncheckAllTags()
{ {
this.SelectedTags.Clear(); SelectedTags.Clear();
this.Updated(); Updated();
} }
} }

Some files were not shown because too many files have changed in this diff Show More