I'm getting this error:
would not find a GetExtension method
Code:
public static void Main()
{
string[] arr = {"abc.txt", "asd.TXT","bvc.pdf","fgd.txt","hss.pdf","djhd.xml"};
var arrp = arr.Select(file=>Path.GetExtension(file).TrimStart('.').ToLower()).GroupBy(x=>x,(ext,extcnt)=>new
{
Extension = ext,
count=extcnt.Count()
});
foreach(var v in arrp)
{
Console.WriteLine("{0} files(s) with {1} Extension", v.Count,v.Extension );
Console.ReadLine();
}
}
How can I fix it?
First check, do you have added the using statment? using System.IO;
Second change your code line:
Console.WriteLine("{0} files(s) with {1} Extension", v.Count, v.Extension);
to:
Console.WriteLine("{0} files(s) with {1} Extension", v.count, v.Extension);
i had created a new console application. This example works in my enviroment:
using System;
using System.IO;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string[] arr = { "abc.txt", "asd.TXT", "bvc.pdf", "fgd.txt", "hss.pdf", "djhd.xml" };
var arrp = arr.Select(file => Path.GetExtension(file).TrimStart('.').ToLower()).GroupBy(x => x, (ext, extcnt) => new
{
Extension = ext,
count = extcnt.Count()
});
foreach (var v in arrp)
{
Console.WriteLine("{0} files(s) with {1} Extension", v.count, v.Extension);
Console.ReadLine();
}
}
}
}
i get this result:
Important: this is a console application! not a asp.net application! (you have added the asp.net tag.. )
Related
I've been trying to parse and search for a specific word in a big string, but I can't seem to be able to figure it out. I have created a script that connects a Twitch Channel's chat into unity.
An example of a message would be:
"#badge-info=subscriber/4;badges=moderator/1,subscriber/3,bits/1;bits=1;color=;display-name=TwitchUser1234;emotes=;flags=;id=da6ec4c6-af61-4346-abc-123456789;mod=1;room-id=12345678;subscriber=1;tmi-sent-ts=160987654321;turbo=0;user-id=123456789;user-type=mod :TwitchUser1234#TwitchUser1234.tmi.twitch.tv PRIVMSG #thechannelyouarewatching :PogChamp1 Another Test Bit"
I tried parsing and searching for the string 'bits' the message by doing:
private void GameInputs(string ChatInputs)
{
string Search;
Search = ChatInputs.Split(";", "=");
if(string "bits" in Search)
{
print("I made it here.");
}
}
I'm at a complete loss and have no idea how to do this. Any help is appreciated.
If my full code is needed it is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.ComponentModel;
using System.Net.Sockets;
using System.IO;
public class TwitchChat : MonoBehaviour
{
private TcpClient twitchClient;
private StreamReader reader;
private StreamWriter writer;
public string username, password, channelName; // http://twitchapps.com/tmi
// Start is called before the first frame update
void Start()
{
Connect();
}
void Update()
{
if(!twitchClient.Connected)
{
Connect();
}
ReadChat();
}
private void Connect()
{
twitchClient = new TcpClient("irc.chat.twitch.tv", 6667);
reader = new StreamReader(twitchClient.GetStream());
writer = new StreamWriter(twitchClient.GetStream());
writer.WriteLine("PASS " + password);
writer.WriteLine("NICK " + username);
writer.WriteLine("USER " + username + " 8 * :" + username);
writer.WriteLine("JOIN #" + channelName);
writer.WriteLine("CAP REQ :twitch.tv/tags");
writer.Flush();
}
private void ReadChat()
{
if (twitchClient.Available > 0)
{
var message = reader.ReadLine();
print(message);
GameInputs(message);
}
}
private void GameInputs(string ChatInputs)
{
string Search;
Search = ChatInputs.Split(";", "=");
if(string "bits" in Search)
{
print("I made it here.");
}
}
}
If you want to pull the value of "bits=xx" out, this would do it:
var b = value.Split(';').FirstOrDefault(s => s.StartsWith("bits="))?[5..];
b will be null if "bits=" is not present
If you're going to parse a lot of values out of this string consider turning it into a dictionary:
var c = new []{'='};
var d = value.Split(';').ToDictionary(s => s.Split(c,2)[0], s => s.Split(c,2)[1]);
It's slightly inefficient to split twice, if it bothers you, you can sub string:
value.Split(';').ToDictionary(s => s[..s.IndexOf('=')], s => s[s.IndexOf('=')+1..]);
This gives a dictionary of string, so you can do like:
if(d.ContainsKey("bits")){
var bits = int.Parse(d["bits"]);
...
String has a method Contains(string) that does the job:
if (ChantInputs.Contains("bits")
{
print("I made it here.");
}
You can try below.
private void GameInputs(string ChatInputs)
{
string[] Search = ChatInputs.Split(new char[] { ';', '=' });
foreach(string s in Search)
{
if(s == "bits")
{
print("I made it here.");
}
}
}
Below is the working code.
using System;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
string str = "one;two;test;three;test+test";
string[] strs = str.Split(new char[] { ';', '+' });
foreach(string s in strs)
{
if(s == "test")
{
Console.WriteLine(s);
}
}
Console.ReadLine();
}
}
}
I want to offer the possibly to compile and run code (Csharp Classes) in .NET core 3 for purpose of scripting. The scripts (classes) shall be loaded from the file system and injected in an existing (static) assembly.
https://laurentkempe.com/2019/02/18/dynamically-compile-and-run-code-using-dotNET-Core-3.0/ (using AssemblyContext) seems to be a valid approach for this.
Is there a simpler solution (with less overhead) if I do not have the need to isolate the script code in an assembly?. (Debugging should be possible)
There is a solution at https://laurentkempe.com/2019/02/18/dynamically-compile-and-run-code-using-dotNET-Core-3.0/.
To save time, here is a variant of the program that runs a single file, supports LINQ, and classes from current project DLL :
Program.cs
using System.Linq;
using DynamicRun.Builder;
namespace DynamicRun
{
class Program
{
static void Main(string[] args)
{
var compiler = new Compiler();
var runner = new Runner();
byte[] compiled = compiler.Compile(args.FirstOrDefault());
runner.Execute(compiled, args[1..args.Length]);
}
}
}
Compiler.cs
using System;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Text;
namespace DynamicRun.Builder
{
internal class Compiler
{
public byte[] Compile(string filepath)
{
var sourceCode = File.ReadAllText(filepath);
using (var peStream = new MemoryStream())
{
var result = GenerateCode(sourceCode).Emit(peStream);
if (!result.Success)
{
Console.WriteLine("Compilation done with error.");
var failures = result.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error);
foreach (var diagnostic in failures)
{
Console.Error.WriteLine("{0}: {1}", diagnostic.Id, diagnostic.GetMessage());
}
return null;
}
Console.WriteLine("Compilation done without any error.");
peStream.Seek(0, SeekOrigin.Begin);
return peStream.ToArray();
}
}
private static CSharpCompilation GenerateCode(string sourceCode)
{
var codeString = SourceText.From(sourceCode);
var options = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp7_3);
var parsedSyntaxTree = SyntaxFactory.ParseSyntaxTree(codeString, options);
var references = new MetadataReference[]
{
MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
MetadataReference.CreateFromFile(typeof(Console).Assembly.Location),
MetadataReference.CreateFromFile(typeof(System.Linq.Enumerable).Assembly.Location),
MetadataReference.CreateFromFile(typeof(System.Runtime.AssemblyTargetedPatchBandAttribute).Assembly.Location),
MetadataReference.CreateFromFile(typeof(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo).Assembly.Location),
// Todo : to load current dll in the compilation context
MetadataReference.CreateFromFile(typeof(Family.Startup).Assembly.Location),
};
return CSharpCompilation.Create("Hello.dll",
new[] { parsedSyntaxTree },
references: references,
options: new CSharpCompilationOptions(OutputKind.ConsoleApplication,
optimizationLevel: OptimizationLevel.Release,
assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default));
}
}
}
Runner.cs
using System;
using System.IO;
using System.Runtime.CompilerServices;
namespace DynamicRun.Builder
{
internal class Runner
{
public void Execute(byte[] compiledAssembly, string[] args)
{
var assemblyLoadContext = LoadAndExecute(compiledAssembly, args);
for (var i = 0; i < 8 && assemblyLoadContext.IsAlive; i++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
Console.WriteLine(assemblyLoadContext.IsAlive ? "Unloading failed!" : "Unloading success!");
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static WeakReference LoadAndExecute(byte[] compiledAssembly, string[] args)
{
using (var asm = new MemoryStream(compiledAssembly))
{
var assemblyLoadContext = new SimpleUnloadableAssemblyLoadContext();
var assembly = assemblyLoadContext.LoadFromStream(asm);
var entry = assembly.EntryPoint;
_ = entry != null && entry.GetParameters().Length > 0
? entry.Invoke(null, new object[] {args})
: entry.Invoke(null, null);
assemblyLoadContext.Unload();
return new WeakReference(assemblyLoadContext);
}
}
}
}
I tried to delete a test key through a C# script. The following code is my script, I also added admin value in manifest file for this project UAC. But it still doesn't work. Even restarted Visual Studio 2017 with Admin mode.
The error message said Cannot write to the registry key.
Not sure what's wrong in the script.
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32;
using System.Security;
using System.Security.AccessControl;
using System.Security.Principal;
namespace temp_code_tester
{
class Program
{
static void Main(string[] args)
{
//Get current login account info from another Class
//string userName = WindowsIdentity.GetCurrent().Name;
//var SecCheck = new SecutriyProcesser();
//SecCheck.AddRule(userName);
var RunCheck = new AccessRegistry();
RunCheck.ACL("Test");
}
}
class AccessRegistry
{
public void ACL(string name)
{
Console.WriteLine("Getting the registry keys.....");
Console.WriteLine("---------------------------------------------\n");
//Open the SOFTWARE keys and input those keys into array
RegistryKey SoftKey = Registry.LocalMachine.OpenSubKey(#"SOFTWARE");
string[] lists = SoftKey.GetSubKeyNames();
foreach (string KeyName in lists)
{
Console.WriteLine(KeyName);
}
foreach (string value in lists)
{
if (value.Contains(name)) // if we find the key, then lists all subkeys
{
//Registry.LocalMachine.DeleteSubKeyTree(value);
Console.WriteLine("\nMatch one: {0}", value);
var RightKey = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\" + value);
string[] SubList = RightKey.GetSubKeyNames();
foreach (string SubValue in SubList)
{
Console.WriteLine("Folder: {0} is under this key", SubValue);
}
if (SubList.Length > 1)
{
try
{
SoftKey.DeleteSubKeyTree(value);
Console.WriteLine("\nThe folder {0} has been removed", value);
}
catch (Exception er)
{
Console.WriteLine("Error: {0}", er.Message);
}
}
else
{
try
{
SoftKey.DeleteSubKey(value);
}
catch (Exception)
{
throw;
}
}
}
}
SoftKey.Close();
}
}
class SecutriyProcesser
{
// A method about add enough roles for current window account
public void AddRule(string userName)
{
RegistrySecurity rs = new RegistrySecurity();
rs.AddAccessRule(new RegistryAccessRule(userName,
RegistryRights.FullControl,
InheritanceFlags.ObjectInherit,
PropagationFlags.InheritOnly,
AccessControlType.Allow));
}
// Try to list the security level
public void ShowSecurity(RegistrySecurity security)
{
Console.WriteLine("\r\nCurrent access rules:\r\n");
foreach (RegistryAccessRule ar in security.GetAccessRules(true, true, typeof(NTAccount)))
{
Console.WriteLine(" User: {0}", ar.IdentityReference);
Console.WriteLine(" Type: {0}", ar.AccessControlType);
Console.WriteLine(" Rights: {0}", ar.RegistryRights);
Console.WriteLine(" Inheritance: {0}", ar.InheritanceFlags);
Console.WriteLine(" Propagation: {0}", ar.PropagationFlags);
Console.WriteLine(" Inherited? {0}", ar.IsInherited);
Console.WriteLine();
}
}
}
}
You forgot the 'writable' parameter of the 'OpenSubkey' method.
Try this :
RegistryKey SoftKey = Registry.LocalMachine.OpenSubKey(#"SOFTWARE", true);
It should work like this.
EDIT : This method will probably fail if you don't run Visual Studio as Administrator while debugging.
I started experimenting a bit with CodeDom and made simple Application which collects sourcecode from the user input and tries to compile it with C#-Syntax.
For those who want to try the whole proccess, type end... to finish up the sourcecode entry.
Here's the example:
using System;
using System.Collections;
using System.Reflection;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
namespace CodeDomTest
{
class Program
{
static void Main(string[] args)
{
getTestCode();
}
public static Assembly getTestCode()
{
CompilerParameters CompilerOptions = new CompilerParameters(
assemblyNames: new String[] { "mscorlib.dll", "System.dll", "System.Core.dll" },
outputName: "test.dll",
includeDebugInformation: false)
{ TreatWarningsAsErrors = true, WarningLevel = 0, GenerateExecutable = false, GenerateInMemory = true };
List<String> newList = new List<String>();
String a = null;
while(a != "end...")
{
a = Console.ReadLine();
if (!a.Equals( "end..."))
newList.Add(a);
}
String[] source = { "class Test {static void test() {System.Console.WriteLine(\"test\");}}" };
source = newList.ToArray();
CSharpCodeProvider zb = new CSharpCodeProvider(new Dictionary<String, String> { { "CompilerVersion", "v4.0" } });
CompilerResults Results = zb.CompileAssemblyFromSource(CompilerOptions, source);
Console.WriteLine(Results.Errors.HasErrors);
CompilerErrorCollection errs = Results.Errors;
foreach(CompilerError z in errs)
{
Console.WriteLine(z.ErrorText);
}
if (!(errs.Count > 0))
{
AssemblyName assemblyRef = Results.CompiledAssembly.GetName();
AppDomain.CurrentDomain.Load(assemblyRef);
//foreach (String a in )
Console.WriteLine(Results.CompiledAssembly.FullName.ToString());
Type tempType = Results.CompiledAssembly.GetType("Test");
MethodInfo tempMethodInfo = tempType.GetMethod("test", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public);
if (tempMethodInfo != null)
tempMethodInfo.Invoke(null,null);
}
Console.ReadLine();
return null;
}
}
}
Now as you can see, basically it compiles the following code:
class Test {static void test() {System.Console.WriteLine(\"test\");}}
Which works fine if you enter it like that (without the ") as userinput into the program. But as soon as you insert a line break by pressing enter after one finished line, the compiling breaks with several errors. It seems like it would evaluate each line as own program by giving following statements:
} expected
Expected class, delegate, enum, interface, or struct
A namespace cannot directly contain members such as fields or methods
A namespace cannot directly contain members such as fields or methods
Type or namespace definition, or end-of-file expected
Type or namespace definition, or end-of-file expected
For following input:
class Test
{
static void test()
{
System.Console.WriteLine
("test");
}
}
Do I have to break user (custom) entries down to one line then?
Each line in sources should contain complete source code not a single line of code. Since you're gathering the code line by line into your source array, you'll have to collapse it into a single string then add that string to an array to pass to CompileAssemblyFromSource
Try this:
while (a != "end...")
{
a = Console.ReadLine();
if (!a.Equals("end..."))
newList.Add(a);
}
string code = string.Join("\r\n", newList);
string[] source = new string[] { code };
my program is intended to search for images url inside a string according to specific keywords. it actually works fine, only problem is the "search not found" error.
for some reason its like the code doesn't get to this "if" and wont return any error if there is no match found (last if).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Text.RegularExpressions;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
using (WebClient client = new WebClient())
{
int count = 0;
Regex SearchItem = new Regex("http://.+?\\.jpg");
string SearchValue = "fgdfgdf";
string htmlCode = "fsdflkjsdfkjsdfkjdsflkhttp://www.dssdtanya.jpgfsdf;ldsmfs;dlfms;dmfs";
Match matches = SearchItem.Match(htmlCode);
while (matches.Success)
{
string test = matches.ToString();
if (test.Contains(SearchValue))
{
count++;
Console.WriteLine("Result #{0}: '{1}' found in the source code at position {2}.",count, matches.Value, matches.Index);
matches = matches.NextMatch();
}
}
Console.WriteLine(count);
if (count == 0) { Console.WriteLine("search not found."); }
Console.ReadKey();
}
}
}
}
Your program enters an infinite loop if the first test doesn't contain the search value. Change your code to this:
while (matches.Success)
{
string test = matches.ToString();
if (test.Contains(SearchValue))
{
count++;
Console.WriteLine("Result #{0}: '{1}' found in the source code at position {2}.", count, matches.Value, matches.Index);
}
matches = matches.NextMatch(); //moved this outside the if
}