How can i get lines of code / fetch declaration in c#? [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Hi can anyone tell me that how can I fetch lines of code from C# code.
For example, I have following code in c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyCodeHelp
{
class MultiplicationProgram
{
public int Multiplication(int Firstnumber, int SecondNumber)
{
int Result = (Firstnumber * SecondNumber);
return Result;
}
}
}
So please tell me how can I fetch the following code from the code above and display it in a label or panel?
public int Multiplication(int Firstnumber, int SecondNumber)
{
int Result = (Firstnumber * SecondNumber);
return Result;
}

Get your panel/label name and just do this:
labelName.Text = Result.ToString();

You cannot get the code from the compiled dll, you have to include the code as a resource or as loose files. One way to do this is to add an MSBuild step that causes all Compile items to be embedded as EmbeddedResources.
In your .csproj file, add the below to the end:
Before:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<!-- ... -->
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
After:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<!-- ... -->
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Target Name="CodeAsResource" BeforeTargets="BeforeBuild">
<ItemGroup>
<EmbeddedResource Include="#(Compile)" />
</ItemGroup>
</Target>
</Project>
Then you can access it as a resource:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Resources;
using System.Text;
using System.Threading.Tasks;
namespace Codeception
{
class Program
{
static void Main(string[] args)
{
var code = getcode("Program.cs");
Console.WriteLine(code);
}
private static string getcode(string filename)
{
using (var sr = new StreamReader(typeof(Program).Assembly.GetManifestResourceStream("Codeception." + filename)))
{
return sr.ReadToEnd();
}
}
}
}

Here is an example:
private void Form1_Load(object sender, EventArgs e)
{
string filePath = #"";
using (var sr = new StreamReader(filePath))
{
string line;
while ((line = sr.ReadLine()) != null)
{
label1.Text += "\n" + line;
}
}
}

