String calculator [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Hi fellow programmers,
I am creating a calculator in C#
and I have a string variable math which contains 100 * 5 - 2
How can I display its output which is 498 in my console?
My code is this:
String math = "100 * 5 - 2";
Console.WriteLine(math);
Console.ReadLine(); // For Pause
So basically, what my code will give me is the string itself which 100 * 5 - 2
but I want it to give me 498 as a result.
Idea about this is pretty much appreciated.
Thanks

Regular Expression evaluation can be done using DataTable.Compute method (from MSDN) :
Computes the given expression on the current rows that pass the filter
criteria.
Try this:
using System.Data;//import this namespace
string math = "100 * 5 - 2";
string value = new DataTable().Compute(math, null).ToString();

Simply try this
String math = (100 * 5 - 2).ToString();
I don't know, Why you want more complex? It's very easy ..
And if you want surely that,You can do that by using EvaluateExpression
public int EvaluateExpression(string math )
{
return Convert.ToInt32(math);
}
........................
String math = "100 * 5 - 2";
int result = EvaluateExpression(math );
Console.WriteLine(result );
See this discussions
Evaluating string "3*(4+2)" yield int 18
Update:
If those values came from input textbox, then write this way
String math = txtCalculator.Text.Trim();
int result = EvaluateExpression(math );
Console.WriteLine(result );
And also you can find out some pretty answer from this discussion
Is it possible to compile and execute new code at runtime in .NET?
Update 2:
Finally I have tried this sample for you :
My full code for class library
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.XPath;
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
String math = "100 * 5 - 2";
Console.WriteLine(Evaluate(math));
}
public static double Evaluate(string expression)
{
var xsltExpression =
string.Format("number({0})",
new Regex(#"([\+\-\*])").Replace(expression, " ${1} ")
.Replace("/", " div ")
.Replace("%", " mod "));
// ReSharper disable PossibleNullReferenceException
return (double)new XPathDocument
(new StringReader("<r/>"))
.CreateNavigator()
.Evaluate(xsltExpression);
// ReSharper restore PossibleNullReferenceException
}
}

You can compile code from string at runtime and execute it:
using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace DynamicCalcTest
{
class Program
{
static void Main(string[] args)
{
var result = new DynamicCalculator<double>("2 + 2 * 2").Execute();
}
}
public class DynamicCalculator<T>
{
private MethodInfo _Method = null;
public DynamicCalculator(string code)
{
_Method = GetMethodInfo(code);
}
public T Execute()
{
return (T)_Method.Invoke(null, null);
}
private MethodInfo GetMethodInfo(string code)
{
var tpl = #"
public static class Calculator
{{
public static double Calc()
{{
return {0};
}}
}}";
var finalCode = string.Format(tpl, code);
var parameters = new CompilerParameters();
parameters.ReferencedAssemblies.Add("mscorlib.dll");
parameters.GenerateInMemory = true;
parameters.CompilerOptions = "/platform:anycpu";
var options = new Dictionary<string, string> { { "CompilerVersion", "v4.0" } };
var c = new CSharpCodeProvider(options);
var results = c.CompileAssemblyFromSource(parameters, finalCode);
var type = results.CompiledAssembly.GetExportedTypes()[0];
var mi = type.GetMethod("Calc");
return mi;
}
}
}

Related

Methods return type in C#

