namespace "FileToSend" does not exist - c#

Hi I want to send a photo with my telegram bot but my VS doesn't recognize "FileToSend" and my error is :
int chatId = int.Parse(dgReport.CurrentRow.Cells[0].Value.ToString());
FileStream imageFile = System.IO.File.Open(txtFilePath.Text,FileMode.Open);
bot.SendPhotoAsync(chatId, new FileToSend("1234.jpg", imageFile), txtmessage.Text);
CS0246 The type or namespace name 'FileToSend' could not be found (are
you missing a using directive or an assembly reference?)

The FileToSend() function is removed, use InputOnlineFile():
FileStream imageFile = System.IO.File.Open(txtFilePath.Text,FileMode.Open);
bot.SendPhotoAsync(chatId, new InputOnlineFile(imageFile, "image.png"), txtmessage.Text);

Sounds like you are very new to Visual Studio and also C# so I'll share a general tip. If you see a red squiggly line in Visual Studio you have a compile error. Your program will not build/run until it is fixed.
Here's my tip. Find the code that is causing the compile error (the text with a red squiggle beneath it). Right click the text and choose "Quick Actions and Refactoring". You will see several suggestions that may fix the issue.
The problem you are describing can usually be fixed using this feature. One of the options may be something like "Using Telegram.Bot;". If you choose it, it will automatically put the using statement at the top of your file and fix the compilation error. This is definitely the #1 reason I use Quick Actions and Refactoring.

Actually, the question is quite OK. I think you just might be mixing up examples you've found and tried, which - if so - is an honest mistake. The FileToSend() function is related to a (deprecated) project on GitHub at ScottRFrost/TelegramBot.
The rest of your sample seems to be mixed up a bith with, I assume, the TelegramBots/Telegram.Bot package. If you use that, the following sample might help you a bit further:
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using Telegram.Bot;
using Xunit;
namespace StackOverflowSupport
{
public class Tests
{
[Fact]
public async Task SendFileWithTelegramBot()
{
// Requires NuGet package `Telegram.Bot` (v15.0.0)
var token = "YOUR_TOKEN";
using (var http = new HttpClient())
{
int chatId = 42;
var imageFile = File.Open("filepath", FileMode.Open);
var bot = new TelegramBotClient(token, http);
await bot.SendPhotoAsync(chatId, photo: imageFile, caption: "This is a Caption");
}
}
}
}
As you can see, no FileToSend() in there, which might be the cause of your problem.
Note that this is just to help you in the right direction; it is not meant as code to be used in production. Especially reading out the stream through File.Open could be improved.

Related

Episerver: which directive/namespace am I missing (to resolve error CS0246)? ("using ______;")

Needing to support CMS-user uploaded SVG images in Episerver 10.10.5.0. It was a schlep, but I was able to come right using Marija's solution (in which she documents several others having these issues...).
My difficulty now is with implementing the second bit of Marija's solution, in which thumbnails are made available (rather than default icons) for the SVG images and in which the SVG images render properly in the editor:
[ServiceConfiguration(typeof(IModelTransform), Lifecycle = ServiceInstanceScope.Singleton)]
public class ThumbnailModelTransform : StructureStoreModelTransform
{
public ThumbnailModelTransform(
IContentProviderManager contentProviderManager,
ILanguageBranchRepository languageBranchRepository,
IContentLanguageSettingsHandler contentLanguageSettingsHandler,
ISiteDefinitionRepository siteDefinitionRepository,
IEnumerable hasChildrenEvaluators,
LanguageResolver languageResolver, UrlResolver urlResolver, TemplateResolver templateResolver) :
base(
contentProviderManager,
languageBranchRepository,
contentLanguageSettingsHandler, siteDefinitionRepository,
hasChildrenEvaluators,
languageResolver,
urlResolver,
templateResolver)
{
}
public override void TransformInstance(IContent source, StructureStoreContentDataModel target, IModelTransformContext context)
{
base.TransformInstance(source, target, context);
var contentWithThumbnail = source as VectorFile;
if (contentWithThumbnail != null)
{
var urlResolver = ServiceLocator.Current.GetInstance();
var defaultUrl = urlResolver.GetUrl(contentWithThumbnail.ContentLink, null, new VirtualPathArguments { ContextMode = ContextMode.Default });
target.ThumbnailUrl = defaultUrl;
}
}
}
I get the dreaded error CS0246 for most of the terms in Marija's code (one example below):
The type or namespace name 'StructureStoreModelTransform' could not be found (are you missing a using directive or an assembly reference?)
Here are the terms for which I receive that error (or a similar one):
StructureStoreModelTransform
ServiceConfiguration
IModelTransform
Lifecycle
StructureStoreContentDataModel
IModelTransformContext
ISiteDefinitionRepository
IEnumerable
LanguageResolver
UrlResolver
TemplateResolver
I've tried adding a bunch of directives: (or dependencies? what are these called?)
using System.Collections.Generic;
using System.Linq;
using System.Web;
...and a laundry list of others that didn't work, which I won't include here.
My colleague's installation of VS community autofills in these 'using' statements once VS determines they're needed. Mine (Microsoft Visual Studio Community 2019 Preview, Version 16.7.0 Preview 2.0) is not so kind.
So, two questions I guess, but one or the other will likely sort me out:
Where on earth are these EPiServer namespaces documented??? For
real; I've worn Google out searching.
Alternatively, how can I get
my Visual Studio to kindly fill in the gaps, like my colleague's
does?
Thanks for any assistance. Banging my head against the wall here.