Well, I imagine you want to fetch some lines from the source code you wrote, right?
First of all, you need to ship your code (or a text copy of your code) with your binaries, and put it in a known path.
Then, you can Open the file with File.OpenText method (example in https://msdn.microsoft.com/en-us/library/system.io.file.opentext(v=vs.110).aspx ).
To get specific content from the file (which is the StreamReader you received as return from OpenText method), you can call ReadLine method (example in https://msdn.microsoft.com/en-us/library/system.io.streamreader.readline(v=vs.110).aspx) and search wit String compares (https://msdn.microsoft.com/en-us/library/system.string.compare(v=vs.110).aspx) if you found the piece of code you are looking for.
If you are thinking of changing the code later, I recommend you put the code you would like to share inside a "region" tag (https://msdn.microsoft.com/en-us/library/9a1ybwek.aspx). This way you can look for that region specifically, and you don't need to worry about changing your code.
I hope I could help you.

Related

C#: Unhandled exception. System.TypeLoadException: Could not load type 'System.Drawing.Color'

ANSWER for this question thanks to Jeremy C.:
There is no KeePass nuget package for the Net5.0 yet. Thats why there is that error message. Thanks Jeremy C. for the help and answers.
QUESTION:
Im getting this error after starting my solution.
Unhandled exception. System.TypeLoadException: Could not load type 'System.Drawing.Color' from assembly 'Splat, Version=3.0.0.0, Culture=neutral, PublicKeyToken=null'.
Already used google and tried to find a fix for it and also red all articles about similiar errors like "System.Drawing.Font" or "System.Drawing.Image". But theres nothing really helpful and nothing really informative about 'System.Drawing.Color'.
Ive got the code example and package from here:
github.com/wismna/ModernKeePassLib
This is my code:
.csproj
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="ModernKeePassLib" Version="2.45.1" />
<PackageReference Include="System.Drawing.Common" Version="5.0.2" />
</ItemGroup>
</Project>
And:
using ModernKeePassLib;
using ModernKeePassLib.Interfaces;
using ModernKeePassLib.Keys;
using ModernKeePassLib.Serialization;
using System;
using System.Linq;
using System.Text;
namespace KeePasso
{
class Program
{
static void Main()
{
var dbpath = #"C:\Users\prusinma\Desktop\KeePassDatabase\Database.kdbx";
var keypath = #"C:\Users\prusinma\Desktop\KeePassDatabase\Database.key";
var masterpw = "1234abcd";
Console.WriteLine("init done");
byte[] DBPathBytes = Encoding.ASCII.GetBytes(dbpath);
byte[] KeyPathBytes = Encoding.ASCII.GetBytes(keypath);
var ioConnection = IOConnectionInfo.FromByteArray(DBPathBytes);
var compositeKey = new CompositeKey();
compositeKey.AddUserKey(new KcpPassword(masterpw)); // Password
compositeKey.AddUserKey(new KcpKeyFile(IOConnectionInfo.FromByteArray(KeyPathBytes))); // Keyfile
var db = new PwDatabase();
db.Open(ioConnection, compositeKey, new NullStatusLogger());
var kpdata = from entry in db.RootGroup.GetEntries(true)
select new
{
Group = entry.ParentGroup.Name,
Title = entry.Strings.ReadSafe("Title"),
Username = entry.Strings.ReadSafe("UserName"),
Password = entry.Strings.ReadSafe("Password"),
URL = entry.Strings.ReadSafe("URL"),
Notes = entry.Strings.ReadSafe("Notes")
};
db.Save(new NullStatusLogger());
var contents = db.IOConnectionInfo.Bytes;
string bitString = BitConverter.ToString(contents);
Console.WriteLine(bitString);
Console.WriteLine(kpdata.ToString());
}
}
}
Those classes were moved into their own nuget package. Add it to your project and you should be good to go: https://www.nuget.org/packages/System.Drawing.Common/
From the project directory at the command line:
dotnet add package System.Drawing.Common
Closer inspection reveals ModernKeepPass targets.netstandard1.2 and will not work with 5's System.Drawing nuget package without being upgraded to target the new framework.
https://github.com/wismna/ModernKeePassLib/blob/master/ModernKeePassLib/ModernKeePassLib.csproj
<PropertyGroup>
<TargetFramework>netstandard1.2</TargetFramework>

I have a plain text file with a list of filenames inside, I need to search for a string on each file from the list. How can I do it? In C# [closed]

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 1 year ago.
Improve this question
I have this file named "Files.txt" which contains a list of file names inside:
------Files.TXT------
TS0001.000
TS0002.000
TS0003.000 ...
I need to look for the string "Process Error" inside of the files in the mentioned list and output the filename and the error to a new file as a log.
How can I do it? Complete newbie here :)
Thanks in advance!!
Your question does not provide complete information, so the solution may need to changed a bit based on your complete problem
using System;
using System.Collections.Generic;
using System.IO;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var path = #"c:\file.txt";
var outPath = #"c:\error.log";
var outs = new List<string>();
string fileText = File.ReadAllText(path);
foreach (var file in fileText.Split(" "))
{
var readText = File.ReadAllLines(#"C:\" + file);
foreach (string line in readText)
{
if (line.Contains("Process Error"))
{
outs.Add(file);
outs.Add(line);
}
}
}
File.WriteAllLines(outPath, outs);
}
}
}

Edit and Continue doesn't work with Roslyn compiled class library

