473,394 Members | 1,738 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

from expression to string literal - how ?

If I define an expression or equation, how can I retrieve that expression as
string literal? I want to do this so that I could avoid repetitive typing
(or copy/paste/change) the same thing at two place. I try to demonstrate
the problem in the following code.

Bob M
<%@ Page Language="C#" %>
<script runat="server">

public static double givenFn(double x) {

return (Math.Pow(x, 3) + (3 * Math.Pow(x, 2)) - (10 * x));
}

protected void Page_Load(object sender, EventArgs e) {

Label1.Text = "The given function is: " + "Math.Pow(x, 3) + (3 *
Math.Pow(x, 2)) - (10 * x)";
}
</script>

<html>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
May 21 '07 #1
9 2791
Bob,

If the "Math.Pow(x, 3) + (3 * Math.Pow(x, 2)) - (10 * x)" is constant,
then you can use the const keyword to specify it in one place:

// At the class level:
private const string FunctionExpression = "Math.Pow(x, 3) + (3 * Math.Pow(x,
2)) - (10 * x)";

If it makes sense only to have the constant in the scope of the current
method/property, then you can do this:

// In a method:
const string FunctionExpression = "Math.Pow(x, 3) + (3 * Math.Pow(x, 2)) -
(10 * x)";

If your expression can be generated depending on different parameters,
then create a method which will generate the expression for you, and use
that.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Bob M" <bobM@NoSpamwrote in message
news:OK**************@TK2MSFTNGP02.phx.gbl...
If I define an expression or equation, how can I retrieve that expression
as string literal? I want to do this so that I could avoid repetitive
typing (or copy/paste/change) the same thing at two place. I try to
demonstrate the problem in the following code.

Bob M
<%@ Page Language="C#" %>
<script runat="server">

public static double givenFn(double x) {

return (Math.Pow(x, 3) + (3 * Math.Pow(x, 2)) - (10 * x));
}

protected void Page_Load(object sender, EventArgs e) {

Label1.Text = "The given function is: " + "Math.Pow(x, 3) + (3 *
Math.Pow(x, 2)) - (10 * x)";
}
</script>

<html>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>

May 21 '07 #2
Hi Nicholas,

Thanks. But I have to use that function (x^3 + 3x^2 - 10x) later in my
application code. If I specify
"Math.Pow(x, 3) + (3 * Math.Pow(x, 2)) - (10 * x)" as string constant at
one place, then how can I use this string constant in the return statement
in the givenFn()method?

My problem is a little bit different. Perhaps my code example did not
elaborate the problem I am trying to convey. The revised code is posted
again:

<%@ Page Language="C#" %>
<script runat="server">

public static double givenFn(double x) {

return (Math.Pow(x, 3) + (3 * Math.Pow(x, 2)) - (10 * x)); // function
expression
}

protected void Page_Load(object sender, EventArgs e) {

Label1.Text = "f(x)=" + "Math.Pow(x, 3) + (3 * Math.Pow(x, 2)) - (10 *
x)";
// Can this second string literal
be retrieved
// from the function expression in
// givenFn() method to avoid typing
(copy/paste

Label2.Text = "f(x) = " + givenFn(6) + " at x=6";
}

</script>
<html><body><form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
</div>
</form></body></html>

May 21 '07 #3
For your convenience I post example code as Console Application:
using System;

class ProgramConsole {

private const string StrGivenFn = "Math.Pow(x, 3) + (3 * Math.Pow(x, 2)) -
(10 * x)";

public static double givenFn(double x) {

return (Math.Pow(x, 3) + (3 * Math.Pow(x, 2)) - (10 * x));

// The expression following return statement is

// same as the constant StrGivenFn. How can StrGivenFn be used?

}

static void Main(string[] args) {

Console.WriteLine("f(x) = " + StrGivenFn);

Console.WriteLine("f(x) = " + givenFn(6) + " at x=6");

Console.ReadLine();

}

}



"Bob M" <bobM@NoSpamwrote in message
news:u8****************@TK2MSFTNGP05.phx.gbl...
Hi Nicholas,

