c# Cannot create InlineKeyboardButton - c#

I am creating a telegram bot, but I am unable to create any InlineKeyboardButton objects.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Telegram.Bot.Types.InlineKeyboardButtons;
namespace BuildAutomation.Controllers
{
public class Test
{
public TestMethod()
{
var none = new InlineKeyboardButton("No", "build|no");
var yes = "Yes";
var betaControl = new InlineKeyboardButton(yes, "build|betacontrol");
var betaNode = new InlineKeyboardButton(yes, "build|betanode");
var betaBoth = new InlineKeyboardButton(yes, "build|betaboth");
InlineKeyboardMarkup menu;
menu = new InlineKeyboardMarkup(new[] { betaBoth, none });
}
}
}
I keep getting the error 'Cannot create an instance of the abstract class or interface 'InlineKeyboardButton'. I realize that InlineKeyboardButton is an abstract class, but i see many examples creating an object of InlineKeyboardButton.
Did I miss something?
example 1
example 2
example 3

Instantiation of InlineKeyboardButton directly was correct in previous versions.
There is a new commit for about one month ago which indicates that InlineKeyboardButton is made abstract from then on. You must use derived classes instead. InlineKeyboardUrlButton, InlineKeyboardPayButton and etc. are all derived from InlineKeyboardButton.
It seems that the examples' repository is not updated yet.
Check this link for more details about the mentioned commit:
https://github.com/TelegramBots/telegram.bot/commit/ddaa8b74e3ab5eab632dbe2e8916c2fe87b114a3

Use InlineKeyboardCallbackButton Example, InlineKeyboardCallbackButton("Yes", "CallBackData") instead of InlineKeyboardButton("Yes", "CallbackData")

You couldn't create a new instance of abstraction class. So use sample bellow
var KeyboardButons = new InlineKeyboardButton[][]
{
new InlineKeyboardButton[]
{
InlineKeyboardButton.WithCallbackData("سفارش", callbackQueryData) ,
InlineKeyboardButton.WithCallbackData("بازگشت", "return")
}
};
var replyMarkup = new InlineKeyboardMarkup()
{
InlineKeyboard = KeyboardButons
};

Related

How do I set up an environment to solve LeetCode problems in Visual Studio? C#

When making the file, I am thinking of selecting a console application. But which target framework do I choose? Is this incorrect? Also, I am having trouble figuring out how to make a method in the class Program that is able to be called in the Main method. Can someone give me some advice?
one thing you can do is using interface to keep your code clean; for example :
you create an interface like this:
public interface IQuestionSolving
{
public void Solution();
}
you create some question class :
public class Question1 : IQuestionSolving
{
public void Solution()
{
}
}
and you use it like this :
static void Main(string[] args)
{
IQuestionSolving solve = new Question1();
solve.Solution();
Console.ReadKey();
}
now each time you solve a question you need to change
IQuestionSolving solve = new Question1();
to
IQuestionSolving solve = new Question2(); // 2 3 4 .. etc
you can extract your project as template so you dont have to do this each time .
or you can just use one solution and many classes .
This will get you started with Visual Studio:
Create a new console project - use the latest version of C#, which is probably what VS will "suggest" to you. Currently that's .NET 6 or .NET 7
A modern (net 6 or later) console app lets you start writing code immediately. You could create a method and then call the method right in this little Program.cs file that you start out with. However, I would probably do the following instead:
a) Create a new class for your "problem"
b) In that class create a method that solves the problem.
c) In your Program.cs add a using statement to use the namespace that your new class uses
d) In your program.cs instantiate that class and call its method/test its method
Here is an example:
Program.cs
using LeetCodeProject;
var solver = new Problem001_CalculateSquareRoot();
var solution = solver.calculate_square_root(8);
Console.WriteLine(solution);
Console.WriteLine("Press any key...");
Console.ReadKey();
Problem001_CalculateSquareRoot.cs (solves one leetcode problem)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LeetCodeProject
{
public class Problem001_CalculateSquareRoot
{
public double calculate_square_root(int number)
{
double root = 1;
int i = 0;
while (true)
{
i = i + 1;
root = (number / root + root) / 2;
if (i == number + 1)
{
break;
}
}
return root;
}
}
}
Now you can just add new classes for each problem, and as you work on them just edit Program.cs to create the class you are currently working with and calls its solution methods.
I can (and would - and actually have, in similar cases) implement an interface for this, but the goal here is not to get into OO design principles, but just to get you started so you can get to work on the leetcode problems...once you have a few done you can start thinking about better organization of the code.

DLR: Do i really need code generation here?

