How to create C# string object inside .ps1 file [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
The below C# snippet is embedded in a powershell (.ps1) file and generated an System.Management.Automation.RuntimeException. Removing "string s" and the exception goes away. Tried to use uppercase "String" and tried to add namespace "System.String" and various other approaches but still get the exception. This is driving me nuts, please help me understand why this is happening.
$code = #"
public static class foo
{
public static bool check()
{
string s;
return false;
}
}
Code is invoked like this;
try
{
Add-Type -TypeDefinition $code -Language CSharp
}
catch{} // ignore TYPE_ALREADY_EXISTS exception
$res = [foo]::check();
Here is exception details;
Exception: System.Management.Automation.RuntimeException: unable to find type [foo].
TargetObject: foo
CategoryInfo: InvalidOperation (foo:Typename) [], RuntimeException
FullyQualifiedErrorId: TypeNotFound
InvocationInfo: System.Management.Automation.InvocationInfo

$code = #"
public static class foo {
public static bool check() {
string s;
return false;
}
}
"#
Add-Type -TypeDefinition $code -Language CSharp
produces
Warning as Error: The variable 's' is declared but never used
It will not allow you to declare unused variables.

Related

I'm a beginner and I can't solve some errors within C# code [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm new to C# and I'm currently learning it step by step and I also exercise at every chapter. I'm trying to make a small mad lipz game with what I learned so far but it's not working, something is missing and I think it has to be with the functions.
I'm getting these errors :
CS0103 The name 'color' does not exist in the current context
CS0103 The name 'noun' does not exist in the current context
CS0103 The name 'person' does not exist in the current context
My code:
using System;
namespace Tutorial
{
class Program
{
static void Main(string[] args)
{
Words();
Game();
Console.ReadLine();
}
static void Words()
{
Console.Write(" Write a color: ");
string color = Console.ReadLine();
Console.Write(" Write a noun: ");
string noun = Console.ReadLine();
Console.Write(" Write a person: ");
string person = Console.ReadLine();
}
static void Game()
{
Console.WriteLine("Roses are " + color);
Console.WriteLine( noun + " is dead ");
Console.WriteLine("I should vote " + person);
}
}
}
Thanks a lot!
color, noun and person are local variables in the Words method, and cannot be used outside of it. One way to solve this problem is to declare them as (static) members instead of local variables.
The problem is the scope of the program. The function Words() does not know of the variables, as they are defined in the function Game(). One possible solution would be to add the three variables as parameters to the function Words().
static void Game(string person, string color, string noun) {}

C# - How do I put the Function Regex working? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
Good morning,
I am doing a page for my intership and I found this function but it isn't working, can someone help?
Thank you in advance.
string _id = this.txtIdGrupo.Text;
if (!Regex.IsMatch(_id, #"^\d+$"))
return false;
The output says this:
error CS0103: The name 'Regex' does not exist in the current context
this is not an issue with the bit of code you showed.
This is a namespace issue at the very top of your file.
The solution should be https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/namespaces/
using System;
using System.Text.RegularExpressions;
public class Test
{
public static void Main ()
{
var isNumeric1 = IsNumeric("1");
Console.WriteLine(isNumeric1);
var isNumeric2 = IsNumeric("HelloWorld");
Console.WriteLine(isNumeric2);
//call IsNumeric with the value of this.txtIdGrupo.Text like this
//var isNumeric = IsNumeric(this.txtIdGrupo.Text);
}
private static bool IsNumeric(string str)
{
string id = str;
if (!Regex.IsMatch(id, #"^\d+$"))
return false;
return true;
}
}
See it in action:
https://dotnetfiddle.net/I7cAKs
notice the "using System.Text.RegularExpressions"
Using tools like Resharper and similar will definitely give you hints and will improve your day to day !
Make sure you have the System.Text.RegularExpressions
is imported

How to resolve errors CS1003: Syntax error, '(' expected, and error CS1031: Type expected? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am creating a 2d platform game in the Unity Engine Version Num - 2018.4.9f1 with c# compiled with Visual Studio Version Num - 1.38.1.
The console in Unity Engine is showing two errors listed below with the code I have in the Visual Studio.
error CS1003: Syntax error, '(' expected
error CS1031: Type expected
My code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof)(Text))]
public class CountdownText : MonoBehaviour {
public delegate void CountdownFinished();
public static event CountdownFinished OnCountdownFinished;
Text countdown;
void OnEnable() {
countdown = GetComponent<Text>();
countdown.text = "3";
StartCoroutine("Countdown");
}
IEnumerator Countdown() {
int count = 3;
for (int i = 0; i < count; i++) {
countdown.text = (count - i).ToString();
yield return new WaitForSeconds(1);
}
OnCountdownFinished();
}
}
RequireComponent(typeof)(Text)) is wrong. It should be RequireComponent(typeof(Text))
The typeof operator obtains the System.Type instance for a type.