Thanks. But I have to use that function (x^3 + 3x^2 - 10x) later in my
application code. If I specify
"Math.Pow(x, 3) + (3 * Math.Pow(x, 2)) - (10 * x)" as string constant at
one place, then how can I use this string constant in the return statement
in the givenFn()method?

My problem is a little bit different. Perhaps my code example did not
elaborate the problem I am trying to convey. The revised code is posted
again:

<%@ Page Language="C#" %>
<script runat="server">

public static double givenFn(double x) {

return (Math.Pow(x, 3) + (3 * Math.Pow(x, 2)) - (10 * x)); // function
expression
}

protected void Page_Load(object sender, EventArgs e) {

Label1.Text = "f(x)=" + "Math.Pow(x, 3) + (3 * Math.Pow(x, 2)) - (10 *
x)";
// Can this second string literal
be retrieved
// from the function expression in
// givenFn() method to avoid
typing (copy/paste

Label2.Text = "f(x) = " + givenFn(6) + " at x=6";
}

</script>
<html><body><form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
</div>
</form></body></html>

May 21 '07 #4
* Bob M wrote, On 21-5-2007 22:27:
For your convenience I post example code as Console Application:
using System;

class ProgramConsole {

private const string StrGivenFn = "Math.Pow(x, 3) + (3 * Math.Pow(x, 2)) -
(10 * x)";

public static double givenFn(double x) {

return (Math.Pow(x, 3) + (3 * Math.Pow(x, 2)) - (10 * x));

// The expression following return statement is

// same as the constant StrGivenFn. How can StrGivenFn be used?

}

static void Main(string[] args) {

Console.WriteLine("f(x) = " + StrGivenFn);

Console.WriteLine("f(x) = " + givenFn(6) + " at x=6");

Console.ReadLine();

}

}
The answer is as you've feared all along, you cannot. At least not
without writing a full blown parser or finding a component that can
interpret your function. It's not in the base class library. Sorry.

Jesse
May 21 '07 #5
Hi Jesse,

I am sorry to hear that "a string literal can not be converted to a C#
expression" (or vice versa).

But I have seen some websites where users can enter a mathematical
expression in a TextBox and gets some result after submitting. I do not
know how they do it. Maybe they use what you mention: full blown parser or
some component.

Bob_M

"Jesse Houwing" <je***********@nospam-sogeti.nlwrote in message
news:uF****************@TK2MSFTNGP06.phx.gbl...
The answer is as you've feared all along, you cannot. At least not without
writing a full blown parser or finding a component that can interpret your
function. It's not in the base class library. Sorry.

Jesse

May 21 '07 #6
Bob M wrote:
For your convenience I post example code as Console Application:
using System;

class ProgramConsole {

private const string StrGivenFn = "Math.Pow(x, 3) + (3 * Math.Pow(x, 2)) -
(10 * x)";

public static double givenFn(double x) {

return (Math.Pow(x, 3) + (3 * Math.Pow(x, 2)) - (10 * x));

// The expression following return statement is

// same as the constant StrGivenFn. How can StrGivenFn be used?

}

static void Main(string[] args) {

Console.WriteLine("f(x) = " + StrGivenFn);

Console.WriteLine("f(x) = " + givenFn(6) + " at x=6");

Console.ReadLine();

}

}
You want to evaluate a C# expression at runtime ?

You can call the compiler.

Below are some code to get you started.

Arne

================================================== ============

using System;
using System.Collections.Generic;
using System.Reflection;
using System.CodeDom.Compiler;

using Microsoft.CSharp;