spent some time again with the scripting interface of my app.
i guess i now have an advanced dlr problem here.
I have a python script
I have an .NET object [o1]
I call a method on the python script from .NET via Iron Python.
The python code creates an object [o2]
The python code calls an method on object [o1] passing [o2] as an argument (Via subclassing DynamicMetaObject)
In the .NET code of the o1-method i want to dynamically call methods on o2
For example i could do that via
((dynamic)o2).FuncInPythonScript
so far so good thats all working.
.NET calls Python (step 3)
Python calls back .NET (step 5)
So i have a basic biderectional control flow between .NET and Python.
We go further:
In the [o1]-method I use LanguageContext.GetMemberNames on [o2]
I wanna call these members somehow via reflection or expressions.
Meaning i dont wanna use the dynamic keyword as in step 7.
Instead somehow call the methods via reflection.
Problem is:
a) I do not know how to get the RuntimeType of the Python-Type, meaning i have no System.Reflection.MethodInfo so i stuck here
b) I try to use LanguageContext.CreateCallBinder and MetaObject.BindInvokeMember so i should have the method 'FuncInPythonScript' bound
But then i'm stuck in how to finally call the bound method.
I see i could use code generation to just generate the code as in step 7, just with the member names from step 8.
But is that really necessary?
I do not see wether approach a) or b) might work or maybe there is somthing i did not think of.
Please do not answer with basic "How do i invoke a python method from .NET" hints.
That is done in steps 1-7 and i have no problem doing this. It's really an advanced problem.
namespace DynamicMetaObjectTest
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Dynamic;
using System.Linq.Expressions;
using Microsoft.Scripting.Hosting;
using Microsoft.Scripting.Hosting.Providers;
class Program
{
internal sealed class CDotNetObject : IDynamicMetaObjectProvider
{
DynamicMetaObject IDynamicMetaObjectProvider.GetMetaObject(Expression aExp)
{
return new CInvoker(this, aExp);
}
private sealed class CInvoker : DynamicMetaObject
{
internal CInvoker(CDotNetObject aGws, Expression aExp) : base(aExp, BindingRestrictions.Empty, aGws)
{
this.DotNetObject = aGws;
}
private readonly CDotNetObject DotNetObject;
public override DynamicMetaObject BindGetMember(GetMemberBinder binder)
{
var aMethodInfo = this.GetType().GetMethod("GetSetResultDelegate");
var aExp = Expression.Call(Expression.Constant(this), aMethodInfo);
var aRestrictions = BindingRestrictions.GetTypeRestriction(this.Expression, this.LimitType);
var aMetaObject = new DynamicMetaObject(aExp, aRestrictions);
return aMetaObject;
}
public Action<object> GetSetResultDelegate()
{
return this.DotNetObject.SetResultProvider;
}
}
public void SetResultProvider(object aPythonObject_O2)
{
var aResult = ((dynamic)aPythonObject_O2).GetResult(); // this is for noobs. ;-)
var aMetaObjectProvider = (IDynamicMetaObjectProvider)aPythonObject_O2;
var aMetaObject = aMetaObjectProvider.GetMetaObject(Expression.Constant(aPythonObject_O2));
var aLanguageContext = HostingHelpers.GetLanguageContext(gScriptEngine);
var aMemberNames = aLanguageContext.GetMemberNames(aPythonObject_O2);
var aNonSystemMembers = from aMemberName in aMemberNames where !aMemberName.StartsWith("__") select aMemberName;
foreach (var aMemberName in aNonSystemMembers)
{
Console.WriteLine("Getting function result from Python script: " + aMemberName);
// Now problem:
// P1) How to determine wether its an function or an member variable?
// P2) How to invoke the method respectively get the value of the member variable?
// Your turn ;-)
// some of my failures:
{ // does not work:
//var aVar1Binder = aLanguageContext.CreateGetMemberBinder("GetVar1", false);
//var aVar1Bound = aMetaObject.BindGetMember(aVar1Binder);
//var aCallInfo = new CallInfo(0 , new string[]{});
//var aInvokeBinder = aLanguageContext.CreateCallBinder("GetVar1", false, aCallInfo);
//var aInvokeBound = aMetaObject.BindInvokeMember(aInvokeBinder, new DynamicMetaObject[]{ aVar1Bound});
////var aInvokeExp = Expression.Invoke(Expression.Constant(aInvokeBound), new Expression[] { });
}
{ // does not work
//var aExpandable = (IronPython.Runtime.Binding.IPythonExpandable)aMetaObject;
}
}
}
}
static ScriptEngine gScriptEngine;
static void Main(string[] args)
{
var aScriptRuntime = IronPython.Hosting.Python.CreateRuntime();
// That's the python script from step 1:
var aCode = "class CustomView(object) :" + Environment.NewLine +
"\tdef GetResult(self) :" + Environment.NewLine +
"\t\treturn 42;" + Environment.NewLine + // cuz 42 is the answer to everything ;-)
"DotNetObject.SetResultProvider(CustomView())";
var aEngine = aScriptRuntime.GetEngine("py");
gScriptEngine = aEngine;
var aScope = aEngine.CreateScope();
var aDotNetObject = new CDotNetObject();
aScope.SetVariable("DotNetObject", aDotNetObject);
// That's the invoke to pything from step 3:
aEngine.Execute(aCode, aScope);
}
}
}

