Microsoft.VisualBasic does not work in VisualStudio 2017 class library project - visual-studio-2017

I am trying to create a class library in VS2017 in which I would like to use the TextFieldParser from Microsoft.VisualStudio. I had to add the direct reference to that dll C:\Program Files (x86)\Reference
I am also using the File class from System.IO
Assemblies\Microsoft\Framework.NETFramework\v4.6.2\Microsoft.VisualBasic.dll
But the build is failing with messages that do not make sense to me, some of which are
The name 'File' does not exist in the current context
The type 'Stream' is defined in an assembly that is not referenced. You must add a reference to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
The type 'TextReader' is defined in an assembly that is not referenced. You must add a reference to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
I am not sure if this is due to the new packaging of .NET standard version of the framework
What do I need to do to build the project? Thanks so much!
I have pasted my code below
public async Task<IEnumerable<Security>> GetSecuritiesAsync()
{
string[] lines;
using (var reader = File.OpenText("securities.csv"))
{
var fileText = await reader.ReadToEndAsync();
lines = fileText.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
}
//first line header
var securities = new List<Security>();
for (int i = 1; i < lines.Length; i++)
{
if (!string.IsNullOrEmpty(lines[i]))
{
string[] attrs = ParseCsv(lines[i]);
if (attrs.Length == 4)
{
var sec = new Security();
int id;
if (int.TryParse(attrs[0], out id))
{
sec.ID = id;
}
else
{
continue;
}
sec.Symbol = attrs[1];
sec.Name = attrs[2];
sec.Sector = attrs[3];
securities.Add(sec);
}
}
}
return securities;
}
private string[] ParseCsv(string line)
{
TextFieldParser parser = new TextFieldParser(new StringReader(line));
parser.HasFieldsEnclosedInQuotes = true;
parser.SetDelimiters(",");
string[] fields = null;
while (!parser.EndOfData)
{
fields = parser.ReadFields();
}
parser.Close();
return fields;
}
}

Related

Parameter applicationName must conform to the pattern (Google Report API)

I neet to get the google hangouts meet data by java code and I am trying the google report api
the following is my code
String userKey = "all";
String applicationName = "meet";
String eventName = "call_ended";
Activities result = service.activities().list(userKey, applicationName).setEventName(eventName).setMaxResults(10).execute();
and the response is
Parameter applicationName must conform to the pattern (admin)|(calendar)|(drive)|(login)|(token)
the api I am trying is this, i can get the data in this link by the same parameters
https://developers.google.com/admin-sdk/reports/v1/reference/activities/list
and I also can get the data by the following java code
public static String getGraph() {
String PROTECTED_RESOURCE_URL = "https://www.googleapis.com/admin/reports/v1/activity/users/all/applications/meet?eventName=call_ended&maxResults=10&access_token=";
String graph = "";
try {
URL urUserInfo = new URL(PROTECTED_RESOURCE_URL + "access_token");
HttpURLConnection connObtainUserInfo = (HttpURLConnection) urUserInfo.openConnection();
if (connObtainUserInfo.getResponseCode() == HttpURLConnection.HTTP_OK) {
StringBuilder sbLines = new StringBuilder("");
BufferedReader reader = new BufferedReader(
new InputStreamReader(connObtainUserInfo.getInputStream(), "utf-8"));
String strLine = "";
while ((strLine = reader.readLine()) != null) {
sbLines.append(strLine);
}
graph = sbLines.toString();
}
} catch (IOException ex) {
ex.printStackTrace();
}
return graph;
}
I think it's not a good solution and what i got is a complex string
Any solution please!?
This is a known bug already referenced on Google Issue Tracker; you can check it here.
Just use an old version of library google-api-services-admin-reports, I tested the following version:
com.google.apis:google-api-services-admin-reports:reports_v1-rev83-1.25.0
My gradle file:
apply plugin: 'java'
apply plugin: 'application'
mainClassName = 'SdkAdminQuickStart'
sourceCompatibility = 1.8
targetCompatibility = 1.8
version = '1.0'
repositories {
mavenCentral()
}
dependencies {
compile 'com.google.api-client:google-api-client:1.23.0'
compile 'com.google.oauth-client:google-oauth-client-jetty:1.23.0'
compile 'com.google.apis:google-api-services-admin-reports:reports_v1-rev83-1.25.0'
}

Roslyn - save edited document to physical solution

