String interpolation not working in C# class - c#

I'm using String interpolation in the code behind, and now I need to take part of it to a class.
when I do it, I get error "CS1056: Unexpected character '$'"
even a very simple code gives the error right on running (not on build):
string MailSubject = $"this is your score: {userScore}";
this part of code is part of the FaceClass.CS file
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
namespace ns.App_Code
{
public class FakeClass
{
public static void Check_Next_In_Line(int score)
{
int temp = Fake2Class.GetData();
if (temp == 0)
{
string MailSubject = "";
string MailBody = "";
MailBody = $"Your score: {score}";
/*
mail send function
*/
}
}
}
}
I'm using .NET Framework 4.8
String Interpolation works for me in a aspx code behind but not in a method within a class. If I want to refactor a part of code becuase it is needed more than once - it won't work

Hi an alternative solution to what you are looking for may be would be to use string format. Something like below
int userscore;
string MailSubject = string.Format("this is your score: {0}", userscore);

Related

'IPhoneLine' does not contain a definition for 'PhoneLineStateChenged'

I am just starting with Ozeki VoIP SDK.
in my register method, my phoneLine does not recognize PhoneLineStateChanged.
my code is below.
public void Register(bool registrationRequired,string displayName, string userName, string authenticationId, string registerPassword, string domainHost, string domainPort)
{
try
{
var account = new SIPAccount(registrationRequired, displayName, userName, authenticationId, registerPassword, domainHost, domainPort);
Console.WriteLine("\n Creating SIP account {0}", account);
var natConfiguration = new NatConfiguration(NatTraversalMethod.None);
var phoneLineConfiguration = new PhoneLineConfiguration(account);
//phoneLine = softPhone.CreatePhoneLine(account);
phoneLine = softPhone.CreatePhoneLine(phoneLineConfiguration);
Console.WriteLine("Phoneline created.");
phoneLine.PhoneLineStateChanged += phoneLine_PhoneLineStateChanged;
}
catch
{ }
}
and my references are
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ozeki.Network.Nat;
using Ozeki.VoIP;
using Ozeki.VoIP.SDK;
did I forget a reference or what?
Looking at the SDK examples, it seems that the event is actually called RegistrationStateChanged. So this should work:
phoneLine.RegistrationStateChanged += phoneLine_PhoneLineStateChenged;
It's a little misleading that their example also calls it phoneLine.PhoneLineStateChanged. I guess they renamed it.

Importing a VB6 dll into a c# project

I'm trying to use a object made id VB6 into my c# project, but I don't have the VB6 source code. A did this steps:
1) register the mail.dll (thats a VB6 dll);
2) add the reference that appears on COM;
3) import to my code.
I create an object. But when I tried to call the method SendMailSMTP from this dll I got this error:
ActiveX component can't create object(429)
This error is common when the DLL is not registered. But a registered with success.
Is there any other way to create this VB6 dll with correct interoperability ?
My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SMTPMail;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string msgRetorno = "";
clsSMTPmail smtpMail = new clsSMTPmail();
string from = "test#test.com.br";
string to = "test#test.com.br"; ;
string cc = "";
string subject = "teste subject";
string corpo = "Mensagem de teste";
string profileSMTP = "";
string passwordSMTP = "";
try
{
msgRetorno = smtpMail.SendMailSMTP(from, to, cc, subject, corpo, profileSMTP, passwordSMTP, null);
}
catch (Exception e)
{
msgRetorno = e.InnerException.Message;
}
}
}
}

Skype issue with multiple params