Have PowerShell script use C# code, then pass arguments to Main method

I found a technet blog article the said it was possible to have PowerShell use C# code.
Article: Using CSharp (C#) code in Powershell scripts
I found the format I need to get the C# code to work in PowerShell, but if it don't pass the Main method an argument ([namespace.class]::Main(foo)) the script throws an error.
Is there a way I can pass a string of "on" or "off" to the main method, then depending on which string is passed run an if statement? If this is possible can you provide examples and/or links?
Below is the way I'm currently trying to structure my code.
$Assem = #( //assemblies go here)
$source = #"
using ...;
namespace AlertsOnOff
{
public class onOff
{
public static void Main(string[] args )
{
if(args == on)
{//post foo }
if(arge == off)
{ //post bar }
}
"#
Add-Type -TypeDefinition $Source -ReferencedAssumblies $Assem
[AlertsOnOff.onOff]::Main(off)
#PowerShell script code goes here.
[AlertsOnOff.onOff]::Main(on)
Well to start, if you are going to compile and run C# code, you need to write valid C# code. On the PowerShell side, if you invoke Main from PowerShell, you need to pass it an argument. PowerShell will automatically put a single argument into an array for you, but it won't insert an argument if you don't have one. That said, its not clear why this is in a Main method. It's not an executable. It could very well just have two static methods, TurnOn and TurnOff. The code below compiles and runs, modify as you see fit:
$source = #"
using System;
namespace AlertsOnOff
{
public class onOff
{
public static void Main(string[] args)
{
if(args[0] == `"on`")
{
Console.WriteLine(`"foo`");
}
if(args[0] == `"off`")
{
Console.WriteLine(`"bar`");
}
}
}
}
"#
Add-Type -TypeDefinition $Source
[AlertsOnOff.onOff]::Main("off")
# Other code here
[AlertsOnOff.onOff]::Main("on")

Possibly mistaken empty statement warning [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I'm getting a “Possibly mistaken empty statement” warning when I compile this code:
class Lab6
{
static void Main(string[] args)
{
Program fileOperation = new Program();
Console.WriteLine("Enter a name for the file:");
string fileName = Console.ReadLine();
if (File.Exists(fileName))
{
Console.WriteLine("The file name exists. Do you want to continue appendng ? (Y/N)");
string persmission = Console.ReadLine();
if (persmission.Equals("Y") || persmission.Equals("y"))
{
fileOperation.appendFile(fileName);
}
}
else
{
using (StreamWriter sw = new StreamWriter(fileName)) ;
fileOperation.appendFile(fileName);
}
}
public void appendFile(String fileName)
{
Console.WriteLine("Please enter new content for the file - type Done and press enter to finish editing:");
string newContent = Console.ReadLine();
while (newContent != "Done")
{
File.AppendAllText(fileName, (newContent + Environment.NewLine));
newContent = Console.ReadLine();
}
}
}
I tried to fix it, but I couldn't. What does this warning mean and where's the problem?
A “Possibly mistaken empty statement” warning means there's a statement in your code, would should be compound (i.e. contain a “body” like this: statement { ... more statement ... }), but instead of the body there a semicolon ; which terminates the statement. You should immediately know what and where's wrong, just by double-clicking on the warning a navigating to the respective line of code.
Common mistakes like this look like:
if (some condition) ; // mistakenly terminated
do_something(); // this is always executed
if (some condition); // mistakenly terminated
{
// this is always executed
... statement supposed to be the 'then' part, but in fact not ...
}
using (mySuperLock.AcquiredWriterLock()); // mistakenly terminated
{
... no, no, no, this not going to be executed under a lock ...
}
Specifically, in your code in this statement:
using (StreamWriter sw = new StreamWriter(fileName)) ;
there's a ; at the end, making the using empty (=useless). The immediately following line of code:
fileOperation.appendFile(fileName);
has nothing to do with any StreamWriter whatsoever, so there's apparently something missing in your code (or something left over — the using, probably?).

Categories