I'm trying to iterate through all documents, change some code and then rewrite analyzed document with new Syntax. The only problem I have it's that i don't know how to save changed document via workspace. After my code execution nothing happens.
var manager = new AnalyzerManager(slnPath);
foreach (var project in manager.Projects.Values)
{
var workspace = project.GetWorkspace();
var sln = workspace.CurrentSolution;
foreach (var msBuildProject in sln.Projects)
{
foreach (var document in msBuildProject.Documents)
{
var tree = await document.GetSyntaxTreeAsync();
var root = tree.GetRoot();
var compilation = await msBuildProject.GetCompilationAsync();
var walker = new CustomRewriter(compilation, tree);
var newRoot = walker.Visit(root);
if (!walker.Edited)
continue;
var editor = await DocumentEditor.CreateAsync(document);
editor.ReplaceNode(root, newRoot);
var newDocument = editor.GetChangedDocument();
workspace.TryApplyChanges(newDocument.Project.Solution);
break;
}
}
}
EDIT: Workspace is fetched with help of the Buildalyzer package.
Buildalyzer uses the adhoc workspace which does not persist changes. You want to use the MSBuildWorkspace.
You should have a project file that looks something like this
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net48</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Build.Locator" Version="1.2.6" />
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="2.9.8" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="3.3.1" />
<PackageReference Include="Microsoft.CodeAnalysis.VisualBasic.Workspaces" Version="3.3.1" />
<PackageReference Include="Microsoft.CodeAnalysis.Workspaces.MSBuild" Version="3.3.1" />
</ItemGroup>
</Project>
And then this is how I would load your solution and run your rewriter
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Build.Locator;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.MSBuild;
class Program {
static async Task Main(string[] args) {
// Attempt to set the version of MSBuild.
var visualStudioInstances = MSBuildLocator.QueryVisualStudioInstances().ToArray();
var instance = visualStudioInstances.Length == 1
// If there is only one instance of MSBuild on this machine, set that as the one to use.
? visualStudioInstances[0]
// Handle selecting the version of MSBuild you want to use.
: SelectVisualStudioInstance(visualStudioInstances);
Console.WriteLine($"Using MSBuild at '{instance.MSBuildPath}' to load projects.");
// NOTE: Be sure to register an instance with the MSBuildLocator
// before calling MSBuildWorkspace.Create()
// otherwise, MSBuildWorkspace won't MEF compose.
MSBuildLocator.RegisterInstance(instance);
using (var workspace = MSBuildWorkspace.Create()) {
// Print message for WorkspaceFailed event to help diagnosing project load failures.
workspace.WorkspaceFailed += (o, e) => Console.WriteLine(e.Diagnostic.Message);
var solutionPath = args[0];
Console.WriteLine($"Loading solution '{solutionPath}'");
// Attach progress reporter so we print projects as they are loaded.
var solution = await workspace.OpenSolutionAsync(solutionPath, new ConsoleProgressReporter());
Console.WriteLine($"Finished loading solution '{solutionPath}'");
// Run your custome re-writer on the loaded solution
foreach (var msBuildProject in solution.Projects) {
foreach (var document in msBuildProject.Documents) {
var tree = await document.GetSyntaxTreeAsync();
var root = tree.GetRoot();
var compilation = await msBuildProject.GetCompilationAsync();
var walker = new CustomRewriter(compilation, tree);
var newRoot = walker.Visit(root);
if (!walker.Edited)
continue;
var editor = await DocumentEditor.CreateAsync(document);
editor.ReplaceNode(root, newRoot);
var newDocument = editor.GetChangedDocument();
workspace.TryApplyChanges(newDocument.Project.Solution);
break;
}
}
}
}
private static VisualStudioInstance SelectVisualStudioInstance(VisualStudioInstance[] visualStudioInstances) {
Console.WriteLine("Multiple installs of MSBuild detected please select one:");
for (int i = 0; i < visualStudioInstances.Length; i++) {
Console.WriteLine($"Instance {i + 1}");
Console.WriteLine($" Name: {visualStudioInstances[i].Name}");
Console.WriteLine($" Version: {visualStudioInstances[i].Version}");
Console.WriteLine($" MSBuild Path: {visualStudioInstances[i].MSBuildPath}");
}
while (true) {
var userResponse = Console.ReadLine();
if (int.TryParse(userResponse, out int instanceNumber) &&
instanceNumber > 0 &&
instanceNumber <= visualStudioInstances.Length) {
return visualStudioInstances[instanceNumber - 1];
}
Console.WriteLine("Input not accepted, try again.");
}
}
private class ConsoleProgressReporter : IProgress<ProjectLoadProgress> {
public void Report(ProjectLoadProgress loadProgress) {
var projectDisplay = Path.GetFileName(loadProgress.FilePath);
if (loadProgress.TargetFramework != null) {
projectDisplay += $" ({loadProgress.TargetFramework})";
}
Console.WriteLine($"{loadProgress.Operation,-15} {loadProgress.ElapsedTime,-15:m\\:ss\\.fffffff} {projectDisplay}");
}
}
}