PUN Networking error - No Suitable Method found to override

I'm fairly new to C# and unity, and i've been trying to set up the Photon Networking service. I've run into an issue i can't figure out the cause of. Here are the two error messages.
Assets\PhotonUnityNetworking\Resources\TestConnect.cs(21,41): error CS0246: The Type or namespace name 'DisconnectCause' could not be found (are you missing a using directive or an assembly reference?)
Asseta\PhotonUnityNetworking\Resources\TestConnect.cs(21,26): error CS0115 'TestConnect.OnDisconnected(DisconnectCause)': no suitable method found to override.
However, in visual studio, nothing shows up as incorrect.
Any help as to the cause of these issues appreciated.
using Photon.Pun;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestConect : MonoBehaviourPunCallbacks
{
private void Start()
{
print("Connecting to server...");
PhotonNetwork.GameVersion = "0.0.1";
PhotonNetwork.ConnectUsingSettings();
}
public override void OnConnectedToMaster()
{
print("Connected to server!");
}
public override void OnDisconnected(DiconnectionCause cause)
{
print("Disconnected from Server for reason " + cause.ToString());
}
}
First another important note: You should not put any of your custom scripts inside a folder called Resources!
Also afaik PhotonUnityNetworking is their official folder of Photon itself. I'ld recommend to not modify or add anything within it, makes it hard to upgrade or fix it later if you have messed it up somehow.
Then to your issue
It is as the error already suggests
are you missing a using directive
DisconnectCause belongs to another namespace Photon.Realtime.
You will need to add a
using Photon.Realtime;
on the top of that file or have to address it directly like
public override void OnDisconnected(Photon.Realtime.DisconnectCause cause)
{
...
}
Strange though that VisualStudio doesn't note that...
The second error is just a follow-up compile error not finding the according method to override because of a supposed signature mismatch since it doesn't know the type you used as parameter due to the error before.
In the future please don't post screenshots of code and error messages! This makes it not only harder to solve the issue but also makes it impossible for others to find this thread when searching for the error message content in order to see if it was already solved somewhere!
Rather copy & paste the raw text I your question and format it as code using the { } button.