i am using a method to retrieve data from an OPC DA server using TitaniumAS packages, the problem i am having is that i have a lot of tags to read/write so i have to use methods.
The WriteX method works fines as it doesnt have to return anything but the read does not, well it does its job, it reads but i cannot use that data outside of the method because it was a void method, when i tried to use it as a String method (that's the type of data i need) it says :
Error CS0161 'ReadX(string, string)': not all code paths return a value
PS : note that i am just a beginner in C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TitaniumAS.Opc.Client.Common;
using TitaniumAS.Opc.Client.Da;
using TitaniumAS.Opc.Client.Da.Browsing;
using System.Threading;
using System.Threading.Channels;
using Async;
namespace OPCDA
{
class Program
{
static void Main(string[] args)
{
TitaniumAS.Opc.Client.Bootstrap.Initialize();
Uri url = UrlBuilder.Build("Kepware.KEPServerEX.V6");
using (var server = new OpcDaServer(url))
{
server.Connect();
OpcDaGroup group = server.AddGroup("MyGroup");
group.IsActive = true;
Ascon ascon1 = new Ascon();
ReadX("Channel1.Ascon1.AsconS", ascon1.ALM);
Console.WriteLine("value = {0}", ascon1.ALM);
void WriteX(String Link, String Ascon)
{
var definition1 = new OpcDaItemDefinition
{
ItemId = Link,
IsActive = true
};
OpcDaItemDefinition[] definitions = { definition1 };
OpcDaItemResult[] results = group.AddItems(definitions);
OpcDaItem tag = group.Items.FirstOrDefault(i => i.ItemId == Link);
OpcDaItem[] items = { tag };
object[] Values = { Ascon };
HRESULT[] Results = group.Write(items, Values);
}
string ReadX(String Link, String read)
{
var definition1 = new OpcDaItemDefinition
{
ItemId = Link,
IsActive = true
};
OpcDaItemDefinition[] definitions = { definition1 };
OpcDaItemResult[] results = group.AddItems(definitions);
OpcDaItemValue[] values = group.Read(group.Items, OpcDaDataSource.Device);
read = Convert.ToString(values[0].Value);
}
}
}
}
}
the first step was to state the return like this :
return Convert.ToString(values[0].Value) instead of read = Convert.ToString(values[0].Value)
then go up and use that value with my variable :
ascon1.ALM=ReadX("Channel1.Ascon1.AsconS");

How to fix can't convert string to double error after converting it

I am very new to Xamarin and a little but confused but I when applying a code get this error:
can't convert string to double error after converting it.
My code is this:
DATA.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Orbage
{
public class DATA
{
public string Label = "USA";
public string Address = "This is the US";
public string Lat = "40.060407";
public string Lng = "-102.453091";
}
}
and my main page is this:
using System.Collections.Generic;
using Xamarin.Forms.Maps;
using Xamarin.Forms;
using System.IO;
using Newtonsoft.Json;
using System;
using System.Globalization;
namespace Orbage
{
class MapPage : ContentPage
{
public MapPage()
{
CustomMap customMap = new CustomMap
{
MapType = MapType.Street
};
// ...
Content = customMap;
var json = File.ReadAllText("DATA");
NumberFormatInfo provider = new NumberFormatInfo();
provider.NumberDecimalSeparator = ".";
provider.NumberGroupSeparator = ",";
double doubleVal = Convert.ToDouble("855.65", provider);
var places = JsonConvert.DeserializeObject<List<DATA>>(json);
foreach (var place in places)
{
CustomPin pin = new CustomPin
{
Type = PinType.Place,
Position = new Position(place.Lat,place.Lng),
Label = place.Label,
Address = place.Address,
Name = "Xamarin",
Url = "http://xamarin.com/about/"
};
customMap.CustomPins = new List<CustomPin> { pin };
customMap.Pins.Add(pin);
customMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(37.79752, -122.40183), Distance.FromMiles(1.0)));
}
}
}
}
Even after doing this I receive this error.
How can I fix this or make any changes to my code so there is no need in doubling it.
If my code seems confusing I have basically created custom maps and instead of creating a million pins writing all the code in a data script . When I try to apply it I get this error.
Is there a better way to write it which avoids doubling it or can you please tell me how to convert it.
PLease help me. Thanks a lot!
Error in this line:
Position = new Position(place.Lat,place.Lng),
in your DATA class Lat and Lng are defined as strings. You need to convert them to double, which is what Position requires
Position = new Position(Double.Parse(place.Lat),Double.Parse(place.Lng)),