Unit test All the Actions Methods in Controller in .Net core visual studio 2017

public async Task<IActionResult> Create(DonorViewModel be, IFormFile pic)
{
be.RegCampId = Convert.ToInt32(TempData["Camp"]);
if (ModelState.IsValid)
{
DONOR entity = new DONOR();
#region Insert Entities
entity.Address = be.Address;
entity.BarCode = be.BarCode;
entity.BloodGroupId = be.BloodGroupId;
entity.CityId = be.CityId;
entity.CNIC = be.CNIC;
entity.DOB = be.DOB;
entity.Email = be.Email;
entity.EmergencyContact = be.EmergencyContact;
entity.FullName = be.FullName;
entity.GenderId = be.GenderId;
entity.HomeNo = be.HomeNo;
entity.IsActive = true;
entity.IsDeleted = false;
entity.LastDonDate = be.LastDonDate;
entity.MaritalStatus = be.MaritalStatus;
entity.MobileNo = be.MobileNo;
entity.Occupation = be.Occupation;
entity.PreDonCount = be.PreDonCount;
if (be.RegCampId != 0) { entity.RegCampId = be.RegCampId; entity.RegistrationTypeId = 3; }
if (be.RegLocId != 0) { entity.RegLocId = be.RegLocId; entity.RegistrationTypeId = 2; }
entity.SignPic = entity.SignPic;
entity.WhatsApp = be.WhatsApp;
entity.CreatedBy = (int)HttpContext.Session.GetInt32("UserId");
entity.CreatedDateTime = DateTime.Now;
#endregion
flag = await _donorContext.AddAsync(entity);
if (pic == null || pic.Length <= 0)
be.Pic = Path.Combine(_hostingEnvironment.WebRootPath, "images", "Avatar.png").Replace(_hostingEnvironment.WebRootPath, "").Replace("\\", "/");
if (pic != null && pic.Length > 0)
{
var path = Path.Combine(new string[]
{
_hostingEnvironment.WebRootPath,
"Reservoir","Donor",entity.Id.ToString(),
entity.Id + Path.GetExtension(pic.FileName)
});
Directory.CreateDirectory(Path.GetDirectoryName(path));
using (var stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
pic.CopyTo(stream);
}
path = path.Replace(_hostingEnvironment.WebRootPath, "").Replace("\\", "/");
entity.Pic = path;
entity.CreatedBy = entity.CreatedBy;
entity.CreatedDateTime = entity.CreatedDateTime;
entity.IsActive = true;
entity.IsDeleted = false;
await _donorContext.UpdateAsync(entity);
}
if (flag)
{
TempData["Message"] = "Donor is Added Successfully.";
if (be.RegCampId != 0)
{
return RedirectToAction("Create", "Donor", new { CampId = be.RegCampId });
}
else
{
return RedirectToAction("Create", "Donor");
}
}
}
ViewData["RegCampId"] = new SelectList(_context.BLOOD_CAMP, "Id", "City", be.RegCampId);
ViewData["BloodGroupId"] = new SelectList(_bloodGroupContext.GetAll(), "Id", "Value", be.BloodGroupId);
ViewData["CityId"] = new SelectList(_cityContext.GetAll(), "Id", "Name", be.CityId);
ViewData["ScreenedBy"] = new SelectList(_context.EMPLOYEE, "Id", "FirstName", be.ScreenedBy);
ViewData["GenderId"] = new SelectList(_genderContext.GetAll(), "Id", "Name", be.GenderId);
ViewData["RegLocId"] = new SelectList(_locationService.GetAll(), "Id", "Name",be.RegLocId);
return View(be);
}
This is My Create method In Controller How to unit test it using UnitTest.
using HMS_Presentation.Controllers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.VisualStudio.TestTools.UnitTesting;
//Unit Test code .
namespace HMS_UnitTest
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
DonorController Controller = new DonorController();
ViewResult result = Controller.Create() as ViewResult;
Assert.AreEqual("",????);
}
}
}
This is my unit test class code how to use my controller object to check the actions and test it . WHAT should i write the in the assert . I SEARCH it on internet but do not find any proper solution kindly check the code below and tell me what should i have to write in the assert . i am using visual studio 2017 and .NET CORE 2.0 AND adding a project of unit test in my solution.
The link i followed .
https://learn.microsoft.com/en-us/visualstudio/test/getting-started-with-unit-testing?view=vs-2017
In ASPNET Core 2.1 introduced feature called Functional testing of MVC applications.
To help streamline in-memory end-to-end testing of MVC applications using TestServer.
See below example
using Xunit;
namespace TestingMvc.Tests
{
public class TestingMvcFunctionalTests : IClassFixture<WebApplicationTestFixture<Startup>>
{
public TestingMvcFunctionalTests(WebApplicationTestFixture<Startup> fixture)
{
Client = fixture.CreateClient();
}
public HttpClient Client { get; }
[Fact]
public async Task GetHomePage()
{
// Arrange & Act
var response = await Client.GetAsync("/");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
}
Read more about functional testing of MVC Applications click here

Roslyn dynamic class generation issue

So I am trying to create a dynamic type (at runtime) using Roslyn. The entire back story to this requirement is too long to go into. I do however need to create a new type which has x many properties, where I am trying to feed in the property names and initial values from a Dictionary
Here is the relevant code
private void CreateAssembly(Dictionary<string, string> propertiesToEmit)
{
if (ourAssembly == null)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("using System;");
sb.AppendLine("public class MyClass");
sb.AppendLine("{");
sb.AppendLine(" public static void Main()");
sb.AppendLine(" {");
sb.AppendLine(" }");
foreach (var kvp in propertiesToEmit)
{
sb.AppendLine($" public {kvp.Value} {kvp.Key}" + " { get; set; }");
}
sb.AppendLine(" public MyClass CreateFromDynamic(Dictionary<string, object> sourceItem)");
sb.AppendLine(" {");
sb.AppendLine(" MyClass newOne = new MyClass();");
foreach (var kvp in propertiesToEmit)
{
sb.AppendLine($#" newOne.{kvp.Key} = sourceItem[""{kvp.Key}""];");
}
sb.AppendLine(" return newOne;");
sb.AppendLine(" }");
sb.AppendLine("}");
var tree = CSharpSyntaxTree.ParseText(sb.ToString());
var mscorlib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
var dictsLib = MetadataReference.CreateFromFile(typeof(Dictionary<,>).Assembly.Location);
var compilation = CSharpCompilation.Create("MyCompilation",
syntaxTrees: new[] { tree }, references: new[] { mscorlib, dictsLib });
//Emit to stream
var ms = new MemoryStream();
var emitResult = compilation.Emit(ms);
//Load into currently running assembly. Normally we'd probably
//want to do this in an AppDomain
ourAssembly = Assembly.Load(ms.ToArray());
}
}
I get this weird error with Roslyn where it can't seem to find a reference to Dictionary<,> even though this is inside mscorlib which is referenced.
It can clearly be seen that Dictionary<,> does live in a dll (namely mscorlib) that is referenced.
Any ideas?
Ok I found the answer, I forgot to add this using statement in code I was creating out using Roslyn
sb.AppendLine("using System.Collections.Generic;");

Compile to module with Roslyn

I need to compile any C# or VB.NET project to .NetModule. I have following sample code which emits DLLs, Need some help to modify following to get .NetModules out from .csproj
Thanks in advance.
// Required Microsoft.CodeAnalysis 1.3.0
class Program
{
static void Main(string[] args)
{
try
{
//Please copy provide a path to a .csproj
CompileProject(#"C:\WebGoat\WebGoat.NET.csproj", #"C:\tempout").Wait();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
async static Task<string> CompileProject(string projectFilePath, string outputFolderPath)
{
using (var workspace = MSBuildWorkspace.Create())
{
var project = workspace.OpenProjectAsync(projectFilePath).Result;
await Emit(project, outputFolderPath);
return Path.GetFileName(project.OutputFilePath);
}
}
async static Task Emit(Project project, string outputFolderPath)
{
Directory.CreateDirectory(outputFolderPath);
var compilation = await project.GetCompilationAsync();
var outputFilePath = Path.Combine(outputFolderPath, Path.GetFileName(project.OutputFilePath));
var pdbFilePath = Path.ChangeExtension(outputFilePath, "pdb");
var compilationStatus = compilation.Emit(outputFilePath, pdbPath: pdbFilePath);
if (!compilationStatus.Success)
{
Console.WriteLine("Failed.");
}
else
{
Console.WriteLine("Pass.");
}
}
I believe you're looking for CompilationOptions.OutputKind and specifically OutputKind.NetModule.
Something similar to the following should work:
var project = workspace.OpenProjectAsync(projectFilePath).Result;
var options = project.CompilationOptions;
var netModuleOptions = options.WithOutputKind(OutputKind.NetModule);
var projectWithOptions = project.WithCompilationOptions(netModuleOptions);
Now you should be able to get a compilation and emit it as you normally would.
Following fixed the issue
var project = workspace.OpenProjectAsync(projectFilePath).Result;
var options = project.CompilationOptions;
options = options.WithOutputKind(OutputKind.NetModule).WithPlatform(Platform.AnyCpu);
project = project.WithCompilationOptions(options);
var moduleCompilation = await project.GetCompilationAsync();