How to fix ambiguous reference errors?

I have a web app that allows importing of contacts from Hotmail, Yahoo and GMail. I finally have it almost completed but since I added the importing of GMail, I am getting ambiguous reference errors and I am unsure how to fix them without breaking any code.
Here is a screen shot of the errors:
Try to use unique class names as much as possible. This will be the better solution in the end.
Write the entire namespace when referencing
OAuth.OAuthBase a = new ...;
Google.GData.Client.OAuthBase b = new ...;
Make an using alias for one or both:
using n2 = OAuth;
using Google.GData.Client;
n2.OAuthBase a = new ...; // referenced using namespace
OAuthBase b = new ...; // referenced through existing `using`
you can try something like this..
using GoogleOAuthBase = Google.GData.Client.OAuthBase;
namespace abc
{
public class Program
{
//make sure this Google.GData.Client.OAuthBase is instansiateable
var googleBase = new GoogleOAuthBase();
}
}
you can try entire name space as well.
var googleBase = new Google.GData.Client.OAuthBase();

How can I roll back changes with Entity Framework 5 within a Unit Test project

I'm playing with Entity Framework, and I have a Unit Test project that I want to exercise what I've done so far. I'd like to have it not actually update my test database when it's done. If I was working in SQL I would create a transaction and then roll it back at the end.
How can I do the same thing here?
As I understand it, context.SaveChanges(); is effectively doing the write to the database. And if I don't have that, then allCartTypes is empty after I assign it context.CarTypes.ToList()
Here's an example of one of my Test classes.
using System;
using System.Diagnostics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Trains;
using System.Linq;
namespace TrainsTest
{
[TestClass]
public class TestCarType : TestBase
{
[TestMethod]
public void TestCarTypeCreate_Success()
{
var tankerCarType = new CarType {Name = "Tanker"};
var boxCarType = new CarType { Name = "Box" };
using (var context = new TrainEntities())
{
context.CarTypes.Add(tankerCarType);
context.CarTypes.Add(boxCarType);
context.SaveChanges();
var allCartTypes = context.CarTypes.ToList();
foreach (var cartType in allCartTypes)
{
Debug.WriteLine(cartType.CarTypeId + " - " + cartType.Name);
}
}
}
}
}
I know I'm missing something fundamental, but I don't know what it is. and my googling has been fruitless.
There's a MSDN article about ef transactions.
http://msdn.microsoft.com/en-gb/library/vstudio/bb738523(v=vs.100).aspx

What's the difference between Marshal.GenerateGuidForType(Type) and Type.GUID?

Type classType = typeof(SomeClass);
bool equal = Marshal.GenerateGuidForType(classType) == classType.GUID;
I haven't found a case that fail this condition.
So why and when should I use the Marshal method instead of simply getting the GUID property?
see http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.generateguidfortype.aspx
... GenerateGuidForType provides the same functionality as the Type.GUID property.
So according to documentation they are the same. However, Marshal.GenerateGuidForType works only for RuntimeType objects, while Type.GUID is provided for some other Type implementations as well.
E.g.:
using System;
using System.CodeDom;
using System.Runtime.InteropServices;
using System.Workflow.ComponentModel.Compiler;
namespace Samples
{
class Program
{
static CodeCompileUnit BuildHelloWorldGraph()
{
var compileUnit = new CodeCompileUnit();
var samples = new CodeNamespace("Samples");
compileUnit.Namespaces.Add(samples);
var class1 = new CodeTypeDeclaration("Class1");
samples.Types.Add(class1);
return compileUnit;
}
static void Main(string[] args)
{
var unit = BuildHelloWorldGraph();
var typeProvider = new TypeProvider(null);
typeProvider.AddCodeCompileUnit(unit);
var t = typeProvider.GetType("Samples.Class1");
Console.WriteLine(t.GUID); // prints GUID for design time type instance.
Console.WriteLine(Marshal.GenerateGuidForType(t)); // throws ArgumentException.
}
}
}
According to MSDN, "GenerateGuidForType provides the same functionality as the Type.GUID property". It should be safe to use the one that suits you the best.

Categories

Resources