dotnet regex to capture using, namespace and its content [closed] - c#

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 3 years ago.
Improve this question
I need a regular expression to capture the using section, the namespace name and the content of the block.
using ns1;
using ns2;
using alias = ns3.Class1;
namespace ns4
{
<content>
}
Each line ends with windows CRLF (\r\n).
I have something using notepad++ (with multiline option) (using.*?;)*(?:\r\n)*(namespace.*?)\r\n\{(.*?)\}(?:\r\n)*\z but it does not work in c# (I tried it here)
I have a console program that finds 2 class files in the same namespace, then combine their using, and namespace block content.

I would strongly advise against using regular expressions for dealing with source files. Regular expressions will just make things harder. Instead, I would advise using a parser, as properly noted by #Cid.
If I understand you correctly, you need to merge two C# source files. Here's my solution using a proper parser.
Let's imagine I have two files, F1.cs and F2.cs.
F1.cs:
using System.Text.RegularExpressions;
using alias = System.Int32;
namespace ConsoleApp3
{
public class DummyClass1
{
public alias DummyProperty { get; set; }
}
}
F2.cs
using System;
namespace ConsoleApp3
{
public class DummyClass2
{
public Int32 Kek { get; set; }
}
}
Here's a quick and dirty program I wrote that merges two C# files together using a parser (warning: not production quality code):
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
namespace ConsoleApp3
{
public static class Program
{
public static async Task Main(string[] args)
{
var sourceFiles = await Task.WhenAll( // reading input files
File.ReadAllTextAsync("F1.cs"),
File.ReadAllTextAsync("F2.cs"));
var tokensOfInterest = sourceFiles
// 1. parse source files
.Select(x => CSharpSyntaxTree.ParseText(x))
// 2. get file syntax tree root elements
.Select(x => x.GetRoot())
// 3. get all top-level using directives and namespace declarations
.SelectMany(root => root.ChildNodes().Where(node => node.Kind() == SyntaxKind.UsingDirective
|| node.Kind() == SyntaxKind.NamespaceDeclaration))
// 4. sort them so that usings come before namespace declarations
.OrderByDescending(x => x.Kind())
// 5. get raw token strings
.Select(x => x.ToString())
.ToArray();
var combined = string.Join(Environment.NewLine, tokensOfInterest);
Console.WriteLine(combined);
}
}
}
Here's how the output looks for my F1.cs and F2.cs files:
using System.Text.RegularExpressions;
using alias = System.Int32;
using System;
namespace ConsoleApp3
{
public class DummyClass1
{
public alias DummyProperty { get; set; }
}
}
namespace ConsoleApp3
{
public class DummyClass2
{
public Int32 Kek { get; set; }
}
}
Yeah... Two namespace declarations of the same namespace... Not pretty, but this is valid C#, so I didn't bother doing anything about it. This file compiles and works as you would expect.
Still, let me assure you - this approach is going to be much easier than wrestling with regular expressions' corner cases, and it only took me five to ten minutes to come up with this, and it's the first time I'm using a C# parser, so it's definitely not rocket science.
Oh, and you'll have to depend on Roslyn by installing Microsoft.CodeAnalysis.CSharp NuGet package. Though it's a small price to pay.

Related

c# xml replace xmlns:noNamespaceSchemaLocation with NS0:noNamespaceSchemaLocation

I have a requirement to generate a xml file with a C# MVC application, with the following attributes:
<File NS0:noNamespaceSchemaLocation="myXML.xsd" xmlns:NS0="http://www.w3.org/2001/XMLSchema-instance">
Notice that the noNamespaceSchemaLocation prefix is NS0
This is what I have right now:
<File xmlns:noNamespaceSchemaLocation="myXML.xsd" xmlns:NS0="http://www.w3.org/2001/XMLSchema-instance">
In my file the prefix is xmlns, this is the first time I need to generate xml files, so I don't know if it is an error in the requirement of if I am just missing something, I am adding the the properties using the XmlSerealizerNamespaces class
var xmlNameSpace = new XmlSerializerNamespaces();
xmlNameSpace.Add( "NS0", "http://www.w3.org/2001/XMLSchema-instance" );
xmlNameSpace.Add( "noNamespaceSchemaLocation", "myXML.xsd" );
The xmlns:NS0 attribute is a namespace declaration, and you have correctly added this to XmlSerializerNamesapces.
The NS0:noNamespaceSchemaLocation is just an attribute, this needs to be part of your model. So a very simple model:
public class File
{
[XmlAttribute("noNamespaceSchemaLocation",
Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
public string NoNamespaceSchemaLocation { get; set; } = "myXML.xsd"
}
Here you can see we define the attribute's name and namespace. The prefix for this namespace will be pulled from XmlSerializerNamespaces as NS0. The output will, when serialised, be:
<File xmlns:NS0="http://www.w3.org/2001/XMLSchema-instance" NS0:noNamespaceSchemaLocation="myXML.xsd" />
See this fiddle for a working demo.
I've given up using the Xml libraries to create the namespaces. Instead of just parse the string
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string xml = "<File NS0:noNamespaceSchemaLocation=\"myXML.xsd\" xmlns:NS0=\"http://www.w3.org/2001/XMLSchema-instance\"></File>";
XDocument doc = XDocument.Parse(xml);
}
}
}

How to read a json file stored online and change image to url when found

