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.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using AsyncFormUpdates.forms;
using TelegramBotBase;
using TelegramBotBase.Builder;
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()
.QuickStart<forms.Start>(apiKey)
__bot = BotBaseBuilder.Create()
.QuickStart<Start>(apiKey)
.Build();
bot.Start();
__bot.Start();
var timer = new Timer(5000);
@ -30,19 +28,19 @@ namespace AsyncFormUpdates
Console.ReadLine();
timer.Stop();
bot.Stop();
__bot.Stop();
}
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
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;
await bot.InvokeMessageLoop(s.Key);
await __bot.InvokeMessageLoop(s.Key);
}

View File

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

View File

@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks;
using TelegramBotBase.Attributes;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
@ -11,19 +7,19 @@ namespace AsyncFormUpdates.forms
{
public class AsyncFormEdit : FormBase
{
[SaveState]
int counter = 0;
[SaveState] private int _counter;
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)
{
await message.ConfirmAction("");
await message.ConfirmAction();
switch (message.RawData ?? "")
{
@ -41,14 +37,14 @@ namespace AsyncFormUpdates.forms
var bf = new ButtonForm();
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
{
var m = await Device.Send($"Your current count is at: {counter}", bf, disableNotification: true);
MessageId = m.MessageId;
var m = await Device.Send($"Your current count is at: {_counter}", bf, disableNotification: true);
_messageId = m.MessageId;
}
}

View File

@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks;
using TelegramBotBase.Attributes;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
@ -11,18 +7,18 @@ namespace AsyncFormUpdates.forms
{
public class AsyncFormUpdate : AutoCleanForm
{
[SaveState]
int counter = 0;
[SaveState] private int _counter;
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)
{
await message.ConfirmAction("");
await message.ConfirmAction();
switch (message.RawData ?? "")
{
@ -40,7 +36,7 @@ namespace AsyncFormUpdates.forms
var bf = new ButtonForm();
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.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
@ -14,7 +10,7 @@ namespace AsyncFormUpdates.forms
public override async Task Action(MessageResult message)
{
await message.ConfirmAction("");
await message.ConfirmAction();
switch (message.RawData ?? "")
{

View File

@ -1,17 +1,18 @@
using System;
using JoinHiderBot.forms;
using TelegramBotBase.Builder;
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()
.QuickStart<forms.Start>(apiKey)
.QuickStart<Start>(apiKey)
.Build();
bot.Start();

View File

@ -1,7 +1,5 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks;
using Telegram.Bot.Types.Enums;
using TelegramBotBase.Args;
using TelegramBotBase.Form;
@ -12,13 +10,13 @@ namespace JoinHiderBot.forms
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;
var m = e.Result.Message;
await this.Device.DeleteMessage(m);
await Device.DeleteMessage(m);
}
}

View File

@ -1,7 +1,4 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
@ -11,7 +8,7 @@ namespace JoinHiderBot.forms
{
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;
}
@ -20,7 +17,7 @@ namespace JoinHiderBot.forms
{
var gmf = new GroupManageForm();
await this.NavigateTo(gmf);
await NavigateTo(gmf);
return true;
}

View File

@ -1,17 +1,19 @@
using System;
using SystemCommandsBot.config;
using SystemCommandsBot.forms;
using TelegramBotBase.Builder;
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() == "")
{
@ -21,7 +23,7 @@ namespace SystemCommandsBot
}
var bot = BotBaseBuilder.Create()
.QuickStart<forms.StartForm>(BotConfig.ApiKey)
.QuickStart<StartForm>(BotConfig.ApiKey)
.Build();
bot.Start();

View File

@ -1,28 +1,23 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace SystemCommandsBot.commands
namespace SystemCommandsBot.commands
{
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 String Action { get; set; }
public string Action { get; set; }
public bool UseShell { get; set; } = true;
public int? MaxInstances { get; set; }
public String ProcName
public string ProcName
{
get;set;
}

View File

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

View File

@ -1,31 +1,29 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
namespace SystemCommandsBot.forms
{
public class CmdForm : TelegramBotBase.Form.AutoCleanForm
public class CmdForm : AutoCleanForm
{
public DateTime ExpiresAt { 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)
{
var btn = message.RawData;
int id = -1;
var id = -1;
if (!int.TryParse(btn, out id))
{
@ -33,10 +31,10 @@ namespace SystemCommandsBot.forms
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)
{
await this.Device.Send("Cmd nicht verfügbar.");
await Device.Send("Cmd nicht verfügbar.");
return;
}
@ -46,14 +44,14 @@ namespace SystemCommandsBot.forms
{
case "start":
FileInfo fi = new FileInfo(cmd.ShellCmd);
var fi = new FileInfo(cmd.ShellCmd);
if (cmd.MaxInstances != null && cmd.MaxInstances >= 0)
{
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.");
return;
@ -61,14 +59,16 @@ namespace SystemCommandsBot.forms
}
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = cmd.ShellCmd;
psi.WorkingDirectory = fi.DirectoryName;
psi.UseShellExecute = cmd.UseShell;
var psi = new ProcessStartInfo
{
FileName = cmd.ShellCmd,
WorkingDirectory = fi.DirectoryName,
UseShellExecute = cmd.UseShell
};
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.");
@ -76,9 +76,9 @@ namespace SystemCommandsBot.forms
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();
@ -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.");
@ -102,9 +102,9 @@ namespace SystemCommandsBot.forms
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();
@ -120,17 +120,19 @@ namespace SystemCommandsBot.forms
}
}
FileInfo fi4 = new FileInfo(cmd.ShellCmd);
var fi4 = new FileInfo(cmd.ShellCmd);
ProcessStartInfo psi2 = new ProcessStartInfo();
psi2.FileName = cmd.ShellCmd;
psi2.WorkingDirectory = fi4.DirectoryName;
var psi2 = new ProcessStartInfo
{
FileName = cmd.ShellCmd,
WorkingDirectory = fi4.DirectoryName
};
psi2.FileName = cmd.ShellCmd;
psi2.UseShellExecute = cmd.UseShell;
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.");
@ -151,15 +153,13 @@ namespace SystemCommandsBot.forms
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);
await this.Device.Send("Deine Optionen", bf);
return;
await Device.Send("Deine Optionen", bf);
}

View File

@ -1,40 +1,39 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
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;
if (Program.BotConfig.Password == inp)
{
this.Password = inp;
Password = inp;
}
return Task.CompletedTask;
}
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;
}
var cmd = new forms.CmdForm();
var cmd = new CmdForm();
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.IO;
using System.Threading.Tasks;
using Telegram.Bot.Types.InputFiles;
using Telegram.Bot.Types;
using TelegramBotBase.Sessions;
using Telegram.Bot.Types.InputFiles;
using TelegramBotBase.Form;
using TelegramBotBase.Sessions;
namespace TelegramBotBase.Extensions.Images
{
@ -14,7 +13,7 @@ namespace TelegramBotBase.Extensions.Images
{
public static Stream ToStream(this Image image, ImageFormat format)
{
var stream = new System.IO.MemoryStream();
var stream = new MemoryStream();
image.Save(stream, format);
stream.Position = 0;
return stream;
@ -29,11 +28,11 @@ namespace TelegramBotBase.Extensions.Images
/// <param name="replyTo"></param>
/// <param name="disableNotification"></param>
/// <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))
{
InputOnlineFile fts = new InputOnlineFile(fileStream, name);
var fts = new InputOnlineFile(fileStream, name);
return await session.SendPhoto(fts, caption: caption, buttons, replyTo, disableNotification);
}
@ -48,11 +47,11 @@ namespace TelegramBotBase.Extensions.Images
/// <param name="replyTo"></param>
/// <param name="disableNotification"></param>
/// <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))
{
InputOnlineFile fts = new InputOnlineFile(fileStream, name);
var fts = new InputOnlineFile(fileStream, name);
return await session.SendPhoto(fts, caption: caption, buttons, replyTo, disableNotification);
}

View File

@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Builder;
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.
/// </summary>
/// <param name="builder"></param>
/// <param name="ConnectionString"></param>
/// <param name="connectionString"></param>
/// <param name="tablePrefix"></param>
/// <param name="fallbackForm"></param>
/// <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);
@ -33,18 +29,18 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL
/// Uses an Microsoft SQL Server Database to save and restore sessions.
/// </summary>
/// <param name="builder"></param>
/// <param name="HostOrIP"></param>
/// <param name="UserId"></param>
/// <param name="Password"></param>
/// <param name="DatabaseName"></param>
/// <param name="hostOrIP"></param>
/// <param name="userId"></param>
/// <param name="password"></param>
/// <param name="databaseName"></param>
/// <param name="tablePrefix"></param>
/// <param name="fallbackForm"></param>
/// <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);
@ -55,19 +51,19 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL
/// Uses an Microsoft SQL Server Database with Windows Authentication to save and restore sessions.
/// </summary>
/// <param name="builder"></param>
/// <param name="HostOrIP"></param>
/// <param name="DatabaseName"></param>
/// <param name="hostOrIP"></param>
/// <param name="databaseName"></param>
/// <param name="tablePrefix"></param>
/// <param name="fallbackForm"></param>
/// <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();
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);

View File

@ -1,19 +1,19 @@
using TelegramBotBase.Interfaces;
using TelegramBotBase.Builder.Interfaces;
using System;
using TelegramBotBase.Base;
using TelegramBotBase.Args;
using TelegramBotBase.Form;
using Microsoft.Data.SqlClient;
using System;
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
{
public class MSSQLSerializer : IStateMachine
public class MssqlSerializer : IStateMachine
{
public Type FallbackStateForm { get; set; }
public string ConnectionString { get; }
public String TablePrefix { get; set; }
public string TablePrefix { get; set; }
/// <summary>
/// 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="fallbackStateForm">Type of Form which will be saved instead of Form which has <seealso cref="Attributes.IgnoreState"/> attribute declared. Needs to be subclass of <seealso cref="Form.FormBase"/>.</param>
/// <param name="overwrite">Declares of the file could be overwritten.</param>
public MSSQLSerializer(String ConnectionString, String tablePrefix = "tgb_", Type fallbackStateForm = null)
public MssqlSerializer(string connectionString, string tablePrefix = "tgb_", Type fallbackStateForm = null)
{
if (ConnectionString is null)
{
throw new ArgumentNullException(nameof(ConnectionString));
}
this.ConnectionString = connectionString ?? throw new ArgumentNullException(nameof(connectionString));
this.ConnectionString = ConnectionString;
TablePrefix = tablePrefix;
this.TablePrefix = tablePrefix;
FallbackStateForm = fallbackStateForm;
this.FallbackStateForm = fallbackStateForm;
if (this.FallbackStateForm != null && !this.FallbackStateForm.IsSubclassOf(typeof(FormBase)))
if (FallbackStateForm != null && !FallbackStateForm.IsSubclassOf(typeof(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)
{
var se = new StateEntry()
var se = new StateEntry
{
DeviceId = (long)r["deviceId"],
ChatTitle = r["deviceTitle"].ToString(),
@ -77,21 +72,21 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL
sc.GroupIds.Add(se.DeviceId);
}
var data_command = connection.CreateCommand();
data_command.CommandText = "SELECT [key], value, type FROM " + TablePrefix + "devices_sessions_data WHERE deviceId = @deviceId";
data_command.Parameters.Add(new SqlParameter("@deviceId", r["deviceId"]));
var command2 = connection.CreateCommand();
command2.CommandText = "SELECT [key], value, type FROM " + TablePrefix + "devices_sessions_data WHERE deviceId = @deviceId";
command2.Parameters.Add(new SqlParameter("@deviceId", r["deviceId"]));
var data_table = new DataTable();
using (var dataAdapter2 = new SqlDataAdapter(data_command))
var dataTable2 = new DataTable();
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 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);
}
@ -118,61 +113,61 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL
connection.Open();
//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
var session_command = connection.CreateCommand();
var data_command = connection.CreateCommand();
var sessionCommand = connection.CreateCommand();
var dataCommand = connection.CreateCommand();
session_command.CommandText = "INSERT INTO " + TablePrefix + "devices_sessions (deviceId, deviceTitle, FormUri, QualifiedName) VALUES (@deviceId, @deviceTitle, @FormUri, @QualifiedName)";
session_command.Parameters.Add(new SqlParameter("@deviceId", ""));
session_command.Parameters.Add(new SqlParameter("@deviceTitle", ""));
session_command.Parameters.Add(new SqlParameter("@FormUri", ""));
session_command.Parameters.Add(new SqlParameter("@QualifiedName", ""));
sessionCommand.CommandText = "INSERT INTO " + TablePrefix + "devices_sessions (deviceId, deviceTitle, FormUri, QualifiedName) VALUES (@deviceId, @deviceTitle, @FormUri, @QualifiedName)";
sessionCommand.Parameters.Add(new SqlParameter("@deviceId", ""));
sessionCommand.Parameters.Add(new SqlParameter("@deviceTitle", ""));
sessionCommand.Parameters.Add(new SqlParameter("@FormUri", ""));
sessionCommand.Parameters.Add(new SqlParameter("@QualifiedName", ""));
data_command.CommandText = "INSERT INTO " + TablePrefix + "devices_sessions_data (deviceId, [key], value, type) VALUES (@deviceId, @key, @value, @type)";
data_command.Parameters.Add(new SqlParameter("@deviceId", ""));
data_command.Parameters.Add(new SqlParameter("@key", ""));
data_command.Parameters.Add(new SqlParameter("@value", ""));
data_command.Parameters.Add(new SqlParameter("@type", ""));
dataCommand.CommandText = "INSERT INTO " + TablePrefix + "devices_sessions_data (deviceId, [key], value, type) VALUES (@deviceId, @key, @value, @type)";
dataCommand.Parameters.Add(new SqlParameter("@deviceId", ""));
dataCommand.Parameters.Add(new SqlParameter("@key", ""));
dataCommand.Parameters.Add(new SqlParameter("@value", ""));
dataCommand.Parameters.Add(new SqlParameter("@type", ""));
//Store session data in database
foreach (var state in container.States)
{
session_command.Parameters["@deviceId"].Value = state.DeviceId;
session_command.Parameters["@deviceTitle"].Value = state.ChatTitle ?? "";
session_command.Parameters["@FormUri"].Value = state.FormUri;
session_command.Parameters["@QualifiedName"].Value = state.QualifiedName;
sessionCommand.Parameters["@deviceId"].Value = state.DeviceId;
sessionCommand.Parameters["@deviceTitle"].Value = state.ChatTitle ?? "";
sessionCommand.Parameters["@FormUri"].Value = state.FormUri;
sessionCommand.Parameters["@QualifiedName"].Value = state.QualifiedName;
session_command.ExecuteNonQuery();
sessionCommand.ExecuteNonQuery();
foreach (var data in state.Values)
{
data_command.Parameters["@deviceId"].Value = state.DeviceId;
data_command.Parameters["@key"].Value = data.Key;
dataCommand.Parameters["@deviceId"].Value = state.DeviceId;
dataCommand.Parameters["@key"].Value = data.Key;
var type = data.Value.GetType();
if (type.IsPrimitive || type.Equals(typeof(string)))
{
data_command.Parameters["@value"].Value = data.Value;
dataCommand.Parameters["@value"].Value = data.Value;
}
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.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot.Types;
using TelegramBotBase;
using TelegramBotBase.Form;
using TelegramBotBaseTest.Tests;
using TelegramBotBase.Commands;
using TelegramBotBase.Args;
using TelegramBotBase.Builder;
using TelegramBotBase.Commands;
using TelegramBotBase.Enums;
using TelegramBotBaseTest.Tests;
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
.Create()
.WithAPIKey(APIKey)
.WithAPIKey(apiKey)
.DefaultMessageLoop()
.WithStartForm<Start>()
.NoProxy()
@ -45,7 +42,7 @@ namespace TelegramBotBaseTest
//Update Bot commands to botfather
bb.UploadBotCommands().Wait();
bb.SetSetting(TelegramBotBase.Enums.eSettings.LogAllMessages, true);
bb.SetSetting(ESettings.LogAllMessages, true);
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)
{
@ -105,7 +102,7 @@ namespace TelegramBotBaseTest
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);

View File

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

View File

@ -1,7 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
@ -13,12 +10,12 @@ namespace TelegramBotBaseTest.Tests
public ButtonTestForm()
{
this.Opened += ButtonTestForm_Opened;
Opened += ButtonTestForm_Opened;
}
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)
@ -38,25 +35,25 @@ namespace TelegramBotBaseTest.Tests
{
case "button1":
await this.Device.Send("Button 1 pressed");
await Device.Send("Button 1 pressed");
break;
case "button2":
await this.Device.Send("Button 2 pressed");
await Device.Send("Button 2 pressed");
break;
case "button3":
await this.Device.Send("Button 3 pressed");
await Device.Send("Button 3 pressed");
break;
case "button4":
await this.Device.Send("Button 4 pressed");
await Device.Send("Button 4 pressed");
break;
@ -64,7 +61,7 @@ namespace TelegramBotBaseTest.Tests
var st = new Menu();
await this.NavigateTo(st);
await NavigateTo(st);
break;
@ -82,7 +79,7 @@ namespace TelegramBotBaseTest.Tests
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()));
@ -92,7 +89,7 @@ namespace TelegramBotBaseTest.Tests
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.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks;
using TelegramBotBase.Args;
using TelegramBotBase.Controls;
using TelegramBotBase.Controls.Hybrid;
using TelegramBotBase.Enums;
using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Controls
{
public class ButtonGridForm : AutoCleanForm
{
ButtonGrid m_Buttons = null;
private ButtonGrid _mButtons;
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;
ButtonForm bf = new ButtonForm();
var bf = new ButtonForm();
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"));
m_Buttons.ButtonsForm = bf;
m_Buttons.ButtonClicked += Bg_ButtonClicked;
this.AddControl(m_Buttons);
_mButtons.ButtonsForm = bf;
_mButtons.ButtonClicked += Bg_ButtonClicked;
AddControl(_mButtons);
return Task.CompletedTask;
}
private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e)
@ -53,26 +48,21 @@ namespace TelegramBotBaseTest.Tests.Controls
if (e.Button.Value == "back")
{
var start = new Menu();
await this.NavigateTo(start);
await NavigateTo(start);
}
else if (e.Button.Value == "switch")
{
switch (m_Buttons.KeyboardType)
_mButtons.KeyboardType = _mButtons.KeyboardType switch
{
case TelegramBotBase.Enums.eKeyboardType.ReplyKeyboard:
m_Buttons.KeyboardType = TelegramBotBase.Enums.eKeyboardType.InlineKeyBoard;
break;
case TelegramBotBase.Enums.eKeyboardType.InlineKeyBoard:
m_Buttons.KeyboardType = TelegramBotBase.Enums.eKeyboardType.ReplyKeyboard;
break;
}
EKeyboardType.ReplyKeyboard => EKeyboardType.InlineKeyBoard,
EKeyboardType.InlineKeyBoard => EKeyboardType.ReplyKeyboard,
_ => _mButtons.KeyboardType
};
}
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.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Args;
using TelegramBotBase.Controls;
using TelegramBotBase.Controls.Hybrid;
using TelegramBotBase.Enums;
using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Controls
{
public class ButtonGridPagingForm : AutoCleanForm
{
ButtonGrid m_Buttons = null;
private ButtonGrid _mButtons;
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();
m_Buttons.KeyboardType = TelegramBotBase.Enums.eKeyboardType.ReplyKeyboard;
m_Buttons.EnablePaging = true;
m_Buttons.EnableSearch = true;
m_Buttons.HeadLayoutButtonRow = new List<ButtonBase>() { new ButtonBase("Back", "back") };
_mButtons = new ButtonGrid
{
KeyboardType = EKeyboardType.ReplyKeyboard,
EnablePaging = true,
EnableSearch = true,
HeadLayoutButtonRow = new List<ButtonBase> { new ButtonBase("Back", "back") }
};
var countries = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
ButtonForm bf = new ButtonForm();
var bf = new ButtonForm();
foreach (var c in countries)
{
bf.AddButtonRow(new ButtonBase(c.EnglishName, c.EnglishName));
}
m_Buttons.ButtonsForm = bf;
m_Buttons.ButtonClicked += Bg_ButtonClicked;
this.AddControl(m_Buttons);
_mButtons.ButtonsForm = bf;
_mButtons.ButtonClicked += Bg_ButtonClicked;
AddControl(_mButtons);
return Task.CompletedTask;
}
private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e)
@ -60,12 +54,12 @@ namespace TelegramBotBaseTest.Tests.Controls
if (e.Button.Value == "back")
{
var start = new Menu();
await this.NavigateTo(start);
await NavigateTo(start);
}
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.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Args;
using TelegramBotBase.Controls;
using TelegramBotBase.Controls.Hybrid;
using TelegramBotBase.DataSources;
using TelegramBotBase.Enums;
using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Controls
{
public class ButtonGridTagForm : AutoCleanForm
{
TaggedButtonGrid m_Buttons = null;
private TaggedButtonGrid _mButtons;
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);
ButtonForm bf = new ButtonForm();
var bf = new ButtonForm();
foreach (var c in countries)
{
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();
m_Buttons.SelectedTags = countries.Select(a => a.Parent.EnglishName).Distinct().OrderBy(a => a).ToList();
_mButtons.Tags = 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)
@ -65,13 +63,13 @@ namespace TelegramBotBaseTest.Tests.Controls
case "back":
var start = new Menu();
await this.NavigateTo(start);
await NavigateTo(start);
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.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
using TelegramBotBase.Controls;
using System.Threading.Tasks;
using TelegramBotBase.Args;
using TelegramBotBase.Base;
using TelegramBotBase.Controls.Inline;
using TelegramBotBase.Enums;
using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Controls
{
@ -17,20 +12,23 @@ namespace TelegramBotBaseTest.Tests.Controls
public CalendarPicker Picker { get; set; }
int? selectedDateMessage { get; set; }
private int? SelectedDateMessage { get; set; }
public CalendarPickerForm()
{
this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm;
this.Init += CalendarPickerForm_Init;
DeleteMode = EDeleteMode.OnLeavingForm;
Init += CalendarPickerForm_Init;
}
private async Task CalendarPickerForm_Init(object sender, InitEventArgs e)
private Task CalendarPickerForm_Init(object sender, InitEventArgs e)
{
this.Picker = new CalendarPicker();
this.Picker.Title = "Datum auswählen / Pick date";
this.AddControl(Picker);
Picker = new CalendarPicker
{
Title = "Datum auswählen / Pick date"
};
AddControl(Picker);
return Task.CompletedTask;
}
@ -43,7 +41,7 @@ namespace TelegramBotBaseTest.Tests.Controls
var s = new Menu();
await this.NavigateTo(s);
await NavigateTo(s);
break;
}
@ -52,23 +50,23 @@ namespace TelegramBotBaseTest.Tests.Controls
public override async Task Render(MessageResult message)
{
String s = "";
var s = "";
s = "Selected date is " + this.Picker.SelectedDate.ToShortDateString() + "\r\n";
s += "Selected month is " + this.Picker.Culture.DateTimeFormat.MonthNames[this.Picker.VisibleMonth.Month - 1] + "\r\n";
s += "Selected year is " + this.Picker.VisibleMonth.Year.ToString();
s = "Selected date is " + Picker.SelectedDate.ToShortDateString() + "\r\n";
s += "Selected month is " + Picker.Culture.DateTimeFormat.MonthNames[Picker.VisibleMonth.Month - 1] + "\r\n";
s += "Selected year is " + Picker.VisibleMonth.Year;
ButtonForm bf = new ButtonForm();
var bf = new ButtonForm();
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
{
var m = await this.Device.Send(s, bf);
this.selectedDateMessage = m.MessageId;
var m = await Device.Send(s, bf);
SelectedDateMessage = m.MessageId;
}

View File

@ -1,56 +1,54 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Threading.Tasks;
using TelegramBotBase.Args;
using TelegramBotBase.Controls;
using TelegramBotBase.Controls.Hybrid;
using TelegramBotBase.DataSources;
using TelegramBotBase.Enums;
using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Controls
{
public class CheckedButtonListForm : AutoCleanForm
{
CheckedButtonList m_Buttons = null;
private CheckedButtonList _mButtons;
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;
m_Buttons.EnablePaging = true;
var bf = new ButtonForm();
m_Buttons.HeadLayoutButtonRow = new List<ButtonBase>() { new ButtonBase("Back", "back"), new ButtonBase("Switch Keyboard", "switch") };
m_Buttons.SubHeadLayoutButtonRow = new List<ButtonBase>() { new ButtonBase("No checked items", "$") };
ButtonForm bf = new ButtonForm();
for (int i = 0; i < 30; i++)
for (var i = 0; i < 30; i++)
{
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;
m_Buttons.CheckedChanged += M_Buttons_CheckedChanged;
_mButtons.ButtonClicked += Bg_ButtonClicked;
_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)
@ -68,16 +66,12 @@ namespace TelegramBotBaseTest.Tests.Controls
case "switch":
switch (m_Buttons.KeyboardType)
_mButtons.KeyboardType = _mButtons.KeyboardType switch
{
case TelegramBotBase.Enums.eKeyboardType.ReplyKeyboard:
m_Buttons.KeyboardType = TelegramBotBase.Enums.eKeyboardType.InlineKeyBoard;
break;
case TelegramBotBase.Enums.eKeyboardType.InlineKeyBoard:
m_Buttons.KeyboardType = TelegramBotBase.Enums.eKeyboardType.ReplyKeyboard;
break;
}
EKeyboardType.ReplyKeyboard => EKeyboardType.InlineKeyBoard,
EKeyboardType.InlineKeyBoard => EKeyboardType.ReplyKeyboard,
_ => _mButtons.KeyboardType
};
break;

View File

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

View File

@ -1,11 +1,10 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Args;
using TelegramBotBase.Controls;
using TelegramBotBase.Controls.Inline;
using TelegramBotBase.Enums;
using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Controls
@ -14,28 +13,33 @@ namespace TelegramBotBaseTest.Tests.Controls
{
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.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.AllowEmptySelection = false;
mtb.Toggled += Tb_Toggled;
this.AddControl(mtb);
AddControl(mtb);
return Task.CompletedTask;
}
private void Tb_Toggled(object sender, EventArgs e)
@ -43,11 +47,11 @@ namespace TelegramBotBaseTest.Tests.Controls
var tb = sender as MultiToggleButton;
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;
}
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.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Base;
using System.Threading.Tasks;
using TelegramBotBase.Args;
using TelegramBotBase.Controls.Hybrid;
using TelegramBotBase.Enums;
using TelegramBotBase.Form;
using TelegramBotBaseTest.Tests.Controls.Subclass;
namespace TelegramBotBaseTest.Tests.Controls
{
public class MultiViewForm : AutoCleanForm
{
private MultiViewTest _mvt;
Subclass.MultiViewTest mvt = null;
ButtonGrid bg = null;
private ButtonGrid _bg;
public MultiViewForm()
{
this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm;
this.Init += MultiViewForm_Init;
DeleteMode = EDeleteMode.OnLeavingForm;
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.ButtonsForm = new ButtonForm();
bg.ButtonsForm.AddButtonRow("Back", "$back$");
bg.ButtonClicked += Bg_ButtonClicked;
bg.KeyboardType = TelegramBotBase.Enums.eKeyboardType.ReplyKeyboard;
AddControl(bg);
_bg = new ButtonGrid
{
ButtonsForm = new ButtonForm()
};
_bg.ButtonsForm.AddButtonRow("Back", "$back$");
_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)
{

View File

@ -1,40 +1,38 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks;
using TelegramBotBase.Args;
using TelegramBotBase.Base;
using TelegramBotBase.Controls.Hybrid;
using TelegramBotBase.Form;
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)
{
case "back":
this.SelectedViewIndex--;
SelectedViewIndex--;
break;
case "next":
this.SelectedViewIndex++;
SelectedViewIndex++;
break;
}
return Task.CompletedTask;
}
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"));
switch (e.CurrentView)

View File

@ -1,11 +1,8 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Args;
using TelegramBotBase.Controls;
using TelegramBotBase.Controls.Inline;
using TelegramBotBase.Enums;
using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Controls
@ -14,38 +11,44 @@ namespace TelegramBotBaseTest.Tests.Controls
{
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();
tb.Checked = true;
var tb = new ToggleButton
{
Checked = true
};
tb.Toggled += Tb_Toggled;
this.AddControl(tb);
AddControl(tb);
tb = new ToggleButton();
tb.Checked = false;
tb = new ToggleButton
{
Checked = false
};
tb.Toggled += Tb_Toggled;
this.AddControl(tb);
AddControl(tb);
tb = new ToggleButton();
tb.Checked = true;
tb = new ToggleButton
{
Checked = true
};
tb.Toggled += Tb_Toggled;
this.AddControl(tb);
AddControl(tb);
return Task.CompletedTask;
}
private void Tb_Toggled(object sender, EventArgs e)
{
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.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Form;
using TelegramBotBase.Controls;
using TelegramBotBase.Base;
using System.Threading.Tasks;
using TelegramBotBase.Args;
using TelegramBotBase.Base;
using TelegramBotBase.Controls.Inline;
using TelegramBotBase.Enums;
using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Controls
{
public class TreeViewForms : AutoCleanForm
{
public TreeView view { get; set; }
public TreeView View { get; set; }
private int? MessageId { get; set; }
public TreeViewForms()
{
this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm;
this.Init += TreeViewForms_Init;
DeleteMode = EDeleteMode.OnLeavingForm;
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");
@ -35,7 +31,7 @@ namespace TelegramBotBaseTest.Tests.Controls
tvn.AddNode(new TreeViewNode("VW", "vw"));
tvn.AddNode(new TreeViewNode("Lamborghini", "lamborghini"));
view.Nodes.Add(tvn);
View.Nodes.Add(tvn);
tvn = new TreeViewNode("Fruits", "fruits");
@ -43,10 +39,10 @@ namespace TelegramBotBaseTest.Tests.Controls
tvn.AddNode(new TreeViewNode("Orange", "orange"));
tvn.AddNode(new TreeViewNode("Lemon", "lemon"));
view.Nodes.Add(tvn);
this.AddControl(view);
View.Nodes.Add(tvn);
AddControl(View);
return Task.CompletedTask;
}
public override async Task Action(MessageResult message)
@ -64,7 +60,7 @@ namespace TelegramBotBaseTest.Tests.Controls
var start = new Menu();
await this.NavigateTo(start);
await NavigateTo(start);
break;
@ -74,26 +70,26 @@ namespace TelegramBotBaseTest.Tests.Controls
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 += "Selected Path: " + (this.view.SelectedNode?.GetPath() ?? "(null)") + "\r\n";
s += "Visible Path: " + View.GetPath() + "\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"));
if (MessageId != null)
{
await this.Device.Edit(this.MessageId.Value, s, bf);
await Device.Edit(MessageId.Value, s, bf);
}
else
{
var m = await this.Device.Send(s, bf);
this.MessageId = m.MessageId;
var m = await Device.Send(s, bf);
MessageId = m.MessageId;
}
}

View File

@ -1,10 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using Telegram.Bot;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types.InputFiles;
using Telegram.Bot.Types.ReplyMarkups;
using TelegramBotBase.Base;
@ -18,68 +15,68 @@ namespace TelegramBotBaseTest.Tests
public override async Task SentData(DataResult data)
{
String tmp = "";
var tmp = "";
InputOnlineFile file;
switch (data.Type)
{
case Telegram.Bot.Types.Enums.MessageType.Contact:
case MessageType.Contact:
tmp += "Firstname: " + data.Contact.FirstName + "\r\n";
tmp += "Lastname: " + data.Contact.LastName + "\r\n";
tmp += "Phonenumber: " + data.Contact.PhoneNumber + "\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;
case Telegram.Bot.Types.Enums.MessageType.Document:
case MessageType.Document:
file = new InputOnlineFile(data.Document.FileId);
await this.Device.SendDocument(file, "Your uploaded document");
await Device.SendDocument(file, "Your uploaded document");
break;
case Telegram.Bot.Types.Enums.MessageType.Video:
case MessageType.Video:
file = new InputOnlineFile(data.Document.FileId);
await this.Device.SendDocument(file, "Your uploaded video");
await Device.SendDocument(file, "Your uploaded video");
break;
case Telegram.Bot.Types.Enums.MessageType.Audio:
case MessageType.Audio:
file = new InputOnlineFile(data.Document.FileId);
await this.Device.SendDocument(file, "Your uploaded audio");
await Device.SendDocument(file, "Your uploaded audio");
break;
case Telegram.Bot.Types.Enums.MessageType.Location:
case MessageType.Location:
tmp += "Lat: " + data.Location.Latitude + "\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;
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 this.Client.TelegramClient.SendPhotoAsync(this.Device.DeviceId, photo);
await Device.Send("Your image: ", replyTo: data.MessageId);
await Client.TelegramClient.SendPhotoAsync(Device.DeviceId, photo);
break;
default:
await this.Device.Send("Unknown response");
await Device.Send("Unknown response");
break;
}
@ -97,13 +94,13 @@ namespace TelegramBotBaseTest.Tests
{
case "contact":
await this.Device.RequestContact();
await Device.RequestContact();
break;
case "location":
await this.Device.RequestLocation();
await Device.RequestLocation();
break;
@ -113,7 +110,7 @@ namespace TelegramBotBaseTest.Tests
var start = new Menu();
await this.NavigateTo(start);
await NavigateTo(start);
break;
}
@ -123,7 +120,7 @@ namespace TelegramBotBaseTest.Tests
public override async Task Render(MessageResult message)
{
ButtonForm bf = new ButtonForm();
var bf = new ButtonForm();
bf.AddButtonRow(new ButtonBase("Request User contact", "contact"));
@ -133,7 +130,7 @@ namespace TelegramBotBaseTest.Tests
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.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using TelegramBotBase.Controls.Hybrid;
using TelegramBotBase.Datasources;
using TelegramBotBase.DataSources;
using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Datasources
@ -13,28 +13,28 @@ namespace TelegramBotBaseTest.Tests.Datasources
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()
{
loadData();
LoadData();
}
/// <summary>
/// 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.
/// </summary>
private void loadData()
private void LoadData()
{
//Exists data source? Read it
if (File.Exists(AppContext.BaseDirectory + "countries.json"))
{
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
{
@ -52,7 +52,7 @@ namespace TelegramBotBaseTest.Tests.Datasources
Countries = countries;
var tmp = Newtonsoft.Json.JsonConvert.SerializeObject(countries);
var tmp = JsonConvert.SerializeObject(countries);
File.WriteAllText( AppContext.BaseDirectory + "countries.json", tmp);
}
@ -76,7 +76,7 @@ namespace TelegramBotBaseTest.Tests.Datasources
{
var items = Countries.Skip(start).Take(count);
List<ButtonRow> lst = new List<ButtonRow>();
var lst = new List<ButtonRow>();
foreach (var c in items)
{
lst.Add(Render(c));
@ -87,7 +87,7 @@ namespace TelegramBotBaseTest.Tests.Datasources
public override List<ButtonRow> AllItems()
{
List<ButtonRow> lst = new List<ButtonRow>();
var lst = new List<ButtonRow>();
foreach (var c in Countries)
{
lst.Add(Render(c));
@ -97,9 +97,9 @@ namespace TelegramBotBaseTest.Tests.Datasources
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)
{
lst.AddButtonRow(c);
@ -109,9 +109,9 @@ namespace TelegramBotBaseTest.Tests.Datasources
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);
@ -128,36 +128,16 @@ namespace TelegramBotBaseTest.Tests.Datasources
public override ButtonRow Render(object data)
{
var s = data as String;
if (s == null)
if (!(data is string s))
return new ButtonRow(new ButtonBase("Empty", "zero"));
return new ButtonRow(new ButtonBase(s, s));
}
public override int Count
{
get
{
return Countries.Count;
}
}
public override int Count => Countries.Count;
public override int ColumnCount
{
get
{
return 1;
}
}
public override int RowCount
{
get
{
return this.Count;
}
}
public override int ColumnCount => 1;
public override int RowCount => Count;
}
}

View File

@ -1,42 +1,43 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Base;
using System.Threading.Tasks;
using TelegramBotBase.Args;
using TelegramBotBase.Controls.Hybrid;
using TelegramBotBase.Enums;
using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Datasources
{
public class List : FormBase
{
ButtonGrid __buttons = null;
private ButtonGrid _buttons;
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.EnableSearch = false;
__buttons.ButtonClicked += __buttons_ButtonClicked;
__buttons.KeyboardType = TelegramBotBase.Enums.eKeyboardType.ReplyKeyboard;
__buttons.DeleteReplyMessage = true;
_buttons.ButtonClicked += __buttons_ButtonClicked;
_buttons.KeyboardType = 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();
__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)
{

View File

@ -1,6 +1,4 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Args;
using TelegramBotBase.Base;
@ -8,24 +6,24 @@ using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Groups
{
public class GroupChange : TelegramBotBase.Form.GroupForm
public class GroupChange : GroupForm
{
public GroupChange()
{
this.Opened += GroupChange_Opened;
Opened += GroupChange_Opened;
}
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 WelcomeUser Test", "welcomeuser"));
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();
await this.NavigateTo(gc);
await NavigateTo(gc);
break;
case "welcomeuser":
var wu = new WelcomeUser();
await this.NavigateTo(wu);
await NavigateTo(wu);
break;
case "linkreplace":
var lr = new LinkReplaceTest();
await this.NavigateTo(lr);
await NavigateTo(lr);
break;
}
@ -69,7 +67,7 @@ namespace TelegramBotBaseTest.Tests.Groups
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.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Groups
{
public class LinkReplaceTest : TelegramBotBase.Form.GroupForm
public class LinkReplaceTest : GroupForm
{
Dictionary<long, int> Counter { get; set; } = new Dictionary<long, int>();
private Dictionary<long, int> Counter { get; set; } = new Dictionary<long, int>();
private const int Maximum = 3;
public LinkReplaceTest()
{
this.Opened += LinkReplaceTest_Opened;
Opened += LinkReplaceTest_Opened;
}
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 WelcomeUser Test", "welcomeuser"));
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();
await this.NavigateTo(gc);
await NavigateTo(gc);
break;
case "welcomeuser":
var wu = new WelcomeUser();
await this.NavigateTo(wu);
await NavigateTo(wu);
break;
case "linkreplace":
var lr = new LinkReplaceTest();
await this.NavigateTo(lr);
await NavigateTo(lr);
break;
}
@ -86,23 +85,25 @@ namespace TelegramBotBaseTest.Tests.Groups
var u = await Device.GetChatUser(from);
//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;
}
await e.Device.DeleteMessage(e.MessageId);
var cp = new ChatPermissions();
cp.CanAddWebPagePreviews = false;
cp.CanChangeInfo = false;
cp.CanInviteUsers = false;
cp.CanPinMessages = false;
cp.CanSendMediaMessages = false;
cp.CanSendMessages = false;
cp.CanSendOtherMessages = false;
cp.CanSendPolls = false;
var cp = new ChatPermissions
{
CanAddWebPagePreviews = false,
CanChangeInfo = false,
CanInviteUsers = false,
CanPinMessages = false,
CanSendMediaMessages = false,
CanSendMessages = false,
CanSendOtherMessages = false,
CanSendPolls = false
};
//Collect user "mistakes" with sending url, after 3 he gets kicked out.
if (Counter.ContainsKey(from))
@ -147,12 +148,12 @@ namespace TelegramBotBaseTest.Tests.Groups
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private bool HasLinks(String str)
private bool HasLinks(string 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]$";
Regex r = new Regex(pattern);
var r = new Regex(pattern);
var matches = r.Matches(tmp);

View File

@ -1,33 +1,32 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using Telegram.Bot.Types.Enums;
using TelegramBotBase.Args;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
using TelegramBotBase.Args;
namespace TelegramBotBaseTest.Tests.Groups
{
public class WelcomeUser : TelegramBotBase.Form.GroupForm
public class WelcomeUser : GroupForm
{
public WelcomeUser()
{
this.Opened += WelcomeUser_Opened;
Opened += WelcomeUser_Opened;
}
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 WelcomeUser Test", "welcomeuser"));
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();
await this.NavigateTo(gc);
await NavigateTo(gc);
break;
case "welcomeuser":
var wu = new WelcomeUser();
await this.NavigateTo(wu);
await NavigateTo(wu);
break;
case "linkreplace":
var lr = new LinkReplaceTest();
await this.NavigateTo(lr);
await NavigateTo(lr);
break;
}
@ -71,15 +70,15 @@ namespace TelegramBotBaseTest.Tests.Groups
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.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks;
using Telegram.Bot.Types.Enums;
using TelegramBotBase.Base;
using TelegramBotBase.Enums;
using TelegramBotBase.Form;
using TelegramBotBaseTest.Tests.Controls;
using TelegramBotBaseTest.Tests.Datasources;
using TelegramBotBaseTest.Tests.Groups;
namespace TelegramBotBaseTest.Tests
{
@ -13,18 +13,18 @@ namespace TelegramBotBaseTest.Tests
{
public Menu()
{
this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm;
DeleteMode = EDeleteMode.OnLeavingForm;
}
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();
await this.NavigateTo(sf);
await NavigateTo(sf);
break;
@ -57,7 +57,7 @@ namespace TelegramBotBaseTest.Tests
var bf = new ButtonTestForm();
await this.NavigateTo(bf);
await NavigateTo(bf);
break;
@ -65,7 +65,7 @@ namespace TelegramBotBaseTest.Tests
var pf = new ProgressTest();
await this.NavigateTo(pf);
await NavigateTo(pf);
break;
@ -73,7 +73,7 @@ namespace TelegramBotBaseTest.Tests
var reg = new Register.Start();
await this.NavigateTo(reg);
await NavigateTo(reg);
break;
@ -81,7 +81,7 @@ namespace TelegramBotBaseTest.Tests
var form1 = new TestForm();
await this.NavigateTo(form1);
await NavigateTo(form1);
break;
@ -89,7 +89,7 @@ namespace TelegramBotBaseTest.Tests
var form2 = new TestForm2();
await this.NavigateTo(form2);
await NavigateTo(form2);
break;
@ -97,71 +97,71 @@ namespace TelegramBotBaseTest.Tests
var data = new DataForm();
await this.NavigateTo(data);
await NavigateTo(data);
break;
case "calendar":
var calendar = new Controls.CalendarPickerForm();
var calendar = new CalendarPickerForm();
await this.NavigateTo(calendar);
await NavigateTo(calendar);
break;
case "month":
var month = new Controls.MonthPickerForm();
var month = new MonthPickerForm();
await this.NavigateTo(month);
await NavigateTo(month);
break;
case "treeview":
var tree = new Controls.TreeViewForms();
var tree = new TreeViewForms();
await this.NavigateTo(tree);
await NavigateTo(tree);
break;
case "togglebuttons":
var tb = new Controls.ToggleButtons();
var tb = new ToggleButtons();
await this.NavigateTo(tb);
await NavigateTo(tb);
break;
case "multitogglebuttons":
var mtb = new Controls.MultiToggleButtons();
var mtb = new MultiToggleButtons();
await this.NavigateTo(mtb);
await NavigateTo(mtb);
break;
case "buttongrid":
var bg = new Controls.ButtonGridForm();
var bg = new ButtonGridForm();
await this.NavigateTo(bg);
await NavigateTo(bg);
break;
case "buttongridfilter":
var bg2 = new Controls.ButtonGridPagingForm();
var bg2 = new ButtonGridPagingForm();
await this.NavigateTo(bg2);
await NavigateTo(bg2);
break;
case "buttongridtags":
var bg3 = new Controls.ButtonGridTagForm();
var bg3 = new ButtonGridTagForm();
await this.NavigateTo(bg3);
await NavigateTo(bg3);
break;
@ -194,7 +194,7 @@ namespace TelegramBotBaseTest.Tests
case "dynamicbuttongrid":
var dg = new Datasources.List();
var dg = new List();
await NavigateTo(dg);
@ -220,7 +220,7 @@ namespace TelegramBotBaseTest.Tests
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("#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()));
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.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Form;
using TelegramBotBase.Form.Navigation;
namespace TelegramBotBaseTest.Tests.Navigation
{
class CustomController : NavigationController
internal class CustomController : NavigationController
{
public CustomController(FormBase form) : base(form)
{
@ -17,7 +15,7 @@ namespace TelegramBotBaseTest.Tests.Navigation
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})");
return base.PushAsync(form, args);
@ -26,7 +24,7 @@ namespace TelegramBotBaseTest.Tests.Navigation
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})");
return base.PopAsync();
@ -34,7 +32,7 @@ namespace TelegramBotBaseTest.Tests.Navigation
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})");
return base.PopToRootAsync();

View File

@ -1,6 +1,4 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot.Types;
using TelegramBotBase.Base;
@ -10,19 +8,19 @@ namespace TelegramBotBaseTest.Tests.Navigation
{
public class Form1 : FormBase
{
Message msg = null;
private Message _msg;
public Form1()
{
this.Closed += Form1_Closed;
Closed += Form1_Closed;
}
private async Task Form1_Closed(object sender, EventArgs e)
{
if (msg == null)
if (_msg == null)
return;
await Device.DeleteMessage(msg);
await Device.DeleteMessage(_msg);
}
public override async Task Action(MessageResult message)
@ -71,7 +69,7 @@ namespace TelegramBotBaseTest.Tests.Navigation
public override async Task Render(MessageResult message)
{
if (msg != null)
if (_msg != null)
return;
var bf = new ButtonForm();
@ -79,7 +77,7 @@ namespace TelegramBotBaseTest.Tests.Navigation
bf.AddButtonRow("Previous page", "previous");
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.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks;
using Telegram.Bot.Types;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
using TelegramBotBase.Form.Navigation;
namespace TelegramBotBaseTest.Tests.Navigation
{
public class Start : FormBase
{
private Message _msg;
Message msg = null;
public Start()
public override Task Load(MessageResult message)
{
}
public override async Task Load(MessageResult message)
{
return Task.CompletedTask;
}
public override async Task Action(MessageResult message)
@ -50,10 +38,10 @@ namespace TelegramBotBaseTest.Tests.Navigation
await NavigateTo(nc);
if (msg == null)
if (_msg == null)
return;
await Device.DeleteMessage(msg);
await Device.DeleteMessage(_msg);
break;
@ -65,10 +53,10 @@ namespace TelegramBotBaseTest.Tests.Navigation
await NavigateTo(mn);
if (msg == null)
if (_msg == null)
return;
await Device.DeleteMessage(msg);
await Device.DeleteMessage(_msg);
break;
}
@ -82,7 +70,7 @@ namespace TelegramBotBaseTest.Tests.Navigation
bf.AddButtonRow("Yes", "yes");
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.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks;
using TelegramBotBase.Base;
using TelegramBotBase.Enums;
using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Notifications
{
public class Start : AutoCleanForm
{
bool sent = false;
private bool _sent;
public Start()
{
this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm;
DeleteMode = EDeleteMode.OnLeavingForm;
}
public override async Task Action(MessageResult message)
@ -46,7 +44,7 @@ namespace TelegramBotBaseTest.Tests.Notifications
public override async Task Render(MessageResult message)
{
if (sent)
if (_sent)
return;
var bf = new ButtonForm();
@ -56,7 +54,7 @@ namespace TelegramBotBaseTest.Tests.Notifications
await Device.Send("Choose your test", bf);
sent = true;
_sent = true;
}
}

View File

@ -1,11 +1,9 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using TelegramBotBase.Base;
using TelegramBotBase.Controls.Inline;
using TelegramBotBase.Enums;
using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests
@ -15,15 +13,15 @@ namespace TelegramBotBaseTest.Tests
public ProgressTest()
{
this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm;
this.Opened += ProgressTest_Opened;
this.Closed += ProgressTest_Closed;
DeleteMode = EDeleteMode.OnLeavingForm;
Opened += ProgressTest_Opened;
Closed += ProgressTest_Closed;
}
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)
@ -36,42 +34,52 @@ namespace TelegramBotBaseTest.Tests
if (call == null)
return;
ProgressBar Bar = null;
ProgressBar bar = null;
switch (call.Value)
{
case "standard":
Bar = new ProgressBar(0, 100, ProgressBar.eProgressStyle.standard);
Bar.Device = this.Device;
bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.standard)
{
Device = Device
};
break;
case "squares":
Bar = new ProgressBar(0, 100, ProgressBar.eProgressStyle.squares);
Bar.Device = this.Device;
bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.squares)
{
Device = Device
};
break;
case "circles":
Bar = new ProgressBar(0, 100, ProgressBar.eProgressStyle.circles);
Bar.Device = this.Device;
bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.circles)
{
Device = Device
};
break;
case "lines":
Bar = new ProgressBar(0, 100, ProgressBar.eProgressStyle.lines);
Bar.Device = this.Device;
bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.lines)
{
Device = Device
};
break;
case "squaredlines":
Bar = new ProgressBar(0, 100, ProgressBar.eProgressStyle.squaredLines);
Bar.Device = this.Device;
bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.squaredLines)
{
Device = Device
};
break;
@ -79,7 +87,7 @@ namespace TelegramBotBaseTest.Tests
var sf = new Menu();
await this.NavigateTo(sf);
await NavigateTo(sf);
return;
@ -91,14 +99,14 @@ namespace TelegramBotBaseTest.Tests
//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++;
await Bar.Render(message);
bar.Value++;
await bar.Render(message);
Thread.Sleep(250);
}
@ -109,7 +117,7 @@ namespace TelegramBotBaseTest.Tests
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("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()));
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)
{
await this.Device.Send("Ciao from ProgressTest");
await Device.Send("Ciao from ProgressTest");
}
}

View File

@ -1,8 +1,4 @@
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.Form;
@ -10,38 +6,39 @@ namespace TelegramBotBaseTest.Tests.Register
{
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() == "")
return;
return Task.CompletedTask;
if (this.Firstname == null)
if (Firstname == null)
{
this.Firstname = message.MessageText;
return;
Firstname = message.MessageText;
return Task.CompletedTask;
}
if (this.Lastname == null)
if (Lastname == null)
{
this.Lastname = message.MessageText;
return;
Lastname = message.MessageText;
return Task.CompletedTask;
}
if (this.EMail == null)
if (EMail == null)
{
this.EMail = message.MessageText;
return;
EMail = message.MessageText;
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>();
@ -56,7 +53,7 @@ namespace TelegramBotBaseTest.Tests.Register
var start = new Start();
await this.NavigateTo(start);
await NavigateTo(start);
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;
}
if (this.Lastname == null)
if (Lastname == null)
{
await this.Device.Send("Please sent your lastname:");
await Device.Send("Please sent your lastname:");
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;
}
String s = "";
var s = "";
s += "Firstname: " + this.Firstname + "\r\n";
s += "Lastname: " + this.Lastname + "\r\n";
s += "E-Mail: " + this.EMail + "\r\n";
s += "Firstname: " + Firstname + "\r\n";
s += "Lastname: " + Lastname + "\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()));
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.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
using TelegramBotBaseTest.Tests.Register.Steps;
namespace TelegramBotBaseTest.Tests.Register
{
public class PerStep: AutoCleanForm
{
public async override Task Action(MessageResult message)
public override async Task Action(MessageResult message)
{
await message.ConfirmAction();
@ -19,29 +16,29 @@ namespace TelegramBotBaseTest.Tests.Register
{
case "start":
var step1 = new Steps.Step1();
var step1 = new Step1();
await this.NavigateTo(step1);
await NavigateTo(step1);
break;
case "back":
var start = new Start();
await this.NavigateTo(start);
await NavigateTo(start);
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("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.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
@ -10,12 +6,7 @@ namespace TelegramBotBaseTest.Tests.Register
{
public class Start : AutoCleanForm
{
public Start()
{
}
public async override Task Action(MessageResult message)
public override async Task Action(MessageResult message)
{
var call = message.GetData<CallbackData>();
@ -31,21 +22,21 @@ namespace TelegramBotBaseTest.Tests.Register
var form = new PerForm();
await this.NavigateTo(form);
await NavigateTo(form);
break;
case "step":
var step = new PerStep();
await this.NavigateTo(step);
await NavigateTo(step);
break;
case "backtodashboard":
var start = new Tests.Menu();
var start = new Menu();
await this.NavigateTo(start);
await NavigateTo(start);
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.2 Per Step", new CallbackData("a", "step").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;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TelegramBotBaseTest.Tests.Register.Steps
namespace TelegramBotBaseTest.Tests.Register.Steps
{
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.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks;
using TelegramBotBase.Args;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
@ -15,35 +11,38 @@ namespace TelegramBotBaseTest.Tests.Register.Steps
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)
return;
return Task.CompletedTask;
if (message.MessageText.Trim() == "")
return;
return Task.CompletedTask;
if (this.UserData.Firstname == null)
if (UserData.Firstname == null)
{
this.UserData.Firstname = message.MessageText;
return;
UserData.Firstname = message.MessageText;
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;
}
@ -51,9 +50,9 @@ namespace TelegramBotBaseTest.Tests.Register.Steps
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.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
@ -13,27 +9,29 @@ namespace TelegramBotBaseTest.Tests.Register.Steps
public Data UserData { get; set; }
public async override Task Load(MessageResult message)
public override Task Load(MessageResult message)
{
if (message.Handled)
return;
return Task.CompletedTask;
if (message.MessageText.Trim() == "")
return;
return Task.CompletedTask;
if (this.UserData.Lastname == null)
if (UserData.Lastname == null)
{
this.UserData.Lastname = message.MessageText;
return;
UserData.Lastname = message.MessageText;
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;
}
@ -41,9 +39,9 @@ namespace TelegramBotBaseTest.Tests.Register.Steps
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.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
@ -12,22 +8,24 @@ namespace TelegramBotBaseTest.Tests.Register.Steps
{
public Data UserData { get; set; }
public async override Task Load(MessageResult message)
public override Task Load(MessageResult message)
{
if (message.Handled)
return;
return Task.CompletedTask;
if (message.MessageText.Trim() == "")
return;
return Task.CompletedTask;
if (this.UserData.EMail == null)
if (UserData.EMail == null)
{
this.UserData.EMail = message.MessageText;
return;
UserData.EMail = message.MessageText;
return Task.CompletedTask;
}
return Task.CompletedTask;
}
public async override Task Action(MessageResult message)
public override async Task Action(MessageResult message)
{
await message.ConfirmAction();
@ -37,7 +35,7 @@ namespace TelegramBotBaseTest.Tests.Register.Steps
var start = new Start();
await this.NavigateTo(start);
await NavigateTo(start);
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;
}
message.Handled = true;
String s = "";
var s = "";
s += "Firstname: " + this.UserData.Firstname + "\r\n";
s += "Lastname: " + this.UserData.Lastname + "\r\n";
s += "E-Mail: " + this.UserData.EMail + "\r\n";
s += "Firstname: " + UserData.Firstname + "\r\n";
s += "Lastname: " + UserData.Lastname + "\r\n";
s += "E-Mail: " + UserData.EMail + "\r\n";
ButtonForm bf = new ButtonForm();
var bf = new ButtonForm();
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.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Base;
using TelegramBotBase.Enums;
using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests
@ -13,15 +11,15 @@ namespace TelegramBotBaseTest.Tests
public SimpleForm()
{
this.DeleteSide = TelegramBotBase.Enums.eDeleteSide.Both;
this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm;
DeleteSide = EDeleteSide.Both;
DeleteMode = EDeleteMode.OnLeavingForm;
this.Opened += SimpleForm_Opened;
Opened += SimpleForm_Opened;
}
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)
@ -36,13 +34,13 @@ namespace TelegramBotBaseTest.Tests
case "hi":
//Send him a simple message
await this.Device.Send("Hello you there !");
await Device.Send("Hello you there !");
break;
case "maybe":
//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;
@ -50,14 +48,14 @@ namespace TelegramBotBaseTest.Tests
case "ciao":
//Send him a simple message
await this.Device.Send("Ok, take care !");
await Device.Send("Ok, take care !");
break;
case "back":
var st = new Menu();
await this.NavigateTo(st);
await NavigateTo(st);
break;
}

View File

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

View File

@ -1,9 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot.Types;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
@ -11,24 +7,22 @@ namespace TelegramBotBaseTest.Tests
{
public class TestForm : FormBase
{
String LastMessage { get; set; }
private string LastMessage { get; set; }
public TestForm()
{
this.Opened += TestForm_Opened;
this.Closed += TestForm_Closed;
Opened += TestForm_Opened;
Closed += TestForm_Closed;
}
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)
{
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();
await this.NavigateTo(tf);
await NavigateTo(tf);
break;
@ -54,7 +48,7 @@ namespace TelegramBotBaseTest.Tests
if (message.UpdateData == null)
return;
this.LastMessage = message.Message.Text;
LastMessage = message.Message.Text;
break;
}
@ -68,7 +62,7 @@ namespace TelegramBotBaseTest.Tests
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.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot.Types;
using Telegram.Bot.Types.ReplyMarkups;
using Telegram.Bot.Types.Enums;
using TelegramBotBase.Base;
using TelegramBotBase.Extensions.Images;
using TelegramBotBase.Form;
@ -19,18 +14,18 @@ namespace TelegramBotBaseTest.Tests
public TestForm2()
{
this.Opened += TestForm2_Opened;
this.Closed += TestForm2_Closed;
Opened += TestForm2_Opened;
Closed += TestForm2_Closed;
}
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)
{
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();
await this.NavigateTo(tf);
await NavigateTo(tf);
}
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) =>
{
var fto = new TestForm2();
await this.NavigateTo(fto);
await NavigateTo(fto);
};
await this.NavigateTo(ad);
await NavigateTo(ad);
}
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) =>
{
@ -76,18 +71,18 @@ namespace TelegramBotBaseTest.Tests
await pd.NavigateTo(tf);
};
await this.NavigateTo(pd);
await NavigateTo(pd);
}
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) =>
{
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)
{
Bitmap bmp = new Bitmap(800, 600);
using (Graphics g = Graphics.FromImage(bmp))
var bmp = new Bitmap(800, 600);
using (var g = Graphics.FromImage(bmp))
{
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")));
@ -119,7 +114,7 @@ namespace TelegramBotBaseTest.Tests
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.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot.Types;
using TelegramBotBase.Sessions;
@ -13,9 +10,9 @@ namespace TelegramBotBase.Args
/// </summary>
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; }
@ -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.Parameters = Parameters;
this.OriginalMessage = Message;
this.DeviceId = DeviceId;
this.Device = Device;
this.Command = command;
this.Parameters = parameters;
OriginalMessage = message;
this.DeviceId = deviceId;
this.Device = device;
}
}

View File

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

View File

@ -1,15 +1,12 @@
using System;
using System.Collections.Generic;
using System.Text;
using TelegramBotBase.Controls.Hybrid;
using TelegramBotBase.Form;
namespace TelegramBotBase.Args
{
public class CheckedChangedEventArgs : EventArgs
{
/// <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.
/// </summary>
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;
this.Index = Index;
this.Checked = Checked;
Row = row;
this.Index = index;
this.Checked = @checked;
}

View File

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

View File

@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TelegramBotBase.Args
{
@ -12,7 +8,7 @@ namespace TelegramBotBase.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.Text;
namespace TelegramBotBase.Args
{
public class LoadStateEventArgs
{
public Dictionary<String,object> Values { get; set; }
public Dictionary<string,object> Values { get; set; }
public LoadStateEventArgs()
{
Values = new Dictionary<string, object>();
}
public List<String> Keys
{
get
{
return Values.Keys.ToList();
}
}
public List<string> Keys => Values.Keys.ToList();
public String Get(String key)
public string Get(string key)
{
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))
return i;
return 0;
}
public double GetDouble(String key)
public double GetDouble(string key)
{
double d = 0;
if (double.TryParse(Values[key].ToString(), out d))
@ -45,16 +37,16 @@ namespace TelegramBotBase.Args
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))
return b;
return false;
}
public object GetObject(String key)
public object GetObject(string key)
{
return Values[key];
}

View File

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

View File

@ -1,11 +1,4 @@
using System;
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 MessageDeletedEventArgs
{
@ -16,7 +9,7 @@ namespace TelegramBotBase.Args
public MessageDeletedEventArgs(int messageId)
{
this.MessageId = messageId;
MessageId = messageId;
}
}

View File

@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Sessions;
namespace TelegramBotBase.Base
@ -16,11 +12,11 @@ namespace TelegramBotBase.Base
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.Device = Device;
this.Message = message;
this.DeviceId = deviceId;
this.Device = device;
Message = message;
}

View File

@ -1,27 +1,16 @@
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
{
public class MessageReceivedEventArgs
{
public int MessageId
{
get
{
return this.Message.MessageId;
}
}
public int MessageId => Message.MessageId;
public Message Message { get; set; }
public MessageReceivedEventArgs(Message m)
{
this.Message = m;
Message = m;
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Sessions;
namespace TelegramBotBase.Args
@ -10,7 +6,7 @@ namespace TelegramBotBase.Args
public class SystemExceptionEventArgs : EventArgs
{
public String Command { get; set; }
public string Command { 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.DeviceId = DeviceId;
this.Device = Device;
this.Error = error;
this.Command = command;
this.DeviceId = deviceId;
this.Device = device;
Error = error;
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -1,8 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks;
using TelegramBotBase.Sessions;
namespace TelegramBotBase.Base
{
@ -11,17 +8,11 @@ namespace TelegramBotBase.Base
/// </summary>
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
{
get
{
return "#c" + this.ID.ToString();
}
}
public string ControlId => "#c" + Id;
/// <summary>
/// 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>
/// Will be called on a cleanup.
/// </summary>
/// <returns></returns>
public virtual async Task Cleanup()
public virtual Task Cleanup()
{
return Task.CompletedTask;
}
}

View File

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

View File

@ -2,7 +2,6 @@
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Args;
using TelegramBotBase.Base;
@ -27,7 +26,7 @@ namespace TelegramBotBase.Form
/// <summary>
/// has this formular already been disposed ?
/// </summary>
public bool IsDisposed { get; set; } = false;
public bool IsDisposed { get; set; }
public List<ControlBase> Controls { get; set; }
@ -35,33 +34,33 @@ namespace TelegramBotBase.Form
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()
{
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)
{
var handler = this.Events[__evInit]?.GetInvocationList().Cast<AsyncEventHandler<InitEventArgs>>();
var handler = Events[EvInit]?.GetInvocationList().Cast<AsyncEventHandler<InitEventArgs>>();
if (handler == null)
return;
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>
public event AsyncEventHandler<InitEventArgs> Init
{
add
{
this.Events.AddHandler(__evInit, value);
}
remove
{
this.Events.RemoveHandler(__evInit, value);
}
add => Events.AddHandler(EvInit, value);
remove => Events.RemoveHandler(EvInit, value);
}
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)
return;
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>
public event AsyncEventHandler<EventArgs> Opened
{
add
{
this.Events.AddHandler(__evOpened, value);
}
remove
{
this.Events.RemoveHandler(__evOpened, value);
}
add => Events.AddHandler(EvOpened, value);
remove => Events.RemoveHandler(EvOpened, value);
}
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)
return;
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>
public event AsyncEventHandler<EventArgs> Closed
{
add
{
this.Events.AddHandler(__evClosed, value);
}
remove
{
this.Events.RemoveHandler(__evClosed, value);
}
add => Events.AddHandler(EvClosed, value);
remove => Events.RemoveHandler(EvClosed, value);
}
/// <summary>
@ -146,9 +127,9 @@ namespace TelegramBotBase.Form
/// </summary>
/// <param name="message"></param>
/// <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
/// </summary>
/// <returns></returns>
public async Task CloseControls()
public Task CloseControls()
{
foreach (var b in this.Controls)
foreach (var b in Controls)
{
b.Cleanup().Wait();
}
return Task.CompletedTask;
}
public virtual async Task PreLoad(MessageResult message)
public virtual Task PreLoad(MessageResult message)
{
return Task.CompletedTask;
}
/// <summary>
@ -179,7 +162,7 @@ namespace TelegramBotBase.Form
//Looking for the control by id, if not listened, raise event for all
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)
{
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)
continue;
@ -201,9 +184,9 @@ namespace TelegramBotBase.Form
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
public virtual async Task Load(MessageResult message)
public virtual Task Load(MessageResult message)
{
return Task.CompletedTask;
}
/// <summary>
@ -211,9 +194,9 @@ namespace TelegramBotBase.Form
/// </summary>
/// <param name="message"></param>
/// <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
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)
{
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)
continue;
@ -252,9 +235,9 @@ namespace TelegramBotBase.Form
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
public virtual async Task Action(MessageResult message)
public virtual Task Action(MessageResult message)
{
return Task.CompletedTask;
}
/// <summary>
@ -262,9 +245,9 @@ namespace TelegramBotBase.Form
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
public virtual async Task SentData(DataResult message)
public virtual Task SentData(DataResult message)
{
return Task.CompletedTask;
}
/// <summary>
@ -274,7 +257,7 @@ namespace TelegramBotBase.Form
/// <returns></returns>
public virtual async Task RenderControls(MessageResult message)
{
foreach (var b in this.Controls)
foreach (var b in Controls)
{
if (!b.Enabled)
continue;
@ -288,9 +271,9 @@ namespace TelegramBotBase.Form
/// </summary>
/// <param name="message"></param>
/// <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>
public virtual async Task NavigateTo(FormBase newForm, params object[] args)
{
DeviceSession ds = this.Device;
var ds = Device;
if (ds == null)
return;
@ -311,11 +294,11 @@ namespace TelegramBotBase.Form
ds.PreviousForm = ds.ActiveForm;
ds.ActiveForm = newForm;
newForm.Client = this.Client;
newForm.Client = Client;
newForm.Device = ds;
//Notify prior to close
foreach (var b in this.Controls)
foreach (var b in Controls)
{
if (!b.Enabled)
continue;
@ -323,13 +306,13 @@ namespace TelegramBotBase.Form
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.OnOpened(new EventArgs());
await newForm.OnOpened(EventArgs.Empty);
}
/// <summary>
@ -339,7 +322,7 @@ namespace TelegramBotBase.Form
/// <returns></returns>
public virtual async Task OpenModal(ModalDialog newForm, params object[] args)
{
DeviceSession ds = this.Device;
var ds = Device;
if (ds == null)
return;
@ -359,7 +342,7 @@ namespace TelegramBotBase.Form
await CloseModal(newForm, parentForm);
};
foreach (var b in this.Controls)
foreach (var b in Controls)
{
if (!b.Enabled)
continue;
@ -369,14 +352,14 @@ namespace TelegramBotBase.Form
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)
return;
return Task.CompletedTask;
if (modalForm == null)
throw new Exception("No modal form");
@ -386,6 +369,7 @@ namespace TelegramBotBase.Form
ds.PreviousForm = ds.ActiveForm;
ds.ActiveForm = oldForm;
return Task.CompletedTask;
}
/// <summary>
@ -395,12 +379,12 @@ namespace TelegramBotBase.Form
public void AddControl(ControlBase control)
{
//Duplicate check
if (this.Controls.Contains(control))
if (Controls.Contains(control))
throw new ArgumentException("Control has been already added.");
control.ID = this.Controls.Count + 1;
control.Device = this.Device;
this.Controls.Add(control);
control.Id = Controls.Count + 1;
control.Device = Device;
Controls.Add(control);
control.Init();
}
@ -411,12 +395,12 @@ namespace TelegramBotBase.Form
/// <param name="control"></param>
public void RemoveControl(ControlBase control)
{
if (!this.Controls.Contains(control))
if (!Controls.Contains(control))
return;
control.Cleanup().Wait();
this.Controls.Remove(control);
Controls.Remove(control);
}
/// <summary>
@ -424,11 +408,11 @@ namespace TelegramBotBase.Form
/// </summary>
public void RemoveAllControls()
{
foreach(var c in this.Controls)
foreach(var c in Controls)
{
c.Cleanup().Wait();
this.Controls.Remove(c);
Controls.Remove(c);
}
}
@ -437,9 +421,9 @@ namespace TelegramBotBase.Form
/// </summary>
public void Dispose()
{
this.Client = null;
this.Device = null;
this.IsDisposed = true;
Client = null;
Device = null;
IsDisposed = true;
}
}
}

View File

@ -1,17 +1,14 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Telegram.Bot.Exceptions;
using Telegram.Bot;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Exceptions;
using Telegram.Bot.Extensions.Polling;
using Telegram.Bot.Types;
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; }
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();
@ -36,21 +33,21 @@ namespace TelegramBotBase.Base
private static object __evCallbackQuery = new object();
CancellationTokenSource __cancellationTokenSource;
private CancellationTokenSource _cancellationTokenSource;
public MessageClient(String APIKey)
public MessageClient(string apiKey)
{
this.APIKey = APIKey;
this.TelegramClient = new Telegram.Bot.TelegramBotClient(APIKey);
this.ApiKey = apiKey;
TelegramClient = new TelegramBotClient(apiKey);
Prepare();
}
public MessageClient(String APIKey, HttpClient proxy)
public MessageClient(string apiKey, HttpClient proxy)
{
this.APIKey = APIKey;
this.TelegramClient = new Telegram.Bot.TelegramBotClient(APIKey, proxy);
this.ApiKey = apiKey;
TelegramClient = new TelegramBotClient(apiKey, proxy);
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)
{
@ -71,7 +68,7 @@ namespace TelegramBotBase.Base
new HttpClientHandler { Proxy = proxy, UseProxy = true }
);
this.TelegramClient = new Telegram.Bot.TelegramBotClient(APIKey, httpClient);
TelegramClient = new TelegramBotClient(apiKey, httpClient);
Prepare();
}
@ -79,12 +76,12 @@ namespace TelegramBotBase.Base
/// <summary>
/// Initializes the client with a proxy
/// </summary>
/// <param name="APIKey"></param>
/// <param name="apiKey"></param>
/// <param name="proxyHost">i.e. 127.0.0.1</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);
@ -92,17 +89,17 @@ namespace TelegramBotBase.Base
new HttpClientHandler { Proxy = proxy, UseProxy = true }
);
this.TelegramClient = new Telegram.Bot.TelegramBotClient(APIKey, httpClient);
TelegramClient = new TelegramBotClient(apiKey, httpClient);
Prepare();
}
public MessageClient(String APIKey, Telegram.Bot.TelegramBotClient Client)
public MessageClient(string apiKey, TelegramBotClient client)
{
this.APIKey = APIKey;
this.TelegramClient = Client;
this.ApiKey = apiKey;
TelegramClient = client;
Prepare();
}
@ -110,7 +107,7 @@ namespace TelegramBotBase.Base
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()
{
__cancellationTokenSource = new CancellationTokenSource();
_cancellationTokenSource = new CancellationTokenSource();
var receiverOptions = new ReceiverOptions
{
AllowedUpdates = { } // receive all update types
};
var receiverOptions = new ReceiverOptions();
this.TelegramClient.StartReceiving(HandleUpdateAsync, HandleErrorAsync, receiverOptions, __cancellationTokenSource.Token);
TelegramClient.StartReceiving(HandleUpdateAsync, HandleErrorAsync, receiverOptions, _cancellationTokenSource.Token);
}
public void StopReceiving()
{
__cancellationTokenSource.Cancel();
_cancellationTokenSource.Cancel();
}
@ -143,9 +137,9 @@ namespace TelegramBotBase.Base
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
{
@ -159,9 +153,9 @@ namespace TelegramBotBase.Base
/// This will return the current list of bot commands.
/// </summary>
/// <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>
/// <param name="botcommands"></param>
/// <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>
/// This will delete the current list of bot commands.
/// </summary>
/// <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
{
add
{
this.__Events.AddHandler(__evOnMessageLoop, value);
}
remove
{
this.__Events.RemoveHandler(__evOnMessageLoop, value);
}
add => Events.AddHandler(EvOnMessageLoop, value);
remove => Events.RemoveHandler(EvOnMessageLoop, value);
}
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.Text;
using System.Threading.Tasks;
using Telegram.Bot;
using Newtonsoft.Json;
using Telegram.Bot.Types;
using TelegramBotBase.Sessions;
using Telegram.Bot.Types.Enums;
namespace TelegramBotBase.Base
{
public class MessageResult : ResultBase
{
public Telegram.Bot.Types.Update UpdateData { get; set; }
public Update UpdateData { get; set; }
/// <summary>
/// Returns the Device/ChatId
/// </summary>
public override long DeviceId
{
get
{
return this.UpdateData?.Message?.Chat?.Id
?? this.UpdateData?.EditedMessage?.Chat.Id
?? this.UpdateData?.CallbackQuery.Message?.Chat.Id
?? Device?.DeviceId
?? 0;
}
}
public override long DeviceId =>
UpdateData?.Message?.Chat?.Id
?? UpdateData?.EditedMessage?.Chat.Id
?? UpdateData?.CallbackQuery.Message?.Chat.Id
?? Device?.DeviceId
?? 0;
/// <summary>
/// The message id
/// </summary>
public new int MessageId
{
get
{
return this.UpdateData?.Message?.MessageId
?? this.Message?.MessageId
?? this.UpdateData?.CallbackQuery?.Message?.MessageId
?? 0;
}
}
public new int MessageId =>
UpdateData?.Message?.MessageId
?? Message?.MessageId
?? UpdateData?.CallbackQuery?.Message?.MessageId
?? 0;
public String Command
{
get
{
return this.UpdateData?.Message?.Text ?? "";
}
}
public string Command => UpdateData?.Message?.Text ?? "";
public String MessageText
{
get
{
return this.UpdateData?.Message?.Text ?? "";
}
}
public string MessageText => UpdateData?.Message?.Text ?? "";
public Telegram.Bot.Types.Enums.MessageType MessageType
{
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;
}
}
public MessageType MessageType => Message?.Type ?? MessageType.Unknown;
/// <summary>
/// Is this an action ? (i.e. button click)
/// </summary>
public bool IsAction
{
get
{
return (this.UpdateData.CallbackQuery != null);
}
}
public bool IsAction => (UpdateData.CallbackQuery != null);
/// <summary>
/// Is this a command ? Starts with a slash '/' and a command
/// </summary>
public bool IsBotCommand
{
get
{
return (this.MessageText.StartsWith("/"));
}
}
public bool IsBotCommand => (MessageText.StartsWith("/"));
/// <summary>
/// Returns a List of all parameters which has been sent with the command itself (i.e. /start 123 456 789 => 123,456,789)
/// </summary>
public List<String> BotCommandParameters
public List<string> BotCommandParameters
{
get
{
@ -112,21 +58,21 @@ namespace TelegramBotBase.Base
return new List<string>();
//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>
/// Returns just the command (i.e. /start 1 2 3 => /start)
/// </summary>
public String BotCommand
public string BotCommand
{
get
{
if (!IsBotCommand)
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 String RawData
{
get
{
return this.UpdateData?.CallbackQuery?.Data;
}
}
public string RawData => UpdateData?.CallbackQuery?.Data;
public T GetData<T>()
where T : class
@ -151,7 +91,7 @@ namespace TelegramBotBase.Base
T cd = null;
try
{
cd = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(this.RawData);
cd = JsonConvert.DeserializeObject<T>(RawData);
return cd;
}
@ -168,16 +108,16 @@ namespace TelegramBotBase.Base
/// </summary>
/// <param name="message"></param>
/// <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()
{
try
{
await base.DeleteMessage(this.MessageId);
await base.DeleteMessage(MessageId);
}
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.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot;
using Telegram.Bot.Types;
using TelegramBotBase.Sessions;
namespace TelegramBotBase.Base
@ -18,15 +16,9 @@ namespace TelegramBotBase.Base
public virtual long DeviceId { get; set; }
public int MessageId
{
get
{
return this.Message.MessageId;
}
}
public int MessageId => Message.MessageId;
public virtual Telegram.Bot.Types.Message Message { get; set; }
public virtual Message Message { get; set; }
/// <summary>
/// Deletes the current message
@ -35,7 +27,7 @@ namespace TelegramBotBase.Base
/// <returns></returns>
public virtual async Task DeleteMessage()
{
await DeleteMessage(this.MessageId);
await DeleteMessage(MessageId);
}
/// <summary>
@ -47,7 +39,7 @@ namespace TelegramBotBase.Base
{
try
{
await Device.Client.TelegramClient.DeleteMessageAsync(this.DeviceId, (messageId == -1 ? this.MessageId : messageId));
await Device.Client.TelegramClient.DeleteMessageAsync(DeviceId, (messageId == -1 ? MessageId : messageId));
}
catch
{

View File

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

View File

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

View File

@ -31,7 +31,7 @@ namespace TelegramBotBase
/// <summary>
/// Your TelegramBot APIKey
/// </summary>
public String APIKey { get; set; } = "";
public string ApiKey { get; set; } = "";
/// <summary>
/// List of all running/active sessions
@ -46,19 +46,19 @@ namespace TelegramBotBase
#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();
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
@ -81,22 +81,24 @@ namespace TelegramBotBase
/// <summary>
/// All internal used settings.
/// </summary>
public Dictionary<eSettings, uint> SystemSettings { get; private set; }
public Dictionary<ESettings, uint> SystemSettings { get; private set; }
public BotBase()
{
this.SystemSettings = new Dictionary<eSettings, uint>();
SystemSettings = new Dictionary<ESettings, uint>();
SetSetting(eSettings.MaxNumberOfRetries, 5);
SetSetting(eSettings.NavigationMaximum, 10);
SetSetting(eSettings.LogAllMessages, false);
SetSetting(eSettings.SkipAllMessages, false);
SetSetting(eSettings.SaveSessionsOnConsoleExit, false);
SetSetting(ESettings.MaxNumberOfRetries, 5);
SetSetting(ESettings.NavigationMaximum, 10);
SetSetting(ESettings.LogAllMessages, false);
SetSetting(ESettings.SkipAllMessages, false);
SetSetting(ESettings.SaveSessionsOnConsoleExit, false);
this.BotCommandScopes = new Dictionary<BotCommandScope, List<BotCommand>>();
BotCommandScopes = new Dictionary<BotCommandScope, List<BotCommand>>();
this.Sessions = new SessionBase();
this.Sessions.BotBase = this;
Sessions = new SessionBase
{
BotBase = this
};
}
@ -106,38 +108,38 @@ namespace TelegramBotBase
/// </summary>
public void Start()
{
if (this.Client == null)
if (Client == null)
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
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)
{
DeviceSession ds = this.Sessions.GetSession(e.DeviceId);
var ds = Sessions.GetSession(e.DeviceId);
if (ds == null)
{
ds = this.Sessions.StartSession(e.DeviceId).GetAwaiter().GetResult();
ds = Sessions.StartSession(e.DeviceId).GetAwaiter().GetResult();
e.Device = ds;
ds.LastMessage = e.RawData.Message;
@ -146,7 +148,7 @@ namespace TelegramBotBase
var mr = new MessageResult(e.RawData);
int i = 0;
var i = 0;
//Should formulars get navigated (allow maximum of 10, to dont get loops)
do
@ -160,7 +162,7 @@ namespace TelegramBotBase
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>
public void Stop()
{
if (this.Client == null)
if (Client == null)
return;
this.Client.MessageLoop -= Client_MessageLoop;
Client.MessageLoop -= Client_MessageLoop;
this.Client.StopReceiving();
Client.StopReceiving();
this.Sessions.SaveSessionStates();
Sessions.SaveSessionStates();
}
/// <summary>
@ -185,14 +187,14 @@ namespace TelegramBotBase
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
public async Task SentToAll(String message)
public async Task SentToAll(string message)
{
if (this.Client == null)
if (Client == null)
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>
/// This will invoke the full message loop for the device even when no "userevent" like message or action has been raised.
/// </summary>
/// <param name="DeviceId">Contains the device/chat id of the device to update.</param>
public async Task InvokeMessageLoop(long DeviceId)
/// <param name="deviceId">Contains the device/chat id of the device to update.</param>
public async Task InvokeMessageLoop(long deviceId)
{
var mr = new MessageResult();
mr.UpdateData = new Update()
var mr = new MessageResult
{
Message = new Message()
UpdateData = new Update()
{
Message = new Message()
}
};
await InvokeMessageLoop(DeviceId, mr);
await InvokeMessageLoop(deviceId, mr);
}
/// <summary>
/// This will invoke the full message loop for the device even when no "userevent" like message or action has been raised.
/// </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>
public async Task InvokeMessageLoop(long DeviceId, MessageResult e)
public async Task InvokeMessageLoop(long deviceId, MessageResult e)
{
try
{
DeviceSession ds = this.Sessions.GetSession(DeviceId);
var ds = Sessions.GetSession(deviceId);
e.Device = ds;
await MessageLoopFactory.MessageLoop(this, ds, new UpdateResult(e.UpdateData, ds), e);
@ -231,8 +234,8 @@ namespace TelegramBotBase
}
catch (Exception ex)
{
DeviceSession ds = this.Sessions.GetSession(DeviceId);
OnException(new SystemExceptionEventArgs(e.Message.Text, DeviceId, ds, ex));
var ds = Sessions.GetSession(deviceId);
OnException(new SystemExceptionEventArgs(e.Message.Text, deviceId, ds, ex));
}
}
@ -252,17 +255,17 @@ namespace TelegramBotBase
/// </summary>
public async Task UploadBotCommands()
{
foreach (var bs in this.BotCommandScopes)
foreach (var bs in BotCommandScopes)
{
if(bs.Value !=null)
{
await this.Client.SetBotCommands(bs.Value, bs.Key);
await Client.SetBotCommands(bs.Value, bs.Key);
}
else
{
await this.Client.DeleteBotCommands(bs.Key);
await Client.DeleteBotCommands(bs.Key);
}
}
}
@ -271,9 +274,9 @@ namespace TelegramBotBase
/// </summary>
/// <param name="command"></param>
/// <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))
return true;
@ -286,20 +289,20 @@ namespace TelegramBotBase
/// Could set a variety of settings to improve the bot handling.
/// </summary>
/// <param name="set"></param>
/// <param name="Value"></param>
public void SetSetting(eSettings set, uint Value)
/// <param name="value"></param>
public void SetSetting(ESettings set, uint value)
{
this.SystemSettings[set] = Value;
SystemSettings[set] = value;
}
/// <summary>
/// Could set a variety of settings to improve the bot handling.
/// </summary>
/// <param name="set"></param>
/// <param name="Value"></param>
public void SetSetting(eSettings set, bool Value)
/// <param name="value"></param>
public void SetSetting(ESettings set, bool value)
{
this.SystemSettings[set] = (Value ? 1u : 0u);
SystemSettings[set] = (value ? 1u : 0u);
}
/// <summary>
@ -308,12 +311,12 @@ namespace TelegramBotBase
/// <param name="set"></param>
/// <param name="defaultValue"></param>
/// <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 this.SystemSettings[set];
return SystemSettings[set];
}
/// <summary>
@ -322,12 +325,12 @@ namespace TelegramBotBase
/// <param name="set"></param>
/// <param name="defaultValue"></param>
/// <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 this.SystemSettings[set] == 0u ? false : true;
return SystemSettings[set] == 0u ? false : true;
}
#region "Events"
@ -338,19 +341,13 @@ namespace TelegramBotBase
public event EventHandler<SessionBeginEventArgs> SessionBegins
{
add
{
this.__Events.AddHandler(__evSessionBegins, value);
}
remove
{
this.__Events.RemoveHandler(__evSessionBegins, value);
}
add => _events.AddHandler(EvSessionBegins, value);
remove => _events.RemoveHandler(EvSessionBegins, value);
}
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>
public event EventHandler<MessageIncomeEventArgs> Message
{
add
{
this.__Events.AddHandler(__evMessage, value);
}
remove
{
this.__Events.RemoveHandler(__evMessage, value);
}
add => _events.AddHandler(EvMessage, value);
remove => _events.RemoveHandler(EvMessage, value);
}
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)
{
if (this.BotCommand != null)
if (BotCommand != null)
await BotCommand(this, e);
}
@ -392,19 +383,13 @@ namespace TelegramBotBase
/// </summary>
public event EventHandler<SystemExceptionEventArgs> Exception
{
add
{
this.__Events.AddHandler(__evException, value);
}
remove
{
this.__Events.RemoveHandler(__evException, value);
}
add => _events.AddHandler(EvException, value);
remove => _events.RemoveHandler(EvException, value);
}
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>
public event EventHandler<UnhandledCallEventArgs> UnhandledCall
{
add
{
this.__Events.AddHandler(__evUnhandledCall, value);
}
remove
{
this.__Events.RemoveHandler(__evUnhandledCall, value);
}
add => _events.AddHandler(EvUnhandledCall, value);
remove => _events.RemoveHandler(EvUnhandledCall, value);
}
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.Collections.Generic;
using System.Net.Http;
using System.Text;
using Telegram.Bot;
using Telegram.Bot.Types;
using TelegramBotBase.Base;
@ -11,29 +10,27 @@ using TelegramBotBase.Factories;
using TelegramBotBase.Form;
using TelegramBotBase.Interfaces;
using TelegramBotBase.Localizations;
using TelegramBotBase.MessageLoops;
using TelegramBotBase.States;
namespace TelegramBotBase.Builder
{
public class BotBaseBuilder : IAPIKeySelectionStage, IMessageLoopSelectionStage, IStartFormSelectionStage, IBuildingStage, INetworkingSelectionStage, IBotCommandsStage, ISessionSerializationStage, ILanguageSelectionStage
{
private string _apiKey;
String _apiKey = null;
private IStartFormFactory _factory;
IStartFormFactory _factory = null;
MessageClient _client = null;
private MessageClient _client;
/// <summary>
/// Contains different Botcommands for different areas.
/// </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;
IMessageLoopFactory _messageloopfactory = null;
private IMessageLoopFactory _messageLoopFactory;
private BotBaseBuilder()
{
@ -49,15 +46,15 @@ namespace TelegramBotBase.Builder
public IMessageLoopSelectionStage WithAPIKey(string apiKey)
{
this._apiKey = apiKey;
_apiKey = apiKey;
return this;
}
public IBuildingStage QuickStart(string apiKey, Type StartForm)
{
this._apiKey = apiKey;
this._factory = new Factories.DefaultStartFormFactory(StartForm);
_apiKey = apiKey;
_factory = new DefaultStartFormFactory(StartForm);
DefaultMessageLoop();
@ -76,8 +73,8 @@ namespace TelegramBotBase.Builder
public IBuildingStage QuickStart<T>(string apiKey)
where T : FormBase
{
this._apiKey = apiKey;
this._factory = new Factories.DefaultStartFormFactory(typeof(T));
_apiKey = apiKey;
_factory = new DefaultStartFormFactory(typeof(T));
DefaultMessageLoop();
@ -94,8 +91,8 @@ namespace TelegramBotBase.Builder
public IBuildingStage QuickStart(string apiKey, IStartFormFactory StartFormFactory)
{
this._apiKey = apiKey;
this._factory = StartFormFactory;
_apiKey = apiKey;
_factory = StartFormFactory;
DefaultMessageLoop();
@ -117,7 +114,7 @@ namespace TelegramBotBase.Builder
public IStartFormSelectionStage DefaultMessageLoop()
{
_messageloopfactory = new MessageLoops.FormBaseMessageLoop();
_messageLoopFactory = new FormBaseMessageLoop();
return this;
}
@ -125,7 +122,7 @@ namespace TelegramBotBase.Builder
public IStartFormSelectionStage MinimalMessageLoop()
{
_messageloopfactory = new MessageLoops.MinimalMessageLoop();
_messageLoopFactory = new MinimalMessageLoop();
return this;
}
@ -133,7 +130,7 @@ namespace TelegramBotBase.Builder
public IStartFormSelectionStage CustomMessageLoop(IMessageLoopFactory messageLoopClass)
{
_messageloopfactory = messageLoopClass;
_messageLoopFactory = messageLoopClass;
return this;
}
@ -141,7 +138,7 @@ namespace TelegramBotBase.Builder
public IStartFormSelectionStage CustomMessageLoop<T>()
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;
}
@ -153,33 +150,33 @@ namespace TelegramBotBase.Builder
public INetworkingSelectionStage WithStartForm(Type startFormClass)
{
this._factory = new Factories.DefaultStartFormFactory(startFormClass);
_factory = new DefaultStartFormFactory(startFormClass);
return this;
}
public INetworkingSelectionStage WithStartForm<T>()
where T : FormBase, new()
{
this._factory = new Factories.DefaultStartFormFactory(typeof(T));
_factory = new DefaultStartFormFactory(typeof(T));
return this;
}
public INetworkingSelectionStage WithServiceProvider(Type startFormClass, IServiceProvider serviceProvider)
{
this._factory = new ServiceProviderStartFormFactory(startFormClass, serviceProvider);
_factory = new ServiceProviderStartFormFactory(startFormClass, serviceProvider);
return this;
}
public INetworkingSelectionStage WithServiceProvider<T>(IServiceProvider serviceProvider)
where T : FormBase
{
this._factory = new ServiceProviderStartFormFactory<T>(serviceProvider);
_factory = new ServiceProviderStartFormFactory<T>(serviceProvider);
return this;
}
public INetworkingSelectionStage WithStartFormFactory(IStartFormFactory factory)
{
this._factory = factory;
_factory = factory;
return this;
}
@ -191,39 +188,64 @@ namespace TelegramBotBase.Builder
public IBotCommandsStage WithProxy(string proxyAddress)
{
var url = new Uri(proxyAddress);
_client = new MessageClient(_apiKey, url);
_client.TelegramClient.Timeout = new TimeSpan(0, 1, 0);
_client = new MessageClient(_apiKey, url)
{
TelegramClient =
{
Timeout = new TimeSpan(0, 1, 0)
}
};
return this;
}
public IBotCommandsStage NoProxy()
{
_client = new MessageClient(_apiKey);
_client.TelegramClient.Timeout = new TimeSpan(0, 1, 0);
_client = new MessageClient(_apiKey)
{
TelegramClient =
{
Timeout = new TimeSpan(0, 1, 0)
}
};
return this;
}
public IBotCommandsStage WithBotClient(TelegramBotClient tgclient)
{
_client = new MessageClient(_apiKey, tgclient);
_client.TelegramClient.Timeout = new TimeSpan(0, 1, 0);
_client = new MessageClient(_apiKey, tgclient)
{
TelegramClient =
{
Timeout = new TimeSpan(0, 1, 0)
}
};
return this;
}
public IBotCommandsStage WithHostAndPort(string proxyHost, int proxyPort)
{
_client = new MessageClient(_apiKey, proxyHost, proxyPort);
_client.TelegramClient.Timeout = new TimeSpan(0, 1, 0);
_client = new MessageClient(_apiKey, proxyHost, proxyPort)
{
TelegramClient =
{
Timeout = new TimeSpan(0, 1, 0)
}
};
return this;
}
public IBotCommandsStage WithHttpClient(HttpClient tgclient)
{
_client = new MessageClient(_apiKey, tgclient);
_client.TelegramClient.Timeout = new TimeSpan(0, 1, 0);
_client = new MessageClient(_apiKey, tgclient)
{
TelegramClient =
{
Timeout = new TimeSpan(0, 1, 0)
}
};
return this;
}
@ -240,7 +262,7 @@ namespace TelegramBotBase.Builder
public ISessionSerializationStage OnlyStart()
{
_BotCommandScopes.Start("Starts the bot");
BotCommandScopes.Start("Starts the bot");
return this;
@ -248,15 +270,15 @@ namespace TelegramBotBase.Builder
public ISessionSerializationStage DefaultCommands()
{
_BotCommandScopes.Start("Starts the bot");
_BotCommandScopes.Help("Should show you some help");
_BotCommandScopes.Settings("Should show you some settings");
BotCommandScopes.Start("Starts the bot");
BotCommandScopes.Help("Should show you some help");
BotCommandScopes.Settings("Should show you some settings");
return this;
}
public ISessionSerializationStage CustomCommands(Action<Dictionary<BotCommandScope, List<BotCommand>>> action)
{
action?.Invoke(_BotCommandScopes);
action?.Invoke(BotCommandScopes);
return this;
}
@ -272,26 +294,26 @@ namespace TelegramBotBase.Builder
public ILanguageSelectionStage UseSerialization(IStateMachine machine)
{
this._statemachine = machine;
_statemachine = machine;
return this;
}
public ILanguageSelectionStage UseJSON(string path)
{
this._statemachine = new JSONStateMachine(path);
_statemachine = new JsonStateMachine(path);
return this;
}
public ILanguageSelectionStage UseSimpleJSON(string path)
{
this._statemachine = new SimpleJSONStateMachine(path);
_statemachine = new SimpleJsonStateMachine(path);
return this;
}
public ILanguageSelectionStage UseXML(string path)
{
this._statemachine = new XMLStateMachine(path);
_statemachine = new XmlStateMachine(path);
return this;
}
@ -307,19 +329,19 @@ namespace TelegramBotBase.Builder
public IBuildingStage UseEnglish()
{
Localizations.Default.Language = new Localizations.English();
Default.Language = new English();
return this;
}
public IBuildingStage UseGerman()
{
Localizations.Default.Language = new Localizations.German();
Default.Language = new German();
return this;
}
public IBuildingStage Custom(Localization language)
{
Localizations.Default.Language = language;
Default.Language = language;
return this;
}
@ -328,20 +350,20 @@ namespace TelegramBotBase.Builder
public BotBase Build()
{
var bb = new BotBase();
bb.APIKey = _apiKey;
bb.StartFormFactory = _factory;
bb.Client = _client;
var bb = new BotBase
{
ApiKey = _apiKey,
StartFormFactory = _factory,
Client = _client
};
bb.Sessions.Client = bb.Client;
bb.BotCommandScopes = _BotCommandScopes;
bb.BotCommandScopes = BotCommandScopes;
bb.StateMachine = _statemachine;
bb.MessageLoopFactory = _messageloopfactory;
bb.MessageLoopFactory = _messageLoopFactory;
bb.MessageLoopFactory.UnhandledCall += bb.MessageLoopFactory_UnhandledCall;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,8 +1,5 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Telegram.Bot.Types;
namespace TelegramBotBase.Commands
@ -15,7 +12,7 @@ namespace TelegramBotBase.Commands
/// <param name="cmds"></param>
/// <param name="command"></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)
{
@ -26,11 +23,11 @@ namespace TelegramBotBase.Commands
if (item.Value != null)
{
item.Value.Add(new BotCommand() { Command = command, Description = description });
item.Value.Add(new BotCommand { Command = command, Description = description });
}
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>
/// <param name="cmds"></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>
/// Adding the default /help command with a description.
/// </summary>
/// <param name="cmds"></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>
/// Adding the default /settings command with a description.
/// </summary>
/// <param name="cmds"></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>
/// Clears all default commands.
/// </summary>
/// <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>
/// Clears all commands of a specific device.
/// </summary>
/// <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>
/// Adding a chat command with a description.
@ -98,7 +95,7 @@ namespace TelegramBotBase.Commands
/// <param name="cmds"></param>
/// <param name="command"></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>
/// Adding a group command with a description.
@ -106,7 +103,7 @@ namespace TelegramBotBase.Commands
/// <param name="cmds"></param>
/// <param name="command"></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>
/// Clears all group commands.
@ -120,7 +117,7 @@ namespace TelegramBotBase.Commands
/// <param name="cmds"></param>
/// <param name="command"></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>
/// Clears all group admin commands.
@ -134,7 +131,7 @@ namespace TelegramBotBase.Commands
/// <param name="cmds"></param>
/// <param name="command"></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>
/// Clears all private commands.

View File

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

View File

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

View File

@ -1,10 +1,7 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using TelegramBotBase.Form;
namespace TelegramBotBase.Controls.Hybrid
@ -12,8 +9,7 @@ namespace TelegramBotBase.Controls.Hybrid
[DebuggerDisplay("{Count} columns")]
public class ButtonRow
{
List<ButtonBase> __buttons = new List<ButtonBase>();
private List<ButtonBase> _buttons = new List<ButtonBase>();
public ButtonRow()
{
@ -23,59 +19,47 @@ namespace TelegramBotBase.Controls.Hybrid
public ButtonRow(params ButtonBase[] buttons)
{
__buttons = buttons.ToList();
_buttons = buttons.ToList();
}
public ButtonBase this[int index]
{
get
{
return __buttons[index];
}
}
public ButtonBase this[int index] => _buttons[index];
public int Count
{
get
{
return __buttons.Count;
}
}
public int Count => _buttons.Count;
public void Add(ButtonBase button)
{
__buttons.Add(button);
_buttons.Add(button);
}
public void AddRange(ButtonBase button)
{
__buttons.Add(button);
_buttons.Add(button);
}
public void Insert(int index, ButtonBase button)
{
__buttons.Insert(index, button);
_buttons.Insert(index, button);
}
public IEnumerator<ButtonBase> GetEnumerator()
{
return __buttons.GetEnumerator();
return _buttons.GetEnumerator();
}
public ButtonBase[] ToArray()
{
return __buttons.ToArray();
return _buttons.ToArray();
}
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))
return true;
@ -92,9 +76,9 @@ namespace TelegramBotBase.Controls.Hybrid
/// <param name="text"></param>
/// <param name="useText"></param>
/// <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))
return b;
@ -106,7 +90,7 @@ namespace TelegramBotBase.Controls.Hybrid
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.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.SymbolStore;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types.ReplyMarkups;
using TelegramBotBase.Args;
using TelegramBotBase.Base;
using TelegramBotBase.Datasources;
using TelegramBotBase.DataSources;
using TelegramBotBase.Enums;
using TelegramBotBase.Exceptions;
using TelegramBotBase.Form;
using TelegramBotBase.Localizations;
using static TelegramBotBase.Base.Async;
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.")]
public ButtonForm ButtonsForm
{
get
{
return DataSource.ButtonForm;
}
set
{
DataSource = new ButtonFormDataSource(value);
}
get => DataSource.ButtonForm;
set => DataSource = new ButtonFormDataSource(value);
}
/// <summary>
@ -51,7 +44,7 @@ namespace TelegramBotBase.Controls.Hybrid
/// </summary>
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; }
@ -91,25 +84,25 @@ namespace TelegramBotBase.Controls.Hybrid
//public String SearchQuery { get; set; }
public eNavigationBarVisibility NavigationBarVisibility { get; set; } = eNavigationBarVisibility.always;
public ENavigationBarVisibility NavigationBarVisibility { get; set; } = ENavigationBarVisibility.always;
/// <summary>
/// Index of the current page
/// </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 CheckedIconLabel { get; set; } = "✅";
public string CheckedIconLabel { get; set; } = "✅";
public String UncheckedIconLabel { get; set; } = "◻️";
public string UncheckedIconLabel { get; set; } = "◻️";
/// <summary>
/// Layout of the buttons which should be displayed always on top.
@ -124,97 +117,82 @@ namespace TelegramBotBase.Controls.Hybrid
/// <summary>
/// Defines which type of Button Keyboard should be rendered.
/// </summary>
public eKeyboardType KeyboardType
public EKeyboardType KeyboardType
{
get
{
return m_eKeyboardType;
}
get => _mEKeyboardType;
set
{
if (m_eKeyboardType != value)
if (_mEKeyboardType != value)
{
this.RenderNecessary = true;
_renderNecessary = true;
Cleanup().Wait();
m_eKeyboardType = value;
_mEKeyboardType = value;
}
}
}
private eKeyboardType m_eKeyboardType = eKeyboardType.ReplyKeyboard;
private EKeyboardType _mEKeyboardType = EKeyboardType.ReplyKeyboard;
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)
{
this.DataSource = new ButtonFormDataSource(form);
DataSource = new ButtonFormDataSource(form);
}
public event AsyncEventHandler<ButtonClickedEventArgs> ButtonClicked
{
add
{
this.Events.AddHandler(__evButtonClicked, value);
}
remove
{
this.Events.RemoveHandler(__evButtonClicked, value);
}
add => _events.AddHandler(EvButtonClicked, value);
remove => _events.RemoveHandler(EvButtonClicked, value);
}
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)
return;
foreach (var h in handler)
{
await Async.InvokeAllAsync<ButtonClickedEventArgs>(h, this, e);
await h.InvokeAllAsync(this, e);
}
}
public event AsyncEventHandler<CheckedChangedEventArgs> CheckedChanged
{
add
{
this.Events.AddHandler(__evCheckedChanged, value);
}
remove
{
this.Events.RemoveHandler(__evCheckedChanged, value);
}
add => _events.AddHandler(EvCheckedChanged, value);
remove => _events.RemoveHandler(EvCheckedChanged, value);
}
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)
return;
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;
if (!result.IsFirstHandler)
@ -225,7 +203,7 @@ namespace TelegramBotBase.Controls.Hybrid
var matches = new List<ButtonRow>();
ButtonRow match = null;
int index = -1;
var index = -1;
if (HeadLayoutButtonRow?.Matches(result.MessageText) ?? false)
{
@ -260,36 +238,36 @@ namespace TelegramBotBase.Controls.Hybrid
//Remove button click message
if (this.DeleteReplyMessage)
if (DeleteReplyMessage)
await Device.DeleteMessage(result.MessageId);
if (match == null)
{
if (result.MessageText == PreviousPageLabel)
{
if (this.CurrentPageIndex > 0)
this.CurrentPageIndex--;
if (CurrentPageIndex > 0)
CurrentPageIndex--;
this.Updated();
Updated();
}
else if (result.MessageText == NextPageLabel)
{
if (this.CurrentPageIndex < this.PageCount - 1)
this.CurrentPageIndex++;
if (CurrentPageIndex < PageCount - 1)
CurrentPageIndex++;
this.Updated();
Updated();
}
else if (result.MessageText.EndsWith(CheckedIconLabel))
{
var s = result.MessageText.Split(' ', '.');
index = int.Parse(s[0]) - 1;
if (!this.CheckedRows.Contains(index))
if (!CheckedRows.Contains(index))
return;
this.CheckedRows.Remove(index);
CheckedRows.Remove(index);
this.Updated();
Updated();
await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, false));
@ -299,13 +277,13 @@ namespace TelegramBotBase.Controls.Hybrid
var s = result.MessageText.Split(' ', '.');
index = int.Parse(s[0]) - 1;
if (this.CheckedRows.Contains(index))
if (CheckedRows.Contains(index))
return;
this.CheckedRows.Add(index);
CheckedRows.Add(index);
this.Updated();
Updated();
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)
return;
@ -364,13 +342,13 @@ namespace TelegramBotBase.Controls.Hybrid
return;
//Find clicked button depending on Text or Value (depending on markup type)
if (this.KeyboardType != eKeyboardType.InlineKeyBoard)
if (KeyboardType != EKeyboardType.InlineKeyBoard)
return;
await result.ConfirmAction(this.ConfirmationText ?? "");
await result.ConfirmAction(ConfirmationText ?? "");
ButtonRow match = null;
int index = -1;
var index = -1;
if (HeadLayoutButtonRow?.Matches(result.RawData, false) ?? false)
{
@ -422,18 +400,18 @@ namespace TelegramBotBase.Controls.Hybrid
{
case "$previous$":
if (this.CurrentPageIndex > 0)
this.CurrentPageIndex--;
if (CurrentPageIndex > 0)
CurrentPageIndex--;
this.Updated();
Updated();
break;
case "$next$":
if (this.CurrentPageIndex < this.PageCount - 1)
this.CurrentPageIndex++;
if (CurrentPageIndex < PageCount - 1)
CurrentPageIndex++;
this.Updated();
Updated();
break;
@ -448,11 +426,11 @@ namespace TelegramBotBase.Controls.Hybrid
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));
}
@ -463,11 +441,11 @@ namespace TelegramBotBase.Controls.Hybrid
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));
}
@ -487,51 +465,51 @@ namespace TelegramBotBase.Controls.Hybrid
/// </summary>
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)
{
throw new MaximumColsException() { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols };
throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols };
}
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)
{
throw new MaximumColsException() { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols };
throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols };
}
break;
}
}
public async override Task Render(MessageResult result)
public override async Task Render(MessageResult result)
{
if (!this.RenderNecessary)
if (!_renderNecessary)
return;
//Check for rows and column limits
CheckGrid();
this.RenderNecessary = false;
_renderNecessary = false;
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 != "")
//{
@ -542,7 +520,7 @@ namespace TelegramBotBase.Controls.Hybrid
//form = form.Duplicate();
//}
if (this.EnablePaging)
if (EnablePaging)
{
IntegratePagingView(form);
}
@ -551,34 +529,34 @@ namespace TelegramBotBase.Controls.Hybrid
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
{
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.
case eKeyboardType.ReplyKeyboard:
case EKeyboardType.ReplyKeyboard:
if (form.Count == 0)
{
if (this.MessageId != null)
if (MessageId != null)
{
await this.Device.HideReplyKeyboard();
this.MessageId = null;
await Device.HideReplyKeyboard();
MessageId = null;
}
return;
@ -589,25 +567,25 @@ namespace TelegramBotBase.Controls.Hybrid
var rkm = (ReplyKeyboardMarkup)form;
rkm.ResizeKeyboard = this.ResizeKeyboard;
rkm.OneTimeKeyboard = this.OneTimeKeyboard;
m = await this.Device.Send(this.Title, rkm, disableNotification: true, parseMode: MessageParseMode, MarkdownV2AutoEscape: false);
rkm.ResizeKeyboard = ResizeKeyboard;
rkm.OneTimeKeyboard = OneTimeKeyboard;
m = await Device.Send(Title, rkm, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false);
//Prevent flicker of keyboard
if (this.DeletePreviousMessage && this.MessageId != null)
await this.Device.DeleteMessage(this.MessageId.Value);
if (DeletePreviousMessage && MessageId != null)
await Device.DeleteMessage(MessageId.Value);
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
{
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;
@ -615,7 +593,7 @@ namespace TelegramBotBase.Controls.Hybrid
if (m != null)
{
this.MessageId = m.MessageId;
MessageId = m.MessageId;
}
@ -623,23 +601,23 @@ namespace TelegramBotBase.Controls.Hybrid
private void IntegratePagingView(ButtonForm dataForm)
{
//No Items
//No Items
if (dataForm.Rows == 0)
{
dataForm.AddButtonRow(new ButtonBase(NoItemsLabel, "$"));
}
ButtonForm bf = new ButtonForm();
var bf = new ButtonForm();
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(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$"));
@ -652,30 +630,30 @@ namespace TelegramBotBase.Controls.Hybrid
private ButtonForm PrepareCheckableLayout(ButtonForm dataForm)
{
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)
// break;
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.
if (this.KeyboardType == eKeyboardType.ReplyKeyboard)
if (KeyboardType == EKeyboardType.ReplyKeyboard)
{
s = $"{it + 1}. " + s;
}
if (CheckedRows.Contains(it))
{
r.Insert(0, new ButtonBase(s, "uncheck$" + it.ToString()));
r.Insert(0, new ButtonBase(s, "uncheck$" + it));
}
else
{
r.Insert(0, new ButtonBase(s, "check$" + it.ToString()));
r.Insert(0, new ButtonBase(s, "check$" + it));
}
bf.AddButtonRow(r);
@ -688,12 +666,12 @@ namespace TelegramBotBase.Controls.Hybrid
{
get
{
if (this.KeyboardType == eKeyboardType.InlineKeyBoard && TotalRows > Constants.Telegram.MaxInlineKeyBoardRows)
if (KeyboardType == EKeyboardType.InlineKeyBoard && TotalRows > Constants.Telegram.MaxInlineKeyBoardRows)
{
return true;
}
if (this.KeyboardType == eKeyboardType.ReplyKeyboard && TotalRows > Constants.Telegram.MaxReplyKeyboardRows)
if (KeyboardType == EKeyboardType.ReplyKeyboard && TotalRows > Constants.Telegram.MaxReplyKeyboardRows)
{
return true;
}
@ -706,7 +684,7 @@ namespace TelegramBotBase.Controls.Hybrid
{
get
{
if (this.NavigationBarVisibility == eNavigationBarVisibility.always | (this.NavigationBarVisibility == eNavigationBarVisibility.auto && PagingNecessary))
if (NavigationBarVisibility == ENavigationBarVisibility.always | (NavigationBarVisibility == ENavigationBarVisibility.auto && PagingNecessary))
{
return true;
}
@ -722,30 +700,19 @@ namespace TelegramBotBase.Controls.Hybrid
{
get
{
switch (this.KeyboardType)
return KeyboardType switch
{
case eKeyboardType.InlineKeyBoard:
return Constants.Telegram.MaxInlineKeyBoardRows;
case eKeyboardType.ReplyKeyboard:
return Constants.Telegram.MaxReplyKeyboardRows;
default:
return 0;
}
EKeyboardType.InlineKeyBoard => Constants.Telegram.MaxInlineKeyBoardRows,
EKeyboardType.ReplyKeyboard => Constants.Telegram.MaxReplyKeyboardRows,
_ => 0
};
}
}
/// <summary>
/// Returns the number of all rows (layout + navigation + content);
/// </summary>
public int TotalRows
{
get
{
return this.LayoutRows + DataSource.RowCount;
}
}
public int TotalRows => LayoutRows + DataSource.RowCount;
/// <summary>
@ -755,15 +722,15 @@ namespace TelegramBotBase.Controls.Hybrid
{
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;
if (this.HeadLayoutButtonRow != null && this.HeadLayoutButtonRow.Count > 0)
if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0)
layoutRows++;
if (this.SubHeadLayoutButtonRow != null && this.SubHeadLayoutButtonRow.Count > 0)
if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0)
layoutRows++;
return layoutRows;
@ -773,13 +740,7 @@ namespace TelegramBotBase.Controls.Hybrid
/// <summary>
/// Returns the number of item rows per page.
/// </summary>
public int ItemRowsPerPage
{
get
{
return this.MaximumRow - this.LayoutRows;
}
}
public int ItemRowsPerPage => MaximumRow - LayoutRows;
public int PageCount
{
@ -790,7 +751,7 @@ namespace TelegramBotBase.Controls.Hybrid
//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 != "")
//{
@ -800,28 +761,30 @@ namespace TelegramBotBase.Controls.Hybrid
if (max == 0)
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
if (!FormClose)
if (!formClose)
{
this.Updated();
Updated();
}
return Task.CompletedTask;
}
public List<ButtonBase> CheckedItems
{
get
{
List<ButtonBase> lst = new List<ButtonBase>();
var lst = new List<ButtonBase>();
foreach (var c in CheckedRows)
{
lst.Add(this.ButtonsForm[c][0]);
lst.Add(ButtonsForm[c][0]);
}
return lst;
@ -834,31 +797,31 @@ namespace TelegramBotBase.Controls.Hybrid
/// </summary>
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;
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;
case eKeyboardType.ReplyKeyboard:
case EKeyboardType.ReplyKeyboard:
if (this.HideKeyboardOnCleanup)
if (HideKeyboardOnCleanup)
{
await this.Device.HideReplyKeyboard();
await Device.HideReplyKeyboard();
}
this.MessageId = null;
MessageId = null;
break;
}

View File

@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Threading.Tasks;
using TelegramBotBase.Args;
using TelegramBotBase.Base;
@ -13,33 +9,30 @@ namespace TelegramBotBase.Controls.Hybrid
/// <summary>
/// This Control is for having a basic form content switching control.
/// </summary>
public abstract class MultiView : Base.ControlBase
public abstract class MultiView : ControlBase
{
/// <summary>
/// Index of the current View.
/// </summary>
public int SelectedViewIndex
{
get
{
return m_iSelectedViewIndex;
}
get => _mISelectedViewIndex;
set
{
m_iSelectedViewIndex = value;
_mISelectedViewIndex = value;
//Already rendered? Re-Render
if (_Rendered)
if (_rendered)
ForceRender().Wait();
}
}
private int m_iSelectedViewIndex = 0;
private int _mISelectedViewIndex;
/// <summary>
/// Hold if the View has been rendered already.
/// </summary>
private bool _Rendered = false;
private bool _rendered;
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)))
return;
return Task.CompletedTask;
this.Messages.Add(e.MessageId);
Messages.Add(e.MessageId);
return Task.CompletedTask;
}
public override void Init()
@ -63,23 +57,24 @@ namespace TelegramBotBase.Controls.Hybrid
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)
{
//When already rendered, skip rendering
if (_Rendered)
if (_rendered)
return;
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.
/// </summary>
/// <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>();
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);
this.Messages.Clear();
Messages.Clear();
}
@ -116,9 +110,9 @@ namespace TelegramBotBase.Controls.Hybrid
{
await CleanUpView();
await RenderView(new RenderViewEventArgs(this.SelectedViewIndex));
await RenderView(new RenderViewEventArgs(SelectedViewIndex));
_Rendered = true;
_rendered = true;
}
public override async Task Cleanup()

View File

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