Background
I'm trying to get Edit and Continue to work with a class library I'm compiling at runtime using Roslyn. This is for adding modding support to a game I'm developing.
Breakdown of problem
I have one class library project (A) with source files (.cs)
I have another console application project (B) in another solution that does the following:
Compiles all of project A's source files
Emits a dll and pdb
Loads the emitted dll and pdb via an assembly context
Calls a static method defined within project B
My desire is to be able to attach a debugger to a running process of project B in an instance of VS with project A loaded and be able to break, edit project A's code, and continue with my changes being executed
Currently, I am only able to break and continue
Any edits lead to the following notification:
This source file has changed. It no longer matches the version of the file used to build the application being debugged.
Source
Project A: DebuggableClassLibrary.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
</Project>
Project A: Test.cs
using System;
namespace DebuggableClassLibrary
{
public class Test
{
public static int Ct = 0;
public static void SayHello()
{
Ct++;
Console.WriteLine("Hello World");
}
}
}
Project B: DynamicLoading.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.8.0" />
</ItemGroup>
</Project>
Project B: Program.cs
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using System.Text;
namespace DynamicLoading
{
class Program
{
static void Main(string[] args)
{
var references = new MetadataReference[]
{
MetadataReference.CreateFromFile(Assembly.Load("System.Runtime").Location),
MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
MetadataReference.CreateFromFile(typeof(Console).Assembly.Location)
};
var files = Directory.GetFiles(#"C:\Users\mrbri\source\repos\DebuggableClassLibrary\DebuggableClassLibrary", "*.cs");
var assemblyName = "DebuggableClassLibrary.dll";
var debug = true;
var allowUnsafe = false;
var outputDirectory = #"C:\Users\mrbri\Documents\Test";
var preprocessorSymbols = debug ? new string[] { "DEBUG" } : new string[] { };
var parseOptions = new CSharpParseOptions(LanguageVersion.Latest, preprocessorSymbols: preprocessorSymbols);
var compilation = CSharpCompilation.Create(
assemblyName: assemblyName,
syntaxTrees: files.Select(f => SyntaxFactory.ParseSyntaxTree(File.ReadAllText(f), parseOptions, f, Encoding.UTF8)),
references: references,
options: new CSharpCompilationOptions(
OutputKind.DynamicallyLinkedLibrary,
assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default,
optimizationLevel: debug ? OptimizationLevel.Debug : OptimizationLevel.Release,
allowUnsafe: allowUnsafe
));
var pePath = Path.Combine(outputDirectory, assemblyName);
var pdbPath = Path.Combine(outputDirectory, Path.ChangeExtension(assemblyName, ".pdb"));
using (var peStream = new FileStream(pePath, FileMode.Create))
using (var pdbStream = new FileStream(pdbPath, FileMode.Create))
{
var results = compilation.Emit(
peStream: peStream,
pdbStream: pdbStream,
options: new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)
);
}
var assemblyLoadContext = new SimpleUnloadableAssemblyLoadContext();
var assembly = assemblyLoadContext.LoadFromStream(File.OpenRead(pePath), File.OpenRead(pdbPath));
var type = assembly.GetTypes().First();
var method = type.GetMethod("SayHello");
while (true)
{
method.Invoke(null, null);
}
}
}
internal class SimpleUnloadableAssemblyLoadContext : AssemblyLoadContext
{
public SimpleUnloadableAssemblyLoadContext(): base(true) { }
protected override Assembly Load(AssemblyName assemblyName) => null;
}
}
Attempts at solutions and observations
Compiling project A manually through VS and loading the generated pdb and dll exactly as I do for the Roslyn compiled one does allow for Edit and Continue
Comparing project A's dlls generated via Roslyn and VS in JetBrains dotPeek did yield some interesting differences that stem from the compilation time generated .NETCoreApp,Version=v5.0.AssemblyAttributes.cs and DebuggableClassLibrary.AssemblyInfo.cs that I do not include when I compile in project B
Going through the trouble of compiling project A via a MSBuildWorkspace Project did not allow Edit and Continue, although did include .NETCoreApp,Version=v5.0.AssemblyAttributes.cs and DebuggableClassLibrary.AssemblyInfo.cs
Alternatives
I am open to Roslyn alternatives/wrappers that do have Edit and Continue support.
Edit and Continue does not support this scenario. The project for the library being edited needs to be loaded in VS (in the current solution) and the program needs to be launched with the debugger attached.

Get ApplicationIcon from Code in NET Core 3.0

In the .csproj I assign an icon to my .NET Core 3.0 application:
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>netcoreapp3.0</TargetFramework>
<UseWindowsForms>true</UseWindowsForms>
<ApplicationIcon>C:\temp\myicon.ico</ApplicationIcon>
</PropertyGroup>
</Project>
The icon gets set for the generated exe file and shown in task-manager/file explorer.
How can I access this icon from code? I don't want to extract it from generated exe or add an additional resource icon.
you can extract like this
using System;
using System.Drawing; //For Icon
using System.Reflection; //For Assembly
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
try
{
//Gets the icon associated with the currently executing assembly
//(or pass a different file path and name for a different executable)
Icon appIcon = Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location);
}
catch(ArgumentException ae)
{
//handle
}
}
}
}
//We can use this statement.
using System.Drawing;
using System.Reflection;
static void Main(string[] args)
{
try
{
Icon appIcon = Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location);
}
catch(ArgumentException ae)
{
//handle
}

Getting ItemGroup collection and their Items from MSBuild xml

