Can I add a variable in a format string? - c#

I'm new to this and just did my first Hello World program yesterday.
I'm wondering if i can change the f5 to a varible.
Console.WriteLine("{0:f5}", theAnswer);
The 5 would change depending on the user input.
This didn't work, but is it possible to use something like it,
Console.WriteLine("{0:f + myVarible}", theAnswer);
If not, any suggestions on what route I should take would be helpful.

You could try with:
Console.WriteLine("{0}", theAnswer.ToString("f" + myVariable));
Or, if you only have the {0} in:
Console.WriteLine(theAnswer.ToString("f" + myVariable));

You can try solve this by changing your code:
Console.WriteLine("{0:f + myVarible}", theAnswer);
to this
Console.WriteLine("{0}", usersAnswer.ToString("f" + myVariable));

Related

Calling a Python script from C# - changing the script's filepath causes the program to not work

The following code works perfectly without flaw:
public partial class MainForm : Form
{
string pyInterp = File.ReadAllText(Directory.GetCurrentDirectory() + #"\config\pathToPythonInterpreter.txt");
string pyWeather = #"C:\getWeather.py";
public MainForm()
{
InitializeComponent();
UpdateWeather();
}
public void UpdateWeather()
{
labelWeather.Text = PySharp.ExecutePy(pyInterp, pyWeather);
}
}
However, when I change the path to getWeather.py to not be in an arbitrary random location, like this:
string pyWeather = Directory.GetCurrentDirectory() + #"\scripts\getWeather.py";
Then my program no longer obtains the script's output. The script still works: I launched it using IDLE and it completed its function properly. When I call it using C#, the console opens, yet no output is obtained.
The Python script is the following:
from requests import get
from bs4 import BeautifulSoup as soup
r = get("http://www.ilmateenistus.ee/ilm/prognoosid/4-oopaeva-prognoos/")
parsed = soup(r.content, "html.parser")
container = parsed.find("div",{"class":"point kuusiku"})
print(str(container["data-title"]))
(It webscrapes my local weather)
PySharp.ExecutePy() can be viewed here
By far the strangest bug I've ever encountered. Any ideas?
EDIT 1: It seems that C# is indeed reading something from the script. It just appears that this something is.. nothing. I gave the label a default sample text, and after running the program, the label's text is simply changed to an empty string. Hope this incredible discovery helps somehow.
EDIT 2: The program fails to call the script correctly when its filepath contains spaces. For example:
C:\foo bar\testing\pyWeather.py
does not work!
Try surrounding the path that contains spaces with 2 double quotes.
For e.g.
string pyWeather = #"""C:\Users\[myname]\Documents\Visual Studio 2017\Projects\testing\testing\scripts\getWeather.py""";
Similarly, you can do string pyWeather = Directory.GetCurrentDirectory() + #"\scripts\getWeather.py"; followed by pyWeather = "\"" + pyWeather + "\"";.
I would want you to return the answer instead of printing. Printer is an I/O based solution to display. So it will work super fine with IDLE however it may not return results as you expected. I strongly believe this will solve your problem.
instead of printing please try return. I can give more support after trying this.
return(str(container["data-title"]))

Why does StringBuilder.AppendLine not add a new line with some strings?

I'm trying to use stringbuilder to create a body of string to be used in a text (not HTML) email. However some lines (where i include dynamic data, a new line is not added, but in some the newline works as intended.
Is there something basic i'm missing when using the stringbuilder class or is there some more fundamental process that should be happening?
in the below code:
sbUser.AppendLine("Please find below confirmation of your registration details. If any of these details are incorrect, please email someone#somewhere.com");
sbUser.AppendLine();
sbUser.AppendLine("Selected event : " + ContentPage.FetchByID(int.Parse(ddlEvent.SelectedValue)).PageTitle);
sbUser.AppendLine("Date of event : " + thisEvent.EventStartDate.ToString("dd MMM yyyy"));
sbUser.AppendLine("==============================================================");
sbUser.AppendLine();
(ContentPage and thisEvent are custom classes built using Subsonic(v2). PageTitle is an output type of string)
is get this as an output:
Please find below confirmation of your registration details. If any of these details are incorrect, please email someone#somewhere.com
Selected event : My Event Date of event : 16 Sept 2012 ==============================================================
as you can see, everything after the 3rd line in the code makes everything go on to one line.
however, further down the code i use:
sbRR.AppendLine("First name : " + txtFirstname.Text.Trim());
sbRR.AppendLine("Surname : " + txtSurname.Text.Trim());
etc,
and all these appear on seperate lines correctly. I can't see why this is happening.
the email is composed as such
mailMessage.Body = sbUser.ToString() + sbRR.ToString();
adding the following code:
sbUser.AppendLine("Selected event : " + ContentPage.FetchByID(int.Parse(ddlEvent.SelectedValue)).PageTitle + Environment.NewLine);
sbUser.AppendLine("Date of event : " + thisEvent.EventStartDate.ToString("dd MMM yyyy") + Environment.NewLine);
produces the following output:
Selected event : My Event
Date of event : 16 Sept 2012
==============================================================
which works i suppose, except it's added 2 newlines (the AppendLine and the Environment.NewLine). it seems that pulling the data directly straight from the database into a stringbuilder seems to be messing with the line ending. Even if I add text after the database pull, it still stays on one line.
UPDATE
doing
StringBuilder.Append("blah"+Environment.NewLine)
produces the correct result, however i'm still not understanding why that works and .AppendLine("blah"+<database content>) doesn't work.
I know the question is old and has been marked as answered, but I thought I'd add this here in case anyone else comes across this as it's the first hit on Google for StringBuilder.AppendLine() not working.
I had the same problem and it turned out to be an Outlook issue. Outlook re-formats text based emails by removing extra line breaks. You can click "We removed extra line breaks in this message -> Restore line breaks" in the header of the individual email, or change the setting that does this nasty little trick "Options->Mail->Message Format->Remove extra line breaks in plain text messages"
The workaround (since you can't control the settings on every potential email target) I found here Newsletter Formatting And The Remove Extra Line Breaks Issue.
Basically, if you add two white space characters to the beginning of each line, Outlook won't reformat the email.
Here's an extension method to help (method name is a bit verbose so change to your liking :))
namespace System.Text
{
public static class StringBuilderExtensions
{
public static void AppendLineWithTwoWhiteSpacePrefix(this StringBuilder sb, string value)
{
sb.AppendFormat("{0}{1}{2}", " ", value, Environment.NewLine);
}
public static void AppendLineWithTwoWhiteSpacePrefix(this StringBuilder sb)
{
sb.AppendFormat("{0}{1}", " ", Environment.NewLine);
}
}
}
Instead of
sbUser.AppendLine();
Try using
sbUser.Append(Environment.NewLine);
No idea why this works...
use Environment.NewLine
sbUser.AppendLine("Please find below confirmation of your registration details. If any of these details are incorrect, please email someone#somewhere.com");
sbUser.AppendLine(Environment.NewLine);
sbUser.AppendLine("Selected event : " + ContentPage.FetchByID(int.Parse(ddlEvent.SelectedValue)).PageTitle);
sbUser.AppendLine("Date of event : " + thisEvent.EventStartDate.ToString("dd MMM yyyy"));
sbUser.AppendLine("==============================================================");
sbUser.AppendLine(Environment.NewLine);
use Environment.NewLine after each line or where you want new line
eg:-
sbUser.AppendLine("Please find below confirmation of your registration details. If any of these details are incorrect, please email someone#somewhere.com" + Environment.NewLine);
sbUser.AppendLine("Selected event : " + ContentPage.FetchByID(int.Parse(ddlEvent.SelectedValue)).PageTitle);
Windows 10 Insider preview Build 15007. The Default Line Terminator and the Environment.NewLine are both "\n". To use "\r\n" I had to create a string constant and use it instead.
First
sbUser.Appendline();
Second
sbUser.Append("texto loco ");
Voila!
=)

Variables, strings and increasing frustration

I'm pretty new to C# and am having a mare trying to get what should be a simple task to work, in a nutshell I've written a PowerShell script to create VApps within a vSphere environment, the PoSh script works perfectly, next I have created (my first go) a Windows Console Application to run (initially) this script with user input, here's the problem, within my console app I'm using Process.Start to call my PoSh script and pass parameters, but, they come out joined up and completely missing the last parameter, here's the line in question:
Process.Start("Powershell.exe","-ExecutionPolicy bypass F:\\hello.ps1 -Location " + location + " -AppName" + appname);
AppName is completely ignored and Location tends to come out as -Locationanywhere instead of -Location Anywhere, I'm sure it's something basic and I've trawled the usual group and RTFM but no joy!
Hello.ps1 is a test script that just records the parameters passed to it so I can check the output before touching my real script.
Any help gratefully received.
You're lacking a space between -AppName and the double quotes.
string.Format is a useful method in .Net - it allows you to easily replace placeholders with dynamic content in a way that makes viewing the 'complete' string intuitive:
string parameters = string.Format("-ExecutionPolicy bypass F:\\hello.ps1 -Location {0} -AppName {1}", location, appName);
Process.Start("Powershell.exe", parameters);
I'm not sure, but I think you need an space between -AppName and the appname
" -AppName " + appname
It's all I can help you :(
Might I suggest using String.Format() instead of using the + operator?
String.Format("-ExecutionPolicy bypass F:\\hello.ps1 -Location {0} -AppName {1}", location, appname)

Retrieve variable value from flash

I have an AxShockwaveFlash object in a Windows Forms application, and load a (AS3) movie into it with LoadMovie. The movie plays correctly, but I am having a problem getting a variable from flash.
I have tried using GetVariable but it always returns an empty string. How can I get the value of a variable from flash?
I think the new security policy for AVM2 requires you to explicitly expose the variables/functions to the container application using ExternalInterface.
If you can't edit the swf, I can't think of a way to get access to them. It was really easy with AS2 though, if you defined it, you could get and set it via javascript/C#/whatever without any extra code in the swf.
Yo can use fscommand method to talk to C# from shockwave player:
fscommand("sendCmd", arg);
to catch value in C# use
flashPlayer.FSCommand += new AxShockwaveFlashObjects._IShockwaveFlashEvents_FSCommandEventHandler(flashPlayer_FSCommand);
....
void flashPlayer_FSCommand(object sender, AxShockwaveFlashObjects._IShockwaveFlashEvents_FSCommandEvent e)
{
tbOut.Text += e.command + " (" + e.args + ")" + "\r\n";
}

Query string problem

Response.Redirect(my site's url + "editques/" + "QuesID/" + QuesID + "/" );
Redirecting as shown above...In the editques.aspx page, whenI debug, I see the Query String's value as {QuesID=jhgjgjhjk&PID=jhhkjkj}
Where on earth did this PID came from!??
There must be some component that needs to persist a value between postbacks and is using the query string for that purpose.
Update: Are you by any chance displaying paginated data on the page? PID might stand for page id and might be generated by the component that is handling paging.
var c = new HttpValueCollection();
c.Add(HttpUtility.ParseQueryString(Request.Url.Query));
if (!string.IsNullOrEmpty(c["PID"]))
c.Remove("PID");
Are you sure you aren't redirecting before this line or after this line?
I don't even see the FAQID in that Qstring..

Categories

Resources