I am trying to make a C# Stress script but it keeps giving me the error: Error Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement.
Code:
using System;
using System.Collections.Generic;
using System.Text;
using Skyper;
using SKYPE4COMLib;
using System.Net;
namespace Skyper.plugins
{
public static class Help
{
public static string Description
{
get
{
return "Stresser";
}
}
public static void Execute(string[] Params, int chat, string username)
{
Skyper.SendMessage(chat, Params[1] + "" + new WebClient().DownloadString("http://example.com/stresser/api.php?key=examplekey&host=" + Params[1]));"&port=&time=&method=";
}
}
}
How this script will work is users in Skype will type in !stress ip, port, time, method and then it will submit it to the API.
Following is a simple string, which is not assigned to any thing,
"&port=&time=&method=";
So may be you can use something like:
Skyper.SendMessage(chat, Params[1] + "" + new WebClient().DownloadString("http://example.com/stresser/api.php?key=examplekey&host=&port=&time=&method=" + Params[1])");
or change that string properly with double quotes and brackets end symbols

Why this google translate code isnt working?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Text.RegularExpressions;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
TranslateText("hi", "German");
}
private void Form1_Load(object sender, EventArgs e)
{
}
public static string TranslateText(string input, string languagePair)
{
return TranslateText(input, languagePair, System.Text.Encoding.UTF7);
}
/// <summary>
/// Translate Text using Google Translate
/// </summary>
/// <param name="input">The string you want translated</param>
/// <param name="languagePair">2 letter Language Pair, delimited by "|".
/// e.g. "en|da" language pair means to translate from English to Danish</param>
/// <param name="encoding">The encoding.</param>
/// <returns>Translated to String</returns>
public static string TranslateText(string input, string languagePair, Encoding encoding)
{
string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);
string result = String.Empty;
using (WebClient webClient = new WebClient())
{
webClient.Encoding = encoding;
result = webClient.DownloadString(url);
}
Match m = Regex.Match(result, "(?<=<div id=result_box dir=\"ltr\">)(.*?)(?=</div>)");
if (m.Success)
result = m.Value;
MessageBox.Show(result);
return result;
}
}
}
I added in the constructor the line:
TranslateText("hi", "German");
And in the bottom i added:
MessageBox.Show(result);
I wanted for the test to translate the word "hi" to German
But the result im getting and in the messagebox is a very long text wich is containing all the google website.
I tried to go manualy to the web site in the string url address and its working im getting to the google translate website.
I dont understand why it dosent work.
I want later to put instead "hi" some text from a text file.
I tried ot use breakpoint and found that this part the Success is all the time return false dont know why:
if (m.Success)
result = m.Value;
I think you are not getting the translated text or value in your html result from your code and also from Google.
Reason:
If you execute this through the browser, it is not translating to the language you expect, example:
http://www.google.com/translate_t?hl=en&ie=UTF8&text=hi&langpair=de
I used langpair=de or langpair=German and doesn't work, it shows me always "hi" as my initial text and not "hallo" (text in german).
Well, just to answer your question to get the text, do the following:
Add this method to your class:
public static string getBetween(string strSource, string strStart, string strEnd)
{
int Start, End;
if (strSource.Contains(strStart) && strSource.Contains(strEnd))
{
Start = strSource.IndexOf(strStart, 0) + strStart.Length;
End = strSource.IndexOf(strEnd, Start);
return strSource.Substring(Start, End - Start);
}
else
{
return "";
}
}
Change the following in your "TranslateText" method:
//Match m = Regex.Match(result, "(?<=<div id=result_box dir=\"ltr\">)(.*?)(?=</div>)");
string text = getBetween(result, "<span id=result_box class=\"short_text\">", "</span>");
//if (m.Success)
// result = m.Value;
return text;
Now execute your code like this:
// this will return empty ("") if no text found.
// or any problem happens (like lose your internet connection)
string translatedText = TranslateText("hi", "German");
Console.Write(translatedText);
At this point, if you get the translated text from google, it will be retrieved in your app.
Recommendations:
Use a console application and no windows forms, it will be faster.
Warning:
"Google is not a free translating tool. What you do is terms violation".
Hope this helps :-)
Would be easier, and more robust to parse the html using something other than a regex. You can then search the parsed HTML tree for the result and extract it from there.
See What is the best way to parse html in C#?

C# write multi lines to cs file

I googled and found the solution at MSDN.
// Compose a string that consists of three lines.
string lines = "First line.\r\nSecond line.\r\nThird line.";
// Write the string to a file.
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt");
file.WriteLine(lines);
file.Close();
How to extend the lines to complex content which including some natural C# code lines.
eg. I want to write the information below to my test.cs file.
Why?
I am parsing a XML schema with C# Console Application. And i want to generate the Console Result to a .cs file during the compiler time.
using System;
using System.Collections.Generic;
using System.Text;
namespace CommonDef
{
public class CCODEData
{
public int iCodeId;
public string sCode;
public CODEDType cType;
public int iOccures;
}
[Description("CodeType for XML schema.")]
public enum CODEDType
{
cString = 1,
cInt = 2,
cBoolean = 3,
}
thank you.
If your source code is hardcoded as in your sample, you could use a C# literal string:
string lines =
#"using System;
using System.Collections.Generic;
using System.Text;
namespace CommonDef
..."
Anyway in such cases it is a better idea (more readable and maintainable) to have the whole text contents into a text file as an embedded resource in your assembly, then read it using GetManifestResourceStream.
(I'm assuming you're trying to build up the result programmatically - if you genuinely have hard-coded data, you could use Konamiman's approach; I agree that using an embedded resource file would be better than a huge verbatim string literal.)
In your case I would suggest not trying to build up the whole file into a single string. Instead, use WriteLine repeatedly:
using (TextWriter writer = File.CreateText("foo.cs"))
{
foreach (string usingDirective in usingDirectives)
{
writer.WriteLine("using {0};", usingDirective);
}
writer.WriteLine();
writer.WriteLine("namespace {0}", targetNamespace);
// etc
}
You may wish to write a helper type to allow simple indentation etc.
If these suggestions don't help, please give more details of your situation.
I know an answer has already been accepted but why not use an XSLT applied to the XML instead? this would mean that you could easily generate c#, vb.net, .net without having to recompile the app.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FileHandling
{
class Class1
{
static void Main()
{
Console.WriteLine("Enter data");
ConsoleKeyInfo k;
//Console.WriteLine(k.KeyChar + ", " + k.Key + ", " + k.Modifiers );
string str="";
char ch;
while (true)
{
k = Console.ReadKey();
if ((k.Modifiers == ConsoleModifiers.Control) && (k.KeyChar == 23))
{
Console.WriteLine("\b");
break;
}
if (k.Key == ConsoleKey.Enter)
{
Console.WriteLine("");
str += "\n";
}
ch = Convert.ToChar(k.KeyChar);
str += ch.ToString();
}
Console.WriteLine(str);
Console.Read();
}
}
}

Categories

Resources