I am making an app in unity and i need the user to search for a keyword and it will return all the imageurls stored in an online json file that relate to that keyword (slug)
My colleague wrote me the below code, as she has way more knowledge with the language than me, but she doesnt use unity and i dont know if its suitable for unity or changing the texture of the image, as i cant seem to trigger it. The json file is currently stored in the project, but i would prefer it to read something that is online.
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class UrlOpener : MonoBehaviour
{
public string imageaddress;
public void Open()
{
using (StreamReader r = new StreamReader("Assets/document.json"))
{
string json = r.ReadToEnd();
var img= JsonUtility.FromJson<ArtImage>(json);
imageaddress = img.imageurl;
}
}
}
[Serializable]
class ArtImage
{
public string name { get; set; }
public string imageurl { get; set; }
}
You can use WebClient to download content of remote file:
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using UnityEngine;
public class UrlOpener : MonoBehaviour
{
public string imageaddress;
public void Open()
{
using (var client = new WebClient())
{
string json = client.DownloadString("http://www.example.com/some.json");
var img= JsonUtility.FromJson<ArtImage>(json);
imageaddress = img.imageurl;
}
}
}
Note that depending on .NET profile you are using, you may need to add assembly references for System.Net.WebClient.dll and System.Net.dll. You can find more details on how to add assembly references here.

I get an error in C# "The type or namespace name does not exist in namespace"

I get an error in C# "The type or namespace name does not exist in namespace". I checked everywhere but it didn't solve my problem here is the main program
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json;
using BlockChainMySelf;
using Formatting = Newtonsoft.Json.Formatting;
namespace BlockChainMySelf
{
class Program
{
static void Main(string[] args)
{
var startTime = DateTime.Now;
BlockChainMySelf.BlockChain StepCoin = new BlockChain();
StepCoin.CreateTransaction(new Transaction("Henry", "MaHesh", 10));
StepCoin.CreateTransaction(new Transaction("lkjsdf", "MaADLKHesh", 15));
StepCoin.CreateTransaction(new Transaction("Henry", "MaHesh", 20));
StepCoin.CreateTransaction(new Transaction("Henry", "MaHesh", 60));
StepCoin.ProcessPendingTransactions("Bill");
And here is the class that I want to call
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json;
using BlockChainMySelf;
using Formatting = Newtonsoft.Json.Formatting;
namespace BlockChainMySelf
{
public class BlockChain
{
IList<Transaction> PendingTransactions = new List<Transaction>();
public IList<Block> Chain { set; get; }
public int Difficulty { set; get; } = 2;
Here are the Screendhots
Main
Class
answerquestion
answerquestion2
The second screenshot in an earlier edit of your question clearly shows the BlockChain class as being 'Miscellaneous Files' in Visual Studio:
The MSDN page for the Miscellaneous Files Project says (emphasis mine):
When a user opens project items, the IDE assigns to the Miscellaneous Files project any items that are not members of any projects in a solution.
Presumably you were in the middle of trying to fix the issue, so you put static in - but that won't work because then you can't create an instance of a BlockChain.
Your question is a duplicate of Visual Studio - project shows up as “Miscellaneous Files”.
The/a solution is to right-click on the bad file in Solution Explorer, remove it from the project, then re-add it, e.g. this answer.
I had this issue... however, I had two classes under the same namespace but in different projects. All I had to do to fix this was to add a reference to the project directly.

C# - serializing list works, but deserializing returns empty list

I have an odd problem with XML deserialization in C#. Serializing the object works as expected, but deserializing makes the list-valued attribute Files empty.
using System;
using System.Collections.Generic;
using System.Xml.Linq;
using System.Xml.Serialization;
using System.Text;
namespace Converter
{
[Serializable]
[XmlRoot("userinput")]
public class Input
{
[XmlArray("files")]
[XmlArrayItem(Type = typeof(FilePair), ElementName = "filepair")]
public List<FilePair> Files;
public Input()
{ }
}
}
and the element:
using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.Xml.Serialization;
namespace Converter
{
[Serializable]
public class FilePair
{
[XmlElement("file1")]
public string File1;
[XmlElement("file2")]
public string File2;
public FilePair() { }
}
public enum FileSource { Foo, Bar };
}
and a sample XML:
<userinput>
<files>
<filepair>
<file1>foo</file1>
<file2>bar</file2>
</filepair>
<filepair>
<file1>foo</file1>
<file2>bar</file2>
</filepair>
</files>
</userinput>
If I take your code, fix the [XmlElement("file2")], and use:
var xml = #"<userinput>
<files>
<filepair>
<file1>foo</file1>
<file2>bar</file2>
</filepair>
<filepair>
<file1>foo</file1>
<file2>bar</file2>
</filepair>
</files>
</userinput>";
using (var reader = new StringReader(xml))
{
var obj = (Input)new XmlSerializer(typeof(Input)).Deserialize(reader);
foreach(var file in obj.Files)
{
Console.WriteLine($"{file.File1}, {file.File2}");
}
}
then: it works. The output is:
foo, bar
foo, bar
So: whatever the problem is: you've fixed it when creating your minimal sample.
So now the question becomes: what is different between your minimal sample and your real code? Answer that, and you'll answer the question for yourself.

How to log results to console with MongoDB 3.0 c# driver

I am writing the simple c# console program to connect mongodb db instance and get the value from the mongodb and need to display console window. I am using mongodb version 3.0.
I am getting date but not able display console. I am getting struck with syntax.
Any one please help me, I have shared my sample code below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB;
using MongoDB.Driver;
using MongoDB.Bson;
using MongoDB.Driver.Linq;
namespace MongoCHash
{
class Program
{
static void Main(string[] args)
{
var mongod = new MongoClient();
var db=mongod.GetDatabase("MyDB");
var movies = db.GetCollection<Movie>("movie");
}
}
public class Movie
{
public ObjectId Id { get; set; }
public string name { get; set; }
}
}
You have got a Movie object collection you need to iterate over the collection and the do a Console.Log() of what ever property of the movie object you want including date. If you want I can post an example.

Categories

Resources