I want to know the name of the ItemGroup by parsing the below xml in dotnet c#. I tried various options but couldn't get it. Basically i want to know that there are ItemGroup , it can be more. Is there anyway we can load this xml and get the ItemGroups's list and their names.
Here i want the ItemGroup name as "cssfile_individual" , cssfile_individual2
<Project xmlns="http://schemas.microsoft.com/developer/MsBuild/2003">
<UsingTask TaskName="CssCompressorTask" AssemblyFile="Yahoo.Yui.Compressor.Build.MsBuild.dll" />
<UsingTask TaskName="JavaScriptCompressorTask" AssemblyFile="Yahoo.Yui.Compressor.Build.MsBuild.dll" />
<PropertyGroup>
</PropertyGroup>
<Target Name="Minify">
<ItemGroup>
<cssfile_individual Include="test1.css"/>
<cssfile_individual Include="test2.css"/>
<cssfile_individual Include="test3.css"/>
<cssfile_individual Include="test3.css"/>
</ItemGroup>
<ItemGroup>
<cssfile_individual2 Include="test1.css"/>
<cssfile_individual2 Include="test2.css"/>
<cssfile_individual2 Include="test3.css"/>
<cssfile_individual2 Include="test3.css"/>
</ItemGroup>
</Target>
</Project>
I tried as below
XmlDocument objXML = new XmlDocument();
objXML.Load(path);
and then started getting childs and all.
Sample XML looks like this
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/MsBuild/2003">
<UsingTask TaskName="CompressorTask"
AssemblyFile="D:\JsCssCompressor\JsCssCompressor\bin\Yahoo.Yui.Compressor.Build.MsBuild.dll" />
<Target Name="MyTaskTarget">
<ItemGroup>
<JavaScriptFiles Include="C:\Work\Purchase_Flow\eBizSol_App\Release\WebSites\Websites\McAfee.Consumer.Website\UIDesign\LegacySite\Scripts\FlexDashboard\AddDevice.js"/>
</ItemGroup>
<CompressorTask
JavaScriptCompressionType="YuiStockCompression"
JavaScriptFiles="#(JavaScriptFiles)"
ObfuscateJavaScript="True"
PreserveAllSemicolons="False"
DisableOptimizations="Nope"
EncodingType="Default"
DeleteJavaScriptFiles="false"
LineBreakPosition="-1"
JavaScriptOutputFile="C:\Work\Purchase_Flow\eBizSol_App\Release\WebSites\Websites\McAfee.Consumer.Website\UIDesign\LegacySite\Scripts\FlexDashboard\MAA2.0.js"
LoggingType="ALittleBit"
ThreadCulture="en-us"
IsEvalIgnored="false"
/>
</Target>
</Project>
Use LINQ to XML
XDocument objXML = new XDocument();
objXML.Load(path);
Your LINQ code will look something like this
var ItemGroups = from IG in objXML.Descendants("ItemGroup")
select new {
Children = LG.Descendants()
};
//Print Results
string str = "";
foreach (var IG in ItemGroups){
str += "Item Group Name: " + IG.Children[0].Name + Environment.NewLine;
foreach (var IGValue in IG.Children){
str += " " + IGValue.Attribute("Include").Value + Environment.NewLine;
}
}
References
MSDN for LINQ to XML Descendants
LINQ to read XML
Update
Here is a sample application.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace testapp_xdocument_linq
{
class Program
{
static void Main(string[] args)
{
XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003";
XDocument X = XDocument.Load("C:\\Users\\Brian\\Documents\\Visual Studio 2012\\Projects\\testapp_xdocument_linq\\testapp_xdocument_linq\\testapp_xdocument_linq.csproj");
var PropertyGroups = from PG in X.Descendants(ns + "PropertyGroup") select PG;
//Print Results
foreach (var element in PropertyGroups)
{
Console.WriteLine("First Descendant Name: " + element.Descendants().First().Name + Environment.NewLine);
}
Console.ReadLine();
}
}
}
This is a fresh C# console app. I am loading the project's own .csproj file.
I am not able to execute this code against your sample XML. I suspect this is because it breaks the schema defined by http://schemas.microsoft.com/developer/msbuild/2003.
You can use Microsoft.Build like this:
var pathToXml = #"<path>";
var nodes = ProjectRootElement.Open(pathToXml).AllChildren;
var itemGroupElements = nodes.OfType<ProjectItemGroupElement>();
And then grab the first child of each Item Group and get its name:
foreach (var itemGroup in itemGroupElements)
{
Console.WriteLine(itemGroup.FirstChild.ElementName);
}

Categories