I created a very very simple domain layer in visual studio (2010). I then used the new test wizard to create a basic unit test. However when I try to put in the using statement so that I can test my code.. it says my namespace could not be found... This is my first time using visual studio so I am at a loss as to what I am doing wrong.
My code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Home
{
class InventoryType
{
/// <summary>
/// Selects the inventory type and returns the selected value
/// </summary>
public class InventorySelect
{
private string inventoryTypes;
public String InventoryTypes
{
set
{
inventoryTypes = value;
}
get
{
return inventoryTypes;
}
}
/// <summary>
/// Validate that the inventory is returning some sort of value
/// </summary>
/// <returns></returns>
public bool Validate()
{
if (InventoryTypes == null) return false;
return true;
}
}
}
}
My Test Code
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Home.InventoryType.InventorySelect;
namespace HomeTest
{
[TestClass]
public class TestInventoryTypeCase
{
[TestMethod]
public void TestInventoryTypeClass()
{
InventorySelect select = new InventorySelect();
select.inventoryTypes = "Collection";
if (Validate() = true)
Console.WriteLine("Test Passed");
else
if (Validate() = false)
Console.WriteLine("Test Returned False");
else
Console.WriteLine("Test Failed To Run");
Console.ReadLine();
}
}
}
using refers to a namespace, not a specific class (unless you add an alias for the class name). Your using statement should only include the word Home.
using Home.InventoryType.InventorySelect;
//becomes
using Home;
Here is a link to MSDN on using directive: using Directive (C#)
I'm assuming your test class is in its own project, so you need to add a reference to that project. (A using statement doesn't add a reference, it merely allows you to use a type in your code without fully qualifying its name.)
Declare InventoryType class as public
InventorySelect class can be private rather than public
When you create a "multi-project" in a solution (by adding projects to any existing solution), the projects do not know about each other.
Go to your test project on Solution Explorer and under "References", right click and select "Add Reference". Then select "project" tab and you will be able to add your project's reference to the test project.
Also, make sure you define the classes in the project as "public" to be able to access them in test project.
namespace Home
{
public class InventoryType
{
...
}
}
Note that you still need the "using" keyword on top of your C# test class:
using Home;
namespace HomeTest
{
public class TestInventoryTypeCase
{
...
}
}
Related
I'm not even trying to test anything there yet, just wanted to create an instance of class Book(that I would like to test in the future) in my testing BookTests.cs file. I've added reference to GradeBook.Tests.csproj as whole source code to Gradebook is in the other folder. Yet it still returns CS0246 error : The type or namespace name 'Book' Could not be found.
Are you missing a using directive of assembly reference?
Gradebook.Tests.csproj with directory tree
using System.Collections.Generic;
namespace Gradebook
{
public class Book
{
private List<double> grades;
private string name;
public Book(string name)
{
this.name = name;
grades = new List<double>();
}
public void AddGrade(double grade)
{
grades.Add(grade);
}
}
}
Book.cs
using System;
using Xunit;
namespace GradeBook.Tests
{
public class BookTests
{
[Fact]
public void Test1()
{
//arrange
var book2 = new Book("test");
}
}
}
BookTests.cs
The code is pretty simple as I'm following Pluralsight course C# Fundamentals and I did everything like on the video. Tried also dotnet restore command. Path to project that contains Book.cs is probably correct(when i change something other errors occur). Working on VSC. What am I missing here?
I know it's been 2 months since this has last had an update, but the reason you're having an issue is because you're using the namespace Gradebook in Book.cs, but using GradeBook in BookTests.cs. (Notice the capital B)
Rename it so they're both Gradebook and ensure your directory names are correct and you should have no issues.
I have written an endpoint in ASP.net (which should give back a nice JSON) and the following error puzzles me since via my Swagger interface, everything works fine, but if I call the endpoint directly in a browser with http://localhost:63291/api/AutoUpload/, I receive:
Internal exception has occured: Type '<>f__AnonymousType2`6[System.String,System.DateTime]' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. If the type is a collection, consider marking it with the CollectionDataContractAttribute.
See the Microsoft .NET Framework documentation for other supported types.
This seems strange, because I was thinking that I did indeed implement a parameter-less (default) constructor. My code reads as follows
using AutoMapper;
using myProject.API.Filters;
using myProject.API.Models;
using myProject.Entity.DAL;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
namespace myProject.API.Controllers
{
[UserAuthenticationFilter]
public class AutoUploadController : BaseController
{
public AutoUploadController() {
System.Diagnostics.Debug.WriteLine("Parameterless default constructor only for serialization");
}
// GET: api/AutoUpload
[ResponseType(typeof(IEnumerable<FilesDetailsDto>))]
public IHttpActionResult GetAutoUpload(string OptionString = "status")
{
if (OptionString == "status")
{
var rootLocation = ConfigurationManager.AppSettings["ROOT-FOLDER-LOCATION"];
string[] entries = Directory.GetFiles(rootLocation, "*.csv", SearchOption.AllDirectories);
var convList = entries.Select(x => new
{
FullPath = x,
LastModifed = System.IO.File.GetLastWriteTime(x)
});
return Ok(convList.AsEnumerable());
} // end IF-clause for optional parameter
else
{
return NotFound();
}
}
}
}
The above piece of code uses the following data transfer object (DTO) definition:
using System;
namespace myProject.API.Models
{
public class FilesDetailsDto
{
public string FileName { get; set; }
public DateTime LastModifiedOnFilesystem { get; set; }
}
}
References
Datacontract exception. Cannot be serialized
You are returning collection of anonymous type instead of your actual type defined as attribute which can be the culprit for this error.
You can try to be more explicit when using the Select here something like:
var convList = entries.Select(x => new FilesDetailsDto()
{
FullPath = x,
LastModifiedOnFilesystem = System.IO.File.GetLastWriteTime(x)
});
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.
I am creating new module called "sms" in orchard cms using webmatrix. I create it successfully but when i generate "migrateions.cs", it doesn't generated successfully.
my sms.cs class in Model is given below
using System.Collections.Generic;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Records;
namespace SMSs.Model{
public class smsrecord:ContentPartRecord
{
public virtual int ID{get;set;}
public virtual string Name{get;set;}
public virtual char is_deleted{get;set;}
}
public class smspart:ContentPart<smsrecord>
{
[Required]
public int ID
{
get{return ID=Record.ID;}
set{Record.ID=value;}
}
public string Name
{
get{return Name=Record.Name;}
set{Record.Name=value;}
}
public char is_deleted
{
get{return is_deleted=Record.is_deleted;}
set{Record.is_deleted=value;}
}
}
and the generated Migrations.cs class is as follow
using System;
using System.Collections.Generic;
using System.Data;
using Orchard.ContentManagement.Drivers;
using Orchard.ContentManagement.MetaData;
using Orchard.ContentManagement.MetaData.Builders;
using Orchard.Core.Contents.Extensions;
using Orchard.Data.Migration;
namespace sms {
public class Migrations : DataMigrationImpl {
public int Create() {
return 1;
}
}
}
the "migrations.cs" is not generated successfully why?? Please help
Class itself is generated properly, although it lacks code for creating appropriate tables because you didn't adhere to naming conventions for your record class.
Data migration code generation requires you to follow several conventions in order for it to work properly. I.e.:
Namespace of a record must end with .Models or .Records
There has to exist a public property named Id
All properties have to be virtual (required by NHibernate anyway)
Class cannot be sealed
Class cannot be abstract
Class has to implement IContent or be a subclass of ContentPartRecord
In your case, the namespace (should end with .Models) and incorrect casing of ID (should be Id) are the culprits.
I started new project of Windows Forms. First page is UserLogin. in form load event I am taking the logintable from database into memory.
I am using a class in which all read and write operations methods are stored.
when I am calling the class in formload event, the error comes "doesnot exist in current context"
I may be missing some references or headerfilename..
Please Help
Thanks in Advance
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Web;
namespace InvestmentAndReturns
{
public partial class UserLogin : Form
{
public UserLogin()
{
InitializeComponent();
CenterToScreen();
}
public string UserID = null;
private string userPass = null;
public string UserGroup = null;
DataTable UserLoginTable;
int logintry = 1;
public bool LoginStatus = false;
private void Form1_Load(object sender, EventArgs e)
{
txtUserID.Select();
string cmd = "Select * from UserLogin";
UserLoginTable = DbRdRw.SqlDbRead(cmd, "UserLogin");
}
DbRdRw: this is the Class
SqlDbRead: this is read method
i have included that class by directly pasting it in the project folder and then opened solution and then included in the project
It looks like you have copy pasted source file containing definition of DbRdRw from some other project - which mostly means the namespace declaration in the file will be from older project.
Things will work if you change the namespace to your current project InvestmentAndReturns.
However, why are you copy pasting this around? You could make a library dll for your DbRdRw and reference the dll. That way you will keep your source code at one place.