What tools are needed to build the Telegram-Bot with Asp.net And C#? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
I've made a robot with the console, now I wanna put the robot on the host server to always be active so I need to change the robot to ASP.net.
I tried many commands but did not succeed.
I'm asking that,What tools are needed to build the Telegram-Bot with Asp.net And C# ?
C# 2013 update3
Summary code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NetTelegramBotApi;
using NetTelegramBotApi.Requests;
using NetTelegramBotApi.Types;
using System.Net.Http;
using System.Runtime.Remoting.Channels;
using System.Data;
using System.Data.SqlClient;
namespace TestMyCam_bot
{
class Program
{
private static string Token = "";
private static ReplyKeyboardMarkup mainmenu;
int i, j;
int Counter = 0;
bool success = false;
bool bool_EndHtml = false;
bool yek_Bar_Downloaded = false;
Exception Ex;
static void Main(string[] args)
{
mainmenu = new ReplyKeyboardMarkup
{
Keyboard = new[] { new[] { "Sony" }, new[] { "Apple" }, new[] { "Nokia"} }
};
Task.Run(() => RunBot());
Console.ReadLine();
}
public static async Task RunBot()
{
var bot = new TelegramBot(Token);
var me = await bot.MakeRequestAsync(new GetMe());
Console.WriteLine("User Name is {0}", me.Username);
long offset = 0;
int whilecount = 0;
while (true)
{
Console.WriteLine("while is {0}", whilecount);
whilecount += 1;
var updates = await bot.MakeRequestAsync(new GetUpdates() { Offset = offset });
Console.WriteLine("Update Count is {0} ", updates.Count());
Console.WriteLine("-------------------------------------");
try
{
foreach (var update in updates)
{
offset = update.UpdateId + 1;
var text = update.Message.Text;
if (text == "/start")
{
var req = new SendMessage(update.Message.Chat.Id, "Select Button") { ReplyMarkup = mainmenu};
await bot.MakeRequestAsync(req);
continue;
}
}
catch (Exception ex)
{
throw;
}
}
}
}
}
if my questions is not clear i am sorry . I need to tell me,for example : vs 2015 ,webhook,ssl and etc. or simple code for my example code above.thanks

C# Objects in a list are overwriting each other [duplicate]

This question already has answers here:
What does the static keyword mean?
(4 answers)
Closed 7 years ago.
The code I am looking at is as follows
string data;
string[] tokens;
while (sr.EndOfStream != true)
{
data = sr.ReadLine();
char delim = ',';
tokens = data.Split(delim);
Team t = new Team(tokens[0], int.Parse(tokens[1]), int.Parse(tokens[2]));
TeamList.Add(t);
}
//Test to make sure the teams were stored properly
foreach(Team t in TeamList)
{
Console.WriteLine(t.Name);
}
sr.Close();
When I use the foreach loop to write the team names out it displays 9 copies of Team9 (The teams are listed 1-9 in the text file line by line, with two numbers separated by commas to hold the wins and losses for each team, which is the reason there are delims with commas). This goes for any number of teams I add, if i add a 10th team it does 10 copies of team10, and if I use 8 teams it shows 8 copies of Team8. I added the foreach loop into the while loop to have it show the teams at each stage and it keeps overwriting all previous objects when it creates a new one, so for example the first time it runs the loop it shows Team1, then the next time it runs the loop it shows two lines of Team2, and so on. From my research I saw that this is usually caused by not declaring a new object inside of the loop, but in this case a new object is declared inside the loop.
Edit: the Team class is as follows
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApplication2
{
class Team
{
private static string tn;
private static int Wins, Losses;
public Team()
{
}
public Team(string name, int wins, int losses)
{
tn = name;
Wins = wins;
Losses = losses;
}
public override string ToString()
{
return tn + ", wins: " + Wins + ", losses: " + Losses;
}
public string Name
{
get { return tn; }
}
}
}
The TeamList variable and main class are as follows
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApplication2
{
class Program
{
private static Random pick = new Random();
private static List<Team> TeamList = new List<Team>();
static void Main(string[] args)
{
//Reading file io
Schedule(TeamList);
Console.ReadLine();
}
static void Schedule(List<Team> TeamList)
{
StreamReader sr = new StreamReader("C:/Users/andre/Desktop/VisualStudioProjects/ConsoleApplication1/ConsoleApplication1/TeamList.txt");
string data;
string[] tokens;
while (sr.EndOfStream != true)
{
data = sr.ReadLine();
char delim = ',';
tokens = data.Split(delim);
Team t = new Team(tokens[0], int.Parse(tokens[1]), int.Parse(tokens[2]));
TeamList.Add(t);
foreach(Team x in TeamList)
{
Console.WriteLine(x.Name);
}
}
//Test to make sure the teams were stored properly
foreach(Team t in TeamList)
{
Console.WriteLine(t.Name);
}
sr.Close();
}
The text file is simply a file that contains the following
Team1,0,0
Team2,0,0
Team3,0,0
Team4,0,0
Team5,0,0
Team6,0,0
Team7,0,0
Team8,0,0
Team9,0,0
You have
class Team
{
private static string tn; //STATIC??
private static int Wins, Losses; //STATIC??
}
static means the variable is shared between all instances of Team in your application. Remove it please. That is the problem.

Automatic number insertion in MySQL with the format "AN-00000000"

My purpose on this is to insert a autonumber for this format AN-00000000 to the db, with the type in db varchar.
my code in windows form is saving a integer number already "10000000".
But I turn on my mind and think if possible that the auto number will be like this AN-00000000 and to save to the db with a character string.
I tried my best to change and apply but suddenly I can not implement because is on the integer part.
I am creating the basic system in our company to create a automate membership for the members, in our company we have 4 parts of membership which is Dep, sep, mep and cef, so I turn on my mind that i need to implement the 4 Id with the following to identify what the department they included. like DEP-00000001, SEP-00000001, MEP-0000001 and CEF-00000001.
Can anyone suggest or give their opinion on my code below? Thanks!
DBconnect.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Windows.Forms;
using System.Data;
namespace PAIRDevelopment.Classes
{
public class DBConnect
{
public static string csConnect = "uid=root; database=membership; pooling = false; convert zero datetime=True";
public static MySqlConnection csCon= new MySqlConnection(Classes.DBConnect.csConnect);
public MySqlCommand cmdCon = new MySqlCommand();
public MySqlDataReader reader;
public void nonQuery(string cmdText)
{
cmdCon.Connection = csCon;
csCon.Open();
cmdCon.CommandText = cmdText;
cmdCon.ExecuteNonQuery();
cmdCon.Dispose();
csCon.Close();
}
public void OPEN(string cmdtext)
{
cmdCon.Connection = Classes.DBConnect.csCon;
Classes.DBConnect.csCon.Open();
cmdCon.CommandText = cmdtext;
reader = cmdCon.ExecuteReader();
}
public void CLOSE()
{
reader.Close();
cmdCon.Dispose();
Classes.DBConnect.csCon.Close();
}
}
}
Windows Form:
using System;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace PAIRDevelopment
{
public partial class Pair_Individual : Form
{
Classes.DBConnect OpenConCls = new Classes.DBConnect();
public Pair_Individual()
{
InitializeComponent();
textBox6.MaxLength = 13;
}
private void benabled_Click(object sender, EventArgs e)
{
OpenConCls.OPEN("SELECT MAX(piId) FROM tblpair_individual_membership");
while (OpenConCls.reader.Read())
{
string pcount = OpenConCls.reader[0].ToString();
if (pcount.Length == 0)
{
textBox1.Text = "10000000";
}
else
{
//int pcount1 = Convert.ToInt32(pcount);
//int pcountAdd = pcount1 + 1;
int pcount1 = Convert.ToInt32(pcount);
int pcountAdd = pcount1 + 1;
textBox1.Text = pcountAdd.ToString();
}
}
OpenConCls.CLOSE();
}
int pcount1 = Convert.ToInt32(pcount);
You are probably throwing a FormatException on the above line now if the string contains more than 0-9.
FormatException - value does not consist of an optional sign followed by
a sequence of digits (0 through 9).
If you know the first 4 chars will always be "XXX-" (e.g. "MEP-") then why don't you:
int pcount1 = Convert.ToInt32(pcount.Substring(4)); // ######## part
int pcountAdd = pcount1 + 1; // ######## + 1
textBox1.Text = String.Format("{0}-{1:D8}", pcount.Substring(0, 4), pcountAdd);
Which will convert only the numeric part, increment it, and then concatenate it with the first part.
Also you can look into the TryParse method. Which will indicate if your parse succeeded.
TryParse - Converts the string representation of a number to its 32-bit signed
integer equivalent. A return value indicates whether the operation succeeded.

Categories

Resources