error CS0433: The imported type `System.Net.WebRequest' is defined multiple times

when i'm loading my C# script, i get the error message in title.
My script starts with these lines:
using System;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TradeServer.ScriptingDriver.DataObjects;
using TradeServer.ScriptingDriver.Interfaces
;
ANd the error comes from that first line:
WebRequest request = HttpWebRequest.Create("https://drive.google.com/file/d/....");
WebResponse webResp = request.GetResponse();
System.IO.StreamReader sr = new System.IO.StreamReader(webResp.GetResponseStream());
string newestversion = sr.ReadToEnd();
I've tried to comment out pretty much all permutations, it just does not work, creates more error codes, or always spits out error in title.
I understand from searching on Google that i have some kind of duplicate issues in my libraries, but i'm really no expert on this.
If anyone 's got a clue how to fix this. Appreciated.
This sounds like it is happening because you have two different assemblies being referenced that contain a type of the same name WebRequest.
You'll want to be explicit about which assemblies' WebRequest type you want to use. In your case try:
System.Net.WebRequest request = HttpWebRequest.Create("https://drive.google.com/file/d/....");
Update:
Here's a way to get more information about what exactly is causing this conflict. Try putting this in before the line throwing the original error. It should cause a new error but this time we should see more information about those conflicting sources.
System.Runtime.InteropServices.DefaultParameterValueAttribut‌​e x = null;
This should tell you something like:
The type 'System.Runtime.InteropServices.DefaultParameterValueAttribut‌​e' exists in both 'c:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Core.dll' and .....

CodeFixProvider-derived class: how to properly format code that is moved in a new block?

I'm using visual-studio-2015 and trying to figure out roslyn code analysis services. In my learning process I want to create an analyzer that will cause a warning to appear when using statements are placed at the top of a c# code file, rather than within a namespace declaration. I also want the IDE to provide me with a quick shortcut to allow easy fixing of the faulting code.
For example, whenever the code analysis tool sees this:
using System;
using System.Collections.Generic;
namespace MyNamespace
{
class TypeName
{
}
}
... I want it to show a warning and propose to turn it into this:
namespace MyNamespace
{
using System;
using System.Collections.Generic;
class TypeName
{
}
}
I managed to get my analyzer class (derived from DiagnosticAnalyzer) working like I want. My main issue right now is with the CodeFixProvider-derived class.
Technically, right now, it works; the statements are moved down to namespace declarations. However, The formatting is not so good. Here is what I actually get when trying to fix the first code block above:
*
namespace ConsoleApplication1
{
using System;
using System.Collections.Generic;
class TypeName
{
}
}
The asterisk character represents a remaining carriage return. Also note how there's a linebreak right after the first namespace bracket and none between using statements and class declaration. I want that linebreak moved down and sit on top of the class.
Here is (parts of interest within) my CodeFixProvider-derived class code:
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
foreach (var diagnostic in context.Diagnostics)
{
context.RegisterCodeFix(
CodeAction.Create(
title: Title,
createChangedDocument: c => ProvideDocumentAsync(context.Document, c),
equivalenceKey: Title),
diagnostic);
}
}
private async Task<Document> ProvideDocumentAsync(Document document, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false) as CompilationUnitSyntax;
if (root == null) return null;
var newRootUsings = new SyntaxList<UsingDirectiveSyntax>();
var newRoot = root.WithUsings(newRootUsings);
foreach (var namespaceDecl in newRoot.Members.OfType<NamespaceDeclarationSyntax>())
{
NamespaceDeclarationSyntax newNsDecl = namespaceDecl;
foreach (var statement in root.Usings)
{
var newStatement = statement.WithLeadingTrivia(statement.GetLeadingTrivia().Union(new[] { Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Whitespace(" ") }));
newNsDecl = newNsDecl.AddUsings(newStatement);
}
newRoot = newRoot.ReplaceNode(namespaceDecl, newNsDecl);
}
return document.WithSyntaxRoot(newRoot);
}
As you can see I did figure out how to add the extra indentation (with GetLeadingTrivia method). I suppose I can do the same for extra lines but somehow I feel there's probably a better way I'm not aware of yet, being pretty green with these new code analysis / refactoring tools.
So any guidance on how to make the formatting - or anything else for that matter - any better?
UPDATE:
It just occured to me today that the "right" formatting to apply within a Roslyn code fix provider should be the one applied by the code editor by default (in my case, Visual Studio 2015), with its own set of rules.
My understanding is that the Formatter class inside the compiler engine can allow "hinting" the code editor that formatting is required on some nodes / textspans. A code fix trying to format the code further than this is probably doing too much.
If anyone believes I'm mistaken, you are very much welcome to chime in. I'm still on training wheels with Roslyn and willing to learn.
Add .WithAdditionalAnnotations(Formatter.Annotation) to tell Roslyn to auto-format your change.

Can someone provide an example for the ImageCompare methods?

I'm attempting to compare two images using Visual Studio 2013 Pro. The MSDN provides information (http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.uitesting.imagecomparer.compare.aspx) on ImageComparer.Compare, alas I'm failing to get it implemented in my code. On the last line of my code I'm told that "The name 'Compare' does not exist in the current context". Can someone please help? Thanks!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using Microsoft.VisualStudio.TestTools.UITesting;
namespace Intranet.SmokeTests
{
public class Intranet_Login : Intranet_Setup
{
public List<string> IntranetLoginTest(string BrowserURL, string Host, int Port)
{
Image expected = Image.FromFile(#"\\webdriver\ImageVerification\Expected\IntranetHome.png");
Image actual = Image.FromFile(#"\\webdriver\ImageVerification\Actual\IntranetHome.png");
bool equal = Compare(actual, expected);
}
}
}
You must do it like this:
bool equal = ImageComparer.Compare(actual, expected);
When you want to use a class's static member in c# you must always qualify it with the class first. Otherwise the compiler will try to locate the member on the current class.
Another problem you might be having with your IntranetLoginTest is that it's supposed to return an instance of List<string>, but it doesn't. I must also say I find it strange that you are making an image comparison test in a method that would suggest it performs authentication mechanisms testing.
1- Using nuget Install System.Drawing.Common
2- Reference Microsoft.VisualStudio.TestTools.UITesting.dll from C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\Common7\IDE\Extensions\TestPlatform
Image expected = Image.FromFile(#"2020-09-01_15h31_24.png");
Image actual = Image.FromFile(#"2020-09-01_15h31_30.png");
Image difference = null;
var isTestPass = ImageComparer.Compare(actual, expected, out difference);
if (!isTestPass)
difference.Save("diff.png");
Console.ReadLine();
Expected
Actual
Difference
It turns out that the correct version of the referenced dll was not being added. The complete answer is here: How can I make the namespace locally match what is listed on MSDN?

Categories