namespace E
{
public class DynComp
{
private static int n = 0;
private static Dictionary<string,objectm = new
Dictionary<string,object>();
public static double Eval(string expr, double x)
{
object o;
if(m.ContainsKey(expr))
{
o = m[expr];
}
else
{
n++;
string cn = "c" + n;
string src = "using System; public class " + cn + " { public static
double Eval(double x) { return " + expr + "; } }";
CodeDomProvider comp = new CSharpCodeProvider();
CompilerParameters param = new CompilerParameters();
param.GenerateInMemory = true;
param.ReferencedAssemblies.Add("System.dll");
CompilerResults res = comp.CompileAssemblyFromSource(param,
src);
Assembly asm = res.CompiledAssembly;
o = asm.CreateInstance(cn);
m.Add(expr, o);
}
return (double)o.GetType().InvokeMember("Eval",
BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Static |
BindingFlags.InvokeMethod, null, null, new object[] { x });
}
}
public class MainClass
{
private const string StrGivenFn = "Math.Pow(x, 3) + (3 * Math.Pow(x,
2)) - (10 * x)";
public static double GivenFn(double x) {
return (Math.Pow(x, 3) + (3 * Math.Pow(x, 2)) - (10 * x));
}
public static void Main(string[] args)
{
Console.WriteLine(GivenFn(6));
Console.WriteLine(DynComp.Eval("Math.Pow(x, 3) + (3 * Math.Pow(x, 2))
- (10 * x)", 6));
Console.ReadLine();
}
}
}
May 22 '07 #7
Arne Vajhøj wrote:
You want to evaluate a C# expression at runtime ?

You can call the compiler.

Below are some code to get you started.
I'm not sure I'd want to put that on my webpage!
Talk about a security hole! :-)

Alun Harford
May 22 '07 #8
My though exactly... after all,
@"System.Diagnostics.Process.Start(""random.exe"") .Id" is well-formed,
uses only "System" and returns a number ;-p
Even with partial trust I wouldn't want this *near* production code...
unless I really, really trust the input.

But if anyone has a parser...? I'm actually faced with a very similar
problem at the moment; I want to implement a filtered IBindingListView
(from scratch). This is very easy if I use a Predicate<T- but if I
want to support the Filter property? Much harder... DataView uses
ExpressionParser, but this is internal and DataTable specific... does
anybody know of a viable implementation?

I'm thinking I'll live with a Predicate<Tfor now ;-p It meets all my
needs... but it would be quite satisfying to finish the implementation
(since every other IBindingList / IBindingListView contract is met...)

Marc

May 22 '07 #9
Alun Harford wrote:
Arne Vajhøj wrote:
>You want to evaluate a C# expression at runtime ?

You can call the compiler.

Below are some code to get you started.

I'm not sure I'd want to put that on my webpage!
Talk about a security hole! :-)
Good point.

But it is unavoidable if the requirement is to evaluate C#.

Requirements need to change.

Arne
May 23 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Ken McAndrew | last post by:
I am trying to write a regular expression to cover US currency, where the dollar sign and cents are optional. The following string worked when I used it in the ValidationExpression field of a...
2
by: pshvarts | last post by:
(I'm new in SOAP) I get some wsdl file (from apache service ). I tried creating SOAP client with .NET - trying to add Web Reference and get error like: "Custom tool error: Unable to import...
0
by: leslie_tighe | last post by:
Hello, I have a web service that is running in a java server using axis that I want to use from .net. In VS.net 2003 I setup a project with a web reference. Using generated code I am able to...
36
by: Roman Mashak | last post by:
Hello, All! I implemented simple program to eliminate entry from the file having the following structure (actually it's config file of 'named' DNS package for those who care and know): ...
3
by: Zach | last post by:
Hello, Please forgive if this is not the most appropriate newsgroup for this question. Unfortunately I didn't find a newsgroup specific to regular expressions. I have the following regular...
9
by: Bob M | last post by:
If I define an expression or equation, how can I retrieve that expression as string literal? I want to do this so that I could avoid repetitive typing (or copy/paste/change) the same thing at two...
156
by: Lame Duck | last post by:
Hi Group! I have a vector<floatvariable that I need to pass to a function, but the function takes a float * arguement. That's OK, I can convert by doing &MyVector.front(), but when I get back a...
9
by: Eric | last post by:
I am working on a large, old code base and attempting to move it to GCC 4.2. Throughout the code, there is stuff like: char *aVar = "aString"; or void aFunc( char *aVar) { ... } aFunc(...
160
by: DiAvOl | last post by:
Hello everyone, Please take a look at the following code: #include <stdio.h> typedef struct person { char name; int